From b2496f3e2bf05c18475e98c57a0c598489e4842f Mon Sep 17 00:00:00 2001 From: =?utf8?q?Leonardo=20Fl=C3=B3rez-Valencia?= Date: Tue, 26 Sep 2017 08:46:18 -0500 Subject: [PATCH] ... --- CMakeLists.txt | 50 - appli/CMakeLists.txt | 10 - appli/PipelineEditor/CMakeLists.txt | 14 - appli/PipelineEditor/PipelineEditor.cxx | 157 - appli/PipelineEditor/PipelineEditor.h | 36 - appli/PipelineEditor/PipelineEditor.ui | 188 - bash/CMakeLists.txt | 25 - bash/Config.h.in | 274 - bash/CreateDemanglers.cxx | 121 - bash/CreateInstances.cxx | 168 - bash/CreateRealConfig.cxx | 37 - bash/HostCreator.cxx | 193 - cmake/BaseConfig.cmake | 51 - cmake/CMakeLists.txt | 11 - cmake/Functions.cmake | 328 - cmake/KitwareTools.cmake | 19 - cmake/Options.cmake | 25 - cmake/QtTools.cmake | 26 - cmake/cpPluginsConfig.cmake.in | 120 - data/data.wxml | 88 - data/read_write_image.wxml | 12 - dependencies/cpPlugins_Install_CMAKE.sh | 198 - .../cpPlugins_Install_Dependencies.py | 383 - dependencies/cpPlugins_Install_ITK.sh | 216 - dependencies/cpPlugins_Install_QT4.sh | 219 - dependencies/cpPlugins_Install_VTK.sh | 256 - .../cpPlugins_ThirdParty_Install_linux.sh | 317 - dependencies/dependencies.py | 328 - dependencies/qt-4.8.6_MAC.patch | 18 - install/macos/clean_libs.sh | 13 - install/macos/prepare_libs.sh | 46 - install/macos/relink_lib.sh | 36 - lib/CMakeLists.txt | 75 - lib/QCustomPlot/GPL.txt | 674 - lib/QCustomPlot/QCustomPlot.cxx | 23553 ---------------- lib/QCustomPlot/QCustomPlot.h | 3772 --- lib/QCustomPlot/changelog.txt | 432 - lib/cpBaseQtApplication/Blocker.cxx | 67 - lib/cpBaseQtApplication/Blocker.h | 30 - lib/cpBaseQtApplication/MainHelper.h | 90 - lib/cpBaseQtApplication/MainWindow.cxx | 309 - lib/cpBaseQtApplication/MainWindow.h | 136 - lib/cpBaseQtApplication/Pipeline/Block.cxx | 418 - lib/cpBaseQtApplication/Pipeline/Block.h | 120 - lib/cpBaseQtApplication/Pipeline/Canvas.cxx | 452 - lib/cpBaseQtApplication/Pipeline/Canvas.h | 83 - .../Pipeline/Connection.cxx | 135 - lib/cpBaseQtApplication/Pipeline/Connection.h | 60 - .../Pipeline/EventFilter.cxx | 227 - .../Pipeline/EventFilter.h | 96 - lib/cpBaseQtApplication/Pipeline/Port.cxx | 358 - lib/cpBaseQtApplication/Pipeline/Port.h | 216 - lib/cpBaseQtApplication/Plugins/Navigator.cxx | 92 - lib/cpBaseQtApplication/Plugins/Navigator.h | 39 - .../Algorithms/BezierCurveFunction.h | 77 - .../Algorithms/BezierCurveFunction.hxx | 155 - lib/cpExtensions/Algorithms/CPRImageFilter.h | 76 - .../Algorithms/CPRImageFilter.hxx | 127 - .../Algorithms/DiscontinuityMapImageFilter.h | 66 - .../DiscontinuityMapImageFilter.hxx | 91 - lib/cpExtensions/Algorithms/FluxMedialness.h | 74 - .../Algorithms/FluxMedialness.hxx | 108 - .../Algorithms/GaussianDensityImageFilter.h | 103 - .../Algorithms/GradientImageFunctionBase.h | 79 - .../Algorithms/GradientImageFunctionBase.hxx | 72 - .../Algorithms/GulsunTekMedialness.h | 76 - .../Algorithms/GulsunTekMedialness.hxx | 114 - lib/cpExtensions/Algorithms/ImageBlender.cxx | 234 - lib/cpExtensions/Algorithms/ImageBlender.h | 65 - .../Algorithms/ImageFunctionFilter.h | 69 - .../Algorithms/ImageFunctionFilter.hxx | 67 - .../Algorithms/ImageFunctorFilter.h | 68 - .../Algorithms/ImageFunctorFilter.hxx | 65 - .../ImageToBoundingBoxFromThreshold.h | 78 - .../ImageToBoundingBoxFromThreshold.hxx | 89 - .../Algorithms/InertiaMedialness.h | 215 - .../Algorithms/InertiaTensorFunction.h | 180 - lib/cpExtensions/Algorithms/IsoImageSlicer.h | 185 - .../Algorithms/IsoImageSlicer.hxx | 234 - .../IterativeGaussianModelEstimator.h | 171 - .../IterativeGaussianModelEstimator.hxx | 365 - .../Algorithms/KalmanConstantFilter.cxx | 49 - .../Algorithms/KalmanConstantFilter.h | 56 - lib/cpExtensions/Algorithms/KalmanFilter.cxx | 137 - lib/cpExtensions/Algorithms/KalmanFilter.h | 213 - lib/cpExtensions/Algorithms/KalmanFilter.hxx | 37 - .../Algorithms/KalmanVelocityFilter.cxx | 90 - .../Algorithms/KalmanVelocityFilter.h | 66 - .../Algorithms/LightCompensationFilter.h | 65 - .../Algorithms/LightCompensationFilter.hxx | 96 - lib/cpExtensions/Algorithms/MFluxMedialness.h | 74 - .../Algorithms/MFluxMedialness.hxx | 159 - .../Algorithms/MacheteImageFilter.h | 72 - .../Algorithms/MacheteImageFilter.hxx | 92 - .../MultiScaleGaussianImageFilter.h | 86 - .../MultiScaleGaussianImageFilter.hxx | 226 - .../Algorithms/ParallelImageMean.h | 70 - .../Algorithms/ParallelImageMean.hxx | 65 - .../PolyLineParametricPathToSimple3DCurve.cxx | 94 - .../PolyLineParametricPathToSimple3DCurve.h | 65 - .../Algorithms/PolyLineParametricPathWriter.h | 74 - .../PolyLineParametricPathWriter.hxx | 160 - .../Algorithms/RGBExtractFunction.h | 54 - .../RGBImageToOtherChannelsFilter.h | 67 - .../RGBImageToOtherChannelsFilter.hxx | 71 - .../Algorithms/RGBToHSVFunction.h | 87 - .../Algorithms/RGBToSingleChannelFunctor.h | 86 - .../Algorithms/RGBToSingleChannelFunctor.hxx | 188 - .../Algorithms/RGBToYPbPrFunction.h | 72 - .../Algorithms/RasterContourFilter.h | 105 - .../Algorithms/RasterContourFilter.hxx | 172 - .../RegionOfInterestImageCalculator.h | 73 - .../RegionOfInterestImageCalculator.hxx | 92 - lib/cpExtensions/Algorithms/SkeletonReader.h | 85 - .../Algorithms/SkeletonReader.hxx | 176 - .../Algorithms/SkeletonToImageFilter.h | 81 - .../Algorithms/SkeletonToImageFilter.hxx | 119 - lib/cpExtensions/Algorithms/SkeletonWriter.h | 69 - .../Algorithms/SkeletonWriter.hxx | 159 - .../Algorithms/SpatialObjectMaskImageFilter.h | 87 - .../SpatialObjectMaskImageFilter.hxx | 136 - .../Algorithms/UnaryThresholdImageFilter.h | 102 - .../Algorithms/UnaryThresholdImageFilter.hxx | 245 - lib/cpExtensions/Config.h.in | 70 - lib/cpExtensions/DataStructures/Graph.h | 166 - lib/cpExtensions/DataStructures/Graph.hxx | 267 - .../DataStructures/PolyLineParametricPath.h | 100 - .../DataStructures/PolyLineParametricPath.hxx | 215 - .../DataStructures/Simple3DCurve.cxx | 137 - .../DataStructures/Simple3DCurve.h | 75 - lib/cpExtensions/DataStructures/Skeleton.h | 62 - lib/cpExtensions/DataStructures/Skeleton.hxx | 94 - lib/cpExtensions/Interaction/BaseStyle.cxx | 437 - lib/cpExtensions/Interaction/BaseStyle.h | 193 - .../Interaction/ImageSlicePointPlacer.cxx | 275 - .../Interaction/ImageSlicePointPlacer.h | 78 - .../Interaction/ImageSliceStyle.cxx | 414 - .../Interaction/ImageSliceStyle.h | 88 - lib/cpExtensions/Interaction/SeedWidget.cxx | 165 - lib/cpExtensions/Interaction/SeedWidget.h | 63 - lib/cpExtensions/QT/ActorsWidgetInterface.h | 68 - lib/cpExtensions/QT/ConfigurationChooser.cxx | 51 - lib/cpExtensions/QT/ConfigurationChooser.h | 45 - lib/cpExtensions/QT/ConfigurationChooser.ui | 51 - lib/cpExtensions/QT/ImageWidget.cxx | 225 - lib/cpExtensions/QT/ImageWidget.h | 75 - lib/cpExtensions/QT/MPR3DWidget.cxx | 140 - lib/cpExtensions/QT/MPR3DWidget.h | 64 - lib/cpExtensions/QT/MPRInteractionCommand.cxx | 97 - lib/cpExtensions/QT/MPRInteractionCommand.h | 58 - lib/cpExtensions/QT/RendererWidget.cxx | 990 - lib/cpExtensions/QT/RendererWidget.h | 138 - lib/cpExtensions/QT/SimpleMPRWidget.cxx | 635 - lib/cpExtensions/QT/SimpleMPRWidget.h | 135 - lib/cpExtensions/QT/SimpleMPRWidget.ui | 48 - .../QT/WindowLevelImageConfiguration.cxx | 231 - .../QT/WindowLevelImageConfiguration.h | 56 - .../QT/WindowLevelImageConfiguration.ui | 216 - .../Visualization/CursorActors.cxx | 176 - lib/cpExtensions/Visualization/CursorActors.h | 70 - lib/cpExtensions/Visualization/ImageActor.cxx | 94 - lib/cpExtensions/Visualization/ImageActor.h | 62 - .../ImageIndexesContainerToPolyData.h | 71 - .../ImageIndexesContainerToPolyData.hxx | 188 - .../Visualization/ImageOutlineActor.cxx | 68 - .../Visualization/ImageOutlineActor.h | 59 - .../Visualization/ImageOutlineSource.cxx | 156 - .../Visualization/ImageOutlineSource.h | 53 - .../Visualization/ImageSliceActors.cxx | 174 - .../Visualization/ImageSliceActors.h | 74 - .../Visualization/ImageSliceMapper.cxx | 64 - .../Visualization/ImageSliceMapper.h | 43 - .../Visualization/ImageViewerActors.cxx | 169 - .../Visualization/ImageViewerActors.h | 64 - .../Visualization/LUTImageActor.cxx | 160 - .../Visualization/LUTImageActor.h | 78 - lib/cpExtensions/Visualization/LineSource.cxx | 119 - lib/cpExtensions/Visualization/LineSource.h | 66 - .../Visualization/MPR3DActors.cxx | 186 - lib/cpExtensions/Visualization/MPR3DActors.h | 85 - lib/cpExtensions/Visualization/MeshActor.cxx | 56 - lib/cpExtensions/Visualization/MeshActor.h | 45 - .../Visualization/OutlineSource.cxx | 50 - .../Visualization/OutlineSource.h | 48 - .../PolyLineParametricPathToPolyData.cxx | 131 - .../PolyLineParametricPathToPolyData.h | 60 - .../Visualization/Simple3DCurveToPolyData.cxx | 119 - .../Visualization/Simple3DCurveToPolyData.h | 60 - .../Visualization/SkeletonToPolyData.cxx | 147 - .../Visualization/SkeletonToPolyData.h | 60 - .../Visualization/WindowLevelImageActor.cxx | 200 - .../Visualization/WindowLevelImageActor.h | 66 - lib/cpInstances/BaseObjects/ITKBaseObjects.i | 41 - .../BaseObjects/ITKBoundingBoxes.i | 6 - lib/cpInstances/BaseObjects/ITKTransforms.i | 18 - lib/cpInstances/CMakeLists.txt | 50 - lib/cpInstances/DataObjects/BoundingBox.cxx | 93 - lib/cpInstances/DataObjects/BoundingBox.h | 107 - lib/cpInstances/DataObjects/Image.cxx | 196 - lib/cpInstances/DataObjects/Image.d | 27 - lib/cpInstances/DataObjects/Image.h | 71 - lib/cpInstances/DataObjects/Mesh.cxx | 180 - lib/cpInstances/DataObjects/Mesh.d | 4 - lib/cpInstances/DataObjects/Mesh.h | 53 - .../DataObjects/PolyLineParametricPath.cxx | 39 - .../DataObjects/PolyLineParametricPath.d | 4 - .../DataObjects/PolyLineParametricPath.h | 52 - lib/cpInstances/DataObjects/Simple3DCurve.cxx | 64 - lib/cpInstances/DataObjects/Simple3DCurve.d | 1 - lib/cpInstances/DataObjects/Simple3DCurve.h | 62 - lib/cpInstances/DataObjects/Skeleton.cxx | 39 - lib/cpInstances/DataObjects/Skeleton.d | 1 - lib/cpInstances/DataObjects/Skeleton.h | 50 - lib/cpInstances/Extensions/Paths.i | 11 - lib/cpInstances/Extensions/Skeleton.i | 8 - lib/cpInstances/Geometries/ITKMeshes.i | 16 - lib/cpInstances/Geometries/ITKPaths.i | 11 - lib/cpInstances/Images/ITK2VTKImageFilters.i | 20 - lib/cpInstances/Images/ITKBoxImageFilters.i | 10 - lib/cpInstances/Images/ITKImageFunctions.i | 13 - .../Images/ITKImageInterpolators.i | 23 - lib/cpInstances/Images/ITKImages.i | 41 - lib/cpInstances/Images/ITKImagesBaseFilters.i | 58 - .../Images/ITKImagesNeighborhoodIterators.i | 38 - .../Images/ITKImagesSimpleIterators.i | 27 - .../Images/itkImageToVTKImageFilter.h | 111 - .../Images/itkImageToVTKImageFilter.hxx | 141 - .../Images/itkVTKImageToImageFilter.h | 100 - .../Images/itkVTKImageToImageFilter.hxx | 107 - lib/cpPlugins/Config.h.in | 134 - lib/cpPlugins/Interface/Loader.cxx | 278 - lib/cpPlugins/Interface/Loader.h | 71 - lib/cpPlugins/Interface/Workspace.cxx | 638 - lib/cpPlugins/Interface/Workspace.h | 156 - lib/cpPlugins/Interface/WorkspaceIO.cxx | 315 - lib/cpPlugins/OS/Chrono.h | 15 - lib/cpPlugins/OS/DLLManager.cxx | 50 - lib/cpPlugins/OS/DLLManager.h | 27 - lib/cpPlugins/OS/FileSystem.cxx | 202 - lib/cpPlugins/OS/FileSystem.h | 60 - lib/cpPlugins/OS/String.cxx | 37 - lib/cpPlugins/OS/String.h | 28 - lib/cpPlugins/OS/tinydir.h | 806 - lib/cpPlugins/OS/tinydir_COPYING.txt | 26 - lib/cpPlugins/OS/tinydir_README.md.txt | 78 - lib/cpPlugins/Pipeline/DataObject.cxx | 92 - lib/cpPlugins/Pipeline/DataObject.h | 62 - lib/cpPlugins/Pipeline/Events.h | 51 - lib/cpPlugins/Pipeline/Functor.cxx | 16 - lib/cpPlugins/Pipeline/Functor.h | 64 - lib/cpPlugins/Pipeline/Object.cxx | 98 - lib/cpPlugins/Pipeline/Object.h | 105 - lib/cpPlugins/Pipeline/Parameters.cxx | 742 - lib/cpPlugins/Pipeline/Parameters.h | 223 - lib/cpPlugins/Pipeline/Port.cxx | 231 - lib/cpPlugins/Pipeline/Port.h | 127 - lib/cpPlugins/Pipeline/ProcessObject.cxx | 377 - lib/cpPlugins/Pipeline/ProcessObject.h | 168 - lib/cpPlugins/Pipeline/ProcessObject.hxx | 293 - lib/cpPlugins/Pipeline/Widget.cxx | 46 - lib/cpPlugins/Pipeline/Widget.h | 65 - lib/cpPlugins/QT/OpenFileDialog.cxx | 107 - lib/cpPlugins/QT/OpenFileDialog.h | 41 - lib/cpPlugins/QT/ParametersDialog.cxx | 888 - lib/cpPlugins/QT/ParametersDialog.h | 69 - lib/cpPlugins/QT/SaveFileDialog.cxx | 76 - lib/cpPlugins/QT/SaveFileDialog.h | 41 - lib/cpPlugins/tinyxml2/OLD_CMakeLists.txt.old | 32 - lib/cpPlugins/tinyxml2/readme.md | 324 - lib/cpPlugins/tinyxml2/tinyxml2.cpp | 2467 -- lib/cpPlugins/tinyxml2/tinyxml2.h | 2106 -- plugins/CMakeLists.txt | 59 - plugins/GenericPlugins/DataReproducer.cxx | 49 - plugins/GenericPlugins/DataReproducer.h | 33 - plugins/GenericPlugins/JoinBoundingBoxes.cxx | 44 - plugins/GenericPlugins/JoinBoundingBoxes.h | 25 - plugins/IO/ImageJSkeletonWriter.cxx | 104 - plugins/IO/ImageJSkeletonWriter.h | 28 - ...rvatureAnisotropicDiffusionImageFilter.cxx | 71 - ...CurvatureAnisotropicDiffusionImageFilter.h | 32 - .../ITKAnisotropicSmoothing.i | 12 - .../BinaryArithmeticImageFilter.cxx | 92 - .../BinaryArithmeticImageFilter.h | 32 - .../BinaryBooleanImageFilter.cxx | 74 - .../BinaryBooleanImageFilter.h | 32 - .../ITKBinaryFunctorFilters.i | 17 - .../BinaryContourImageFilter.cxx | 71 - .../BinaryContourImageFilter.h | 32 - .../ITKDistanceMapFilters.i | 15 - .../SignedMaurerDistanceMapImageFilter.cxx | 82 - .../SignedMaurerDistanceMapImageFilter.h | 32 - .../ITKFiniteDifference/ITKFiniteDifference.i | 15 - plugins/ITKIO/DicomSeriesReader.cxx | 102 - plugins/ITKIO/DicomSeriesReader.h | 23 - plugins/ITKIO/DicomSeriesReaderQDialog.h | 41 - plugins/ITKIO/DicomSeriesReaderQDialog.ui | 81 - plugins/ITKIO/DicomSeriesSelectorWidget.cxx | 182 - plugins/ITKIO/DicomSeriesSelectorWidget.h | 76 - plugins/ITKIO/DicomSeriesSelectorWidget.ui | 89 - plugins/ITKIO/ITKIO.i | 28 - plugins/ITKIO/ImageReader.cxx | 269 - plugins/ITKIO/ImageReader.h | 33 - plugins/ITKIO/ImageWriter.cxx | 93 - plugins/ITKIO/ImageWriter.h | 31 - .../CastImageFilter.cxx | 64 - .../CastImageFilter.h | 32 - .../ITKImageGenericFilters_1.i | 21 - .../ImageToBoundingBoxFromThreshold.cxx | 63 - .../ImageToBoundingBoxFromThreshold.h | 29 - .../MinimumMaximumImageCalculator.cxx | 120 - .../MinimumMaximumImageCalculator.h | 29 - .../RegionOfInterestImageFilter.cxx | 79 - .../RegionOfInterestImageFilter.h | 29 - .../BSplineInterpolateImageFunction.cxx | 62 - .../BSplineInterpolateImageFunction.h | 38 - .../ITKImageInterpolators.i | 25 - .../InterpolateImageFunction.cxx | 39 - .../InterpolateImageFunction.h | 54 - .../LinearInterpolateImageFunction.cxx | 58 - .../LinearInterpolateImageFunction.h | 38 - .../ITKLevelSetFilters/ITKLevelSetFilters.i | 28 - ...placianSegmentationLevelSetImageFilter.cxx | 72 - ...LaplacianSegmentationLevelSetImageFilter.h | 32 - ...resholdSegmentationLevelSetImageFilter.cxx | 76 - ...ThresholdSegmentationLevelSetImageFilter.h | 32 - plugins/ITKMorphology/ITKMorphology.i | 7 - .../ITKNeighborhoodOperatorFilters.i | 19 - .../BinaryDilateParaImageFilter.cxx | 52 - .../BinaryDilateParaImageFilter.h | 29 - .../BinaryErodeParaImageFilter.cxx | 52 - .../BinaryErodeParaImageFilter.h | 29 - plugins/ITKParaMorphology/ITKParaMorphology.i | 18 - plugins/ITKRasterFilters/ITKRasterFilters.i | 9 - .../ITKRasterFilters/RasterImageFilter.cxx | 160 - plugins/ITKRasterFilters/RasterImageFilter.h | 44 - .../ITKSeparableFilters/ITKSeparableFilters.i | 7 - .../SmoothingRecursiveGaussianImageFilter.cxx | 74 - .../SmoothingRecursiveGaussianImageFilter.h | 32 - plugins/ITKSliceFilters/CPRImageFilter.cxx | 63 - plugins/ITKSliceFilters/CPRImageFilter.h | 32 - plugins/ITKSliceFilters/ITKSliceFilters.i | 20 - .../IsoResampleImageFilter.cxx | 109 - .../ITKSliceFilters/IsoResampleImageFilter.h | 32 - .../ITKUnaryFunctorFilters/AbsImageFilter.cxx | 46 - .../ITKUnaryFunctorFilters/AbsImageFilter.h | 29 - .../BinaryThresholdImageFilter.cxx | 65 - .../BinaryThresholdImageFilter.h | 29 - .../ITKUnaryFunctorFilters.i | 33 - .../InvertIntensityImageFilter.cxx | 48 - .../InvertIntensityImageFilter.h | 29 - .../UnaryBooleanImageFilter.cxx | 49 - .../UnaryBooleanImageFilter.h | 29 - .../UnaryThresholdImageFilter.cxx | 57 - .../UnaryThresholdImageFilter.h | 29 - plugins/VTKFilters/CylinderSource.cxx | 35 - plugins/VTKFilters/CylinderSource.h | 25 - plugins/VTKFilters/MarchingCubes.cxx | 64 - plugins/VTKFilters/MarchingCubes.h | 25 - plugins/VTKFilters/SphereSource.cxx | 35 - plugins/VTKFilters/SphereSource.h | 26 - plugins/VTKIO/MeshReader.cxx | 60 - plugins/VTKIO/MeshReader.h | 24 - plugins/VTKIO/MeshWriter.cxx | 65 - plugins/VTKIO/MeshWriter.h | 24 - plugins/VTKWidgets/LineWidget.cxx | 173 - plugins/VTKWidgets/LineWidget.h | 40 - plugins/VTKWidgets/SeedWidget.cxx | 380 - plugins/VTKWidgets/SeedWidget.h | 82 - plugins/VTKWidgets/SplineWidget.cxx | 253 - plugins/VTKWidgets/SplineWidget.h | 83 - plugins/change.csv | 1 - .../DiscontinuityMapImageFilter.cxx | 49 - .../DiscontinuityMapImageFilter.h | 30 - plugins/cpExtensions/ImageFunctorFilter.cxx | 64 - plugins/cpExtensions/ImageFunctorFilter.h | 33 - .../PolyLineParametricPathToPolyData.cxx | 47 - .../PolyLineParametricPathToPolyData.h | 30 - .../PolyLineParametricPathToSimple3DCurve.cxx | 46 - .../PolyLineParametricPathToSimple3DCurve.h | 26 - .../PolyLineParametricPathWriter.cxx | 93 - .../PolyLineParametricPathWriter.h | 36 - plugins/cpExtensions/SkeletonReader.cxx | 93 - plugins/cpExtensions/SkeletonReader.h | 33 - .../cpExtensions/SkeletonToImageFilter.cxx | 54 - plugins/cpExtensions/SkeletonToImageFilter.h | 30 - plugins/cpExtensions/SkeletonWriter.cxx | 79 - plugins/cpExtensions/SkeletonWriter.h | 33 - plugins/cpExtensions/cpExtensions.i | 20 - tools/CMakeLists.txt | 29 - tools/ExecutePipeline.cxx | 45 - tools/PrintDirInfo.cxx | 56 - tools/PrintFileInfo.cxx | 56 - tools/PrintGuessInfo.cxx | 28 - tools/RenameImageFile.cxx | 62 - 394 files changed, 73077 deletions(-) delete mode 100644 CMakeLists.txt delete mode 100644 appli/CMakeLists.txt delete mode 100644 appli/PipelineEditor/CMakeLists.txt delete mode 100644 appli/PipelineEditor/PipelineEditor.cxx delete mode 100644 appli/PipelineEditor/PipelineEditor.h delete mode 100644 appli/PipelineEditor/PipelineEditor.ui delete mode 100644 bash/CMakeLists.txt delete mode 100644 bash/Config.h.in delete mode 100644 bash/CreateDemanglers.cxx delete mode 100644 bash/CreateInstances.cxx delete mode 100644 bash/CreateRealConfig.cxx delete mode 100644 bash/HostCreator.cxx delete mode 100644 cmake/BaseConfig.cmake delete mode 100644 cmake/CMakeLists.txt delete mode 100644 cmake/Functions.cmake delete mode 100644 cmake/KitwareTools.cmake delete mode 100644 cmake/Options.cmake delete mode 100644 cmake/QtTools.cmake delete mode 100644 cmake/cpPluginsConfig.cmake.in delete mode 100644 data/data.wxml delete mode 100644 data/read_write_image.wxml delete mode 100755 dependencies/cpPlugins_Install_CMAKE.sh delete mode 100644 dependencies/cpPlugins_Install_Dependencies.py delete mode 100755 dependencies/cpPlugins_Install_ITK.sh delete mode 100755 dependencies/cpPlugins_Install_QT4.sh delete mode 100755 dependencies/cpPlugins_Install_VTK.sh delete mode 100755 dependencies/cpPlugins_ThirdParty_Install_linux.sh delete mode 100644 dependencies/dependencies.py delete mode 100644 dependencies/qt-4.8.6_MAC.patch delete mode 100755 install/macos/clean_libs.sh delete mode 100755 install/macos/prepare_libs.sh delete mode 100755 install/macos/relink_lib.sh delete mode 100644 lib/CMakeLists.txt delete mode 100644 lib/QCustomPlot/GPL.txt delete mode 100644 lib/QCustomPlot/QCustomPlot.cxx delete mode 100644 lib/QCustomPlot/QCustomPlot.h delete mode 100644 lib/QCustomPlot/changelog.txt delete mode 100644 lib/cpBaseQtApplication/Blocker.cxx delete mode 100644 lib/cpBaseQtApplication/Blocker.h delete mode 100644 lib/cpBaseQtApplication/MainHelper.h delete mode 100644 lib/cpBaseQtApplication/MainWindow.cxx delete mode 100644 lib/cpBaseQtApplication/MainWindow.h delete mode 100644 lib/cpBaseQtApplication/Pipeline/Block.cxx delete mode 100644 lib/cpBaseQtApplication/Pipeline/Block.h delete mode 100644 lib/cpBaseQtApplication/Pipeline/Canvas.cxx delete mode 100644 lib/cpBaseQtApplication/Pipeline/Canvas.h delete mode 100644 lib/cpBaseQtApplication/Pipeline/Connection.cxx delete mode 100644 lib/cpBaseQtApplication/Pipeline/Connection.h delete mode 100644 lib/cpBaseQtApplication/Pipeline/EventFilter.cxx delete mode 100644 lib/cpBaseQtApplication/Pipeline/EventFilter.h delete mode 100644 lib/cpBaseQtApplication/Pipeline/Port.cxx delete mode 100644 lib/cpBaseQtApplication/Pipeline/Port.h delete mode 100644 lib/cpBaseQtApplication/Plugins/Navigator.cxx delete mode 100644 lib/cpBaseQtApplication/Plugins/Navigator.h delete mode 100644 lib/cpExtensions/Algorithms/BezierCurveFunction.h delete mode 100644 lib/cpExtensions/Algorithms/BezierCurveFunction.hxx delete mode 100644 lib/cpExtensions/Algorithms/CPRImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/CPRImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/FluxMedialness.h delete mode 100644 lib/cpExtensions/Algorithms/FluxMedialness.hxx delete mode 100644 lib/cpExtensions/Algorithms/GaussianDensityImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/GradientImageFunctionBase.h delete mode 100644 lib/cpExtensions/Algorithms/GradientImageFunctionBase.hxx delete mode 100644 lib/cpExtensions/Algorithms/GulsunTekMedialness.h delete mode 100644 lib/cpExtensions/Algorithms/GulsunTekMedialness.hxx delete mode 100644 lib/cpExtensions/Algorithms/ImageBlender.cxx delete mode 100644 lib/cpExtensions/Algorithms/ImageBlender.h delete mode 100644 lib/cpExtensions/Algorithms/ImageFunctionFilter.h delete mode 100644 lib/cpExtensions/Algorithms/ImageFunctionFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/ImageFunctorFilter.h delete mode 100644 lib/cpExtensions/Algorithms/ImageFunctorFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.h delete mode 100644 lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.hxx delete mode 100644 lib/cpExtensions/Algorithms/InertiaMedialness.h delete mode 100644 lib/cpExtensions/Algorithms/InertiaTensorFunction.h delete mode 100644 lib/cpExtensions/Algorithms/IsoImageSlicer.h delete mode 100644 lib/cpExtensions/Algorithms/IsoImageSlicer.hxx delete mode 100644 lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.h delete mode 100644 lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.hxx delete mode 100644 lib/cpExtensions/Algorithms/KalmanConstantFilter.cxx delete mode 100644 lib/cpExtensions/Algorithms/KalmanConstantFilter.h delete mode 100644 lib/cpExtensions/Algorithms/KalmanFilter.cxx delete mode 100644 lib/cpExtensions/Algorithms/KalmanFilter.h delete mode 100644 lib/cpExtensions/Algorithms/KalmanFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/KalmanVelocityFilter.cxx delete mode 100644 lib/cpExtensions/Algorithms/KalmanVelocityFilter.h delete mode 100644 lib/cpExtensions/Algorithms/LightCompensationFilter.h delete mode 100644 lib/cpExtensions/Algorithms/LightCompensationFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/MFluxMedialness.h delete mode 100644 lib/cpExtensions/Algorithms/MFluxMedialness.hxx delete mode 100644 lib/cpExtensions/Algorithms/MacheteImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/MacheteImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/ParallelImageMean.h delete mode 100644 lib/cpExtensions/Algorithms/ParallelImageMean.hxx delete mode 100644 lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.cxx delete mode 100644 lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.h delete mode 100644 lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.h delete mode 100644 lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.hxx delete mode 100644 lib/cpExtensions/Algorithms/RGBExtractFunction.h delete mode 100644 lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.h delete mode 100644 lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/RGBToHSVFunction.h delete mode 100644 lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.h delete mode 100644 lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.hxx delete mode 100644 lib/cpExtensions/Algorithms/RGBToYPbPrFunction.h delete mode 100644 lib/cpExtensions/Algorithms/RasterContourFilter.h delete mode 100644 lib/cpExtensions/Algorithms/RasterContourFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.h delete mode 100644 lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.hxx delete mode 100644 lib/cpExtensions/Algorithms/SkeletonReader.h delete mode 100644 lib/cpExtensions/Algorithms/SkeletonReader.hxx delete mode 100644 lib/cpExtensions/Algorithms/SkeletonToImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/SkeletonToImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/SkeletonWriter.h delete mode 100644 lib/cpExtensions/Algorithms/SkeletonWriter.hxx delete mode 100644 lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.hxx delete mode 100644 lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.h delete mode 100644 lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.hxx delete mode 100644 lib/cpExtensions/Config.h.in delete mode 100644 lib/cpExtensions/DataStructures/Graph.h delete mode 100644 lib/cpExtensions/DataStructures/Graph.hxx delete mode 100644 lib/cpExtensions/DataStructures/PolyLineParametricPath.h delete mode 100644 lib/cpExtensions/DataStructures/PolyLineParametricPath.hxx delete mode 100644 lib/cpExtensions/DataStructures/Simple3DCurve.cxx delete mode 100644 lib/cpExtensions/DataStructures/Simple3DCurve.h delete mode 100644 lib/cpExtensions/DataStructures/Skeleton.h delete mode 100644 lib/cpExtensions/DataStructures/Skeleton.hxx delete mode 100644 lib/cpExtensions/Interaction/BaseStyle.cxx delete mode 100644 lib/cpExtensions/Interaction/BaseStyle.h delete mode 100644 lib/cpExtensions/Interaction/ImageSlicePointPlacer.cxx delete mode 100644 lib/cpExtensions/Interaction/ImageSlicePointPlacer.h delete mode 100644 lib/cpExtensions/Interaction/ImageSliceStyle.cxx delete mode 100644 lib/cpExtensions/Interaction/ImageSliceStyle.h delete mode 100644 lib/cpExtensions/Interaction/SeedWidget.cxx delete mode 100644 lib/cpExtensions/Interaction/SeedWidget.h delete mode 100644 lib/cpExtensions/QT/ActorsWidgetInterface.h delete mode 100644 lib/cpExtensions/QT/ConfigurationChooser.cxx delete mode 100644 lib/cpExtensions/QT/ConfigurationChooser.h delete mode 100644 lib/cpExtensions/QT/ConfigurationChooser.ui delete mode 100644 lib/cpExtensions/QT/ImageWidget.cxx delete mode 100644 lib/cpExtensions/QT/ImageWidget.h delete mode 100644 lib/cpExtensions/QT/MPR3DWidget.cxx delete mode 100644 lib/cpExtensions/QT/MPR3DWidget.h delete mode 100644 lib/cpExtensions/QT/MPRInteractionCommand.cxx delete mode 100644 lib/cpExtensions/QT/MPRInteractionCommand.h delete mode 100644 lib/cpExtensions/QT/RendererWidget.cxx delete mode 100644 lib/cpExtensions/QT/RendererWidget.h delete mode 100644 lib/cpExtensions/QT/SimpleMPRWidget.cxx delete mode 100644 lib/cpExtensions/QT/SimpleMPRWidget.h delete mode 100644 lib/cpExtensions/QT/SimpleMPRWidget.ui delete mode 100644 lib/cpExtensions/QT/WindowLevelImageConfiguration.cxx delete mode 100644 lib/cpExtensions/QT/WindowLevelImageConfiguration.h delete mode 100644 lib/cpExtensions/QT/WindowLevelImageConfiguration.ui delete mode 100644 lib/cpExtensions/Visualization/CursorActors.cxx delete mode 100644 lib/cpExtensions/Visualization/CursorActors.h delete mode 100644 lib/cpExtensions/Visualization/ImageActor.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageActor.h delete mode 100644 lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.h delete mode 100644 lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.hxx delete mode 100644 lib/cpExtensions/Visualization/ImageOutlineActor.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageOutlineActor.h delete mode 100644 lib/cpExtensions/Visualization/ImageOutlineSource.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageOutlineSource.h delete mode 100644 lib/cpExtensions/Visualization/ImageSliceActors.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageSliceActors.h delete mode 100644 lib/cpExtensions/Visualization/ImageSliceMapper.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageSliceMapper.h delete mode 100644 lib/cpExtensions/Visualization/ImageViewerActors.cxx delete mode 100644 lib/cpExtensions/Visualization/ImageViewerActors.h delete mode 100644 lib/cpExtensions/Visualization/LUTImageActor.cxx delete mode 100644 lib/cpExtensions/Visualization/LUTImageActor.h delete mode 100644 lib/cpExtensions/Visualization/LineSource.cxx delete mode 100644 lib/cpExtensions/Visualization/LineSource.h delete mode 100644 lib/cpExtensions/Visualization/MPR3DActors.cxx delete mode 100644 lib/cpExtensions/Visualization/MPR3DActors.h delete mode 100644 lib/cpExtensions/Visualization/MeshActor.cxx delete mode 100644 lib/cpExtensions/Visualization/MeshActor.h delete mode 100644 lib/cpExtensions/Visualization/OutlineSource.cxx delete mode 100644 lib/cpExtensions/Visualization/OutlineSource.h delete mode 100644 lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.cxx delete mode 100644 lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.h delete mode 100644 lib/cpExtensions/Visualization/Simple3DCurveToPolyData.cxx delete mode 100644 lib/cpExtensions/Visualization/Simple3DCurveToPolyData.h delete mode 100644 lib/cpExtensions/Visualization/SkeletonToPolyData.cxx delete mode 100644 lib/cpExtensions/Visualization/SkeletonToPolyData.h delete mode 100644 lib/cpExtensions/Visualization/WindowLevelImageActor.cxx delete mode 100644 lib/cpExtensions/Visualization/WindowLevelImageActor.h delete mode 100644 lib/cpInstances/BaseObjects/ITKBaseObjects.i delete mode 100644 lib/cpInstances/BaseObjects/ITKBoundingBoxes.i delete mode 100644 lib/cpInstances/BaseObjects/ITKTransforms.i delete mode 100644 lib/cpInstances/CMakeLists.txt delete mode 100644 lib/cpInstances/DataObjects/BoundingBox.cxx delete mode 100644 lib/cpInstances/DataObjects/BoundingBox.h delete mode 100644 lib/cpInstances/DataObjects/Image.cxx delete mode 100644 lib/cpInstances/DataObjects/Image.d delete mode 100644 lib/cpInstances/DataObjects/Image.h delete mode 100644 lib/cpInstances/DataObjects/Mesh.cxx delete mode 100644 lib/cpInstances/DataObjects/Mesh.d delete mode 100644 lib/cpInstances/DataObjects/Mesh.h delete mode 100644 lib/cpInstances/DataObjects/PolyLineParametricPath.cxx delete mode 100644 lib/cpInstances/DataObjects/PolyLineParametricPath.d delete mode 100644 lib/cpInstances/DataObjects/PolyLineParametricPath.h delete mode 100644 lib/cpInstances/DataObjects/Simple3DCurve.cxx delete mode 100644 lib/cpInstances/DataObjects/Simple3DCurve.d delete mode 100644 lib/cpInstances/DataObjects/Simple3DCurve.h delete mode 100644 lib/cpInstances/DataObjects/Skeleton.cxx delete mode 100644 lib/cpInstances/DataObjects/Skeleton.d delete mode 100644 lib/cpInstances/DataObjects/Skeleton.h delete mode 100644 lib/cpInstances/Extensions/Paths.i delete mode 100644 lib/cpInstances/Extensions/Skeleton.i delete mode 100644 lib/cpInstances/Geometries/ITKMeshes.i delete mode 100644 lib/cpInstances/Geometries/ITKPaths.i delete mode 100644 lib/cpInstances/Images/ITK2VTKImageFilters.i delete mode 100644 lib/cpInstances/Images/ITKBoxImageFilters.i delete mode 100644 lib/cpInstances/Images/ITKImageFunctions.i delete mode 100644 lib/cpInstances/Images/ITKImageInterpolators.i delete mode 100644 lib/cpInstances/Images/ITKImages.i delete mode 100644 lib/cpInstances/Images/ITKImagesBaseFilters.i delete mode 100644 lib/cpInstances/Images/ITKImagesNeighborhoodIterators.i delete mode 100644 lib/cpInstances/Images/ITKImagesSimpleIterators.i delete mode 100644 lib/cpInstances/Images/itkImageToVTKImageFilter.h delete mode 100644 lib/cpInstances/Images/itkImageToVTKImageFilter.hxx delete mode 100644 lib/cpInstances/Images/itkVTKImageToImageFilter.h delete mode 100644 lib/cpInstances/Images/itkVTKImageToImageFilter.hxx delete mode 100644 lib/cpPlugins/Config.h.in delete mode 100644 lib/cpPlugins/Interface/Loader.cxx delete mode 100644 lib/cpPlugins/Interface/Loader.h delete mode 100644 lib/cpPlugins/Interface/Workspace.cxx delete mode 100644 lib/cpPlugins/Interface/Workspace.h delete mode 100644 lib/cpPlugins/Interface/WorkspaceIO.cxx delete mode 100644 lib/cpPlugins/OS/Chrono.h delete mode 100644 lib/cpPlugins/OS/DLLManager.cxx delete mode 100644 lib/cpPlugins/OS/DLLManager.h delete mode 100644 lib/cpPlugins/OS/FileSystem.cxx delete mode 100644 lib/cpPlugins/OS/FileSystem.h delete mode 100644 lib/cpPlugins/OS/String.cxx delete mode 100644 lib/cpPlugins/OS/String.h delete mode 100644 lib/cpPlugins/OS/tinydir.h delete mode 100644 lib/cpPlugins/OS/tinydir_COPYING.txt delete mode 100644 lib/cpPlugins/OS/tinydir_README.md.txt delete mode 100644 lib/cpPlugins/Pipeline/DataObject.cxx delete mode 100644 lib/cpPlugins/Pipeline/DataObject.h delete mode 100644 lib/cpPlugins/Pipeline/Events.h delete mode 100644 lib/cpPlugins/Pipeline/Functor.cxx delete mode 100644 lib/cpPlugins/Pipeline/Functor.h delete mode 100644 lib/cpPlugins/Pipeline/Object.cxx delete mode 100644 lib/cpPlugins/Pipeline/Object.h delete mode 100644 lib/cpPlugins/Pipeline/Parameters.cxx delete mode 100644 lib/cpPlugins/Pipeline/Parameters.h delete mode 100644 lib/cpPlugins/Pipeline/Port.cxx delete mode 100644 lib/cpPlugins/Pipeline/Port.h delete mode 100644 lib/cpPlugins/Pipeline/ProcessObject.cxx delete mode 100644 lib/cpPlugins/Pipeline/ProcessObject.h delete mode 100644 lib/cpPlugins/Pipeline/ProcessObject.hxx delete mode 100644 lib/cpPlugins/Pipeline/Widget.cxx delete mode 100644 lib/cpPlugins/Pipeline/Widget.h delete mode 100644 lib/cpPlugins/QT/OpenFileDialog.cxx delete mode 100644 lib/cpPlugins/QT/OpenFileDialog.h delete mode 100644 lib/cpPlugins/QT/ParametersDialog.cxx delete mode 100644 lib/cpPlugins/QT/ParametersDialog.h delete mode 100644 lib/cpPlugins/QT/SaveFileDialog.cxx delete mode 100644 lib/cpPlugins/QT/SaveFileDialog.h delete mode 100644 lib/cpPlugins/tinyxml2/OLD_CMakeLists.txt.old delete mode 100644 lib/cpPlugins/tinyxml2/readme.md delete mode 100644 lib/cpPlugins/tinyxml2/tinyxml2.cpp delete mode 100644 lib/cpPlugins/tinyxml2/tinyxml2.h delete mode 100644 plugins/CMakeLists.txt delete mode 100644 plugins/GenericPlugins/DataReproducer.cxx delete mode 100644 plugins/GenericPlugins/DataReproducer.h delete mode 100644 plugins/GenericPlugins/JoinBoundingBoxes.cxx delete mode 100644 plugins/GenericPlugins/JoinBoundingBoxes.h delete mode 100644 plugins/IO/ImageJSkeletonWriter.cxx delete mode 100644 plugins/IO/ImageJSkeletonWriter.h delete mode 100644 plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.cxx delete mode 100644 plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.h delete mode 100644 plugins/ITKAnisotropicSmoothing/ITKAnisotropicSmoothing.i delete mode 100644 plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.cxx delete mode 100644 plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.h delete mode 100644 plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.cxx delete mode 100644 plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.h delete mode 100644 plugins/ITKBinaryFunctorFilters/ITKBinaryFunctorFilters.i delete mode 100644 plugins/ITKDistanceMapFilters/BinaryContourImageFilter.cxx delete mode 100644 plugins/ITKDistanceMapFilters/BinaryContourImageFilter.h delete mode 100644 plugins/ITKDistanceMapFilters/ITKDistanceMapFilters.i delete mode 100644 plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.cxx delete mode 100644 plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.h delete mode 100644 plugins/ITKFiniteDifference/ITKFiniteDifference.i delete mode 100644 plugins/ITKIO/DicomSeriesReader.cxx delete mode 100644 plugins/ITKIO/DicomSeriesReader.h delete mode 100644 plugins/ITKIO/DicomSeriesReaderQDialog.h delete mode 100644 plugins/ITKIO/DicomSeriesReaderQDialog.ui delete mode 100644 plugins/ITKIO/DicomSeriesSelectorWidget.cxx delete mode 100644 plugins/ITKIO/DicomSeriesSelectorWidget.h delete mode 100644 plugins/ITKIO/DicomSeriesSelectorWidget.ui delete mode 100644 plugins/ITKIO/ITKIO.i delete mode 100644 plugins/ITKIO/ImageReader.cxx delete mode 100644 plugins/ITKIO/ImageReader.h delete mode 100644 plugins/ITKIO/ImageWriter.cxx delete mode 100644 plugins/ITKIO/ImageWriter.h delete mode 100644 plugins/ITKImageGenericFilters_1/CastImageFilter.cxx delete mode 100644 plugins/ITKImageGenericFilters_1/CastImageFilter.h delete mode 100644 plugins/ITKImageGenericFilters_1/ITKImageGenericFilters_1.i delete mode 100644 plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.cxx delete mode 100644 plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.h delete mode 100644 plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.cxx delete mode 100644 plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.h delete mode 100644 plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.cxx delete mode 100644 plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.h delete mode 100644 plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.cxx delete mode 100644 plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.h delete mode 100644 plugins/ITKImageInterpolators/ITKImageInterpolators.i delete mode 100644 plugins/ITKImageInterpolators/InterpolateImageFunction.cxx delete mode 100644 plugins/ITKImageInterpolators/InterpolateImageFunction.h delete mode 100644 plugins/ITKImageInterpolators/LinearInterpolateImageFunction.cxx delete mode 100644 plugins/ITKImageInterpolators/LinearInterpolateImageFunction.h delete mode 100644 plugins/ITKLevelSetFilters/ITKLevelSetFilters.i delete mode 100644 plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.cxx delete mode 100644 plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.h delete mode 100644 plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.cxx delete mode 100644 plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.h delete mode 100644 plugins/ITKMorphology/ITKMorphology.i delete mode 100644 plugins/ITKNeighborhoodOperatorFilters/ITKNeighborhoodOperatorFilters.i delete mode 100644 plugins/ITKParaMorphology/BinaryDilateParaImageFilter.cxx delete mode 100644 plugins/ITKParaMorphology/BinaryDilateParaImageFilter.h delete mode 100644 plugins/ITKParaMorphology/BinaryErodeParaImageFilter.cxx delete mode 100644 plugins/ITKParaMorphology/BinaryErodeParaImageFilter.h delete mode 100644 plugins/ITKParaMorphology/ITKParaMorphology.i delete mode 100644 plugins/ITKRasterFilters/ITKRasterFilters.i delete mode 100644 plugins/ITKRasterFilters/RasterImageFilter.cxx delete mode 100644 plugins/ITKRasterFilters/RasterImageFilter.h delete mode 100644 plugins/ITKSeparableFilters/ITKSeparableFilters.i delete mode 100644 plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.cxx delete mode 100644 plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.h delete mode 100644 plugins/ITKSliceFilters/CPRImageFilter.cxx delete mode 100644 plugins/ITKSliceFilters/CPRImageFilter.h delete mode 100644 plugins/ITKSliceFilters/ITKSliceFilters.i delete mode 100644 plugins/ITKSliceFilters/IsoResampleImageFilter.cxx delete mode 100644 plugins/ITKSliceFilters/IsoResampleImageFilter.h delete mode 100644 plugins/ITKUnaryFunctorFilters/AbsImageFilter.cxx delete mode 100644 plugins/ITKUnaryFunctorFilters/AbsImageFilter.h delete mode 100644 plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.cxx delete mode 100644 plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.h delete mode 100644 plugins/ITKUnaryFunctorFilters/ITKUnaryFunctorFilters.i delete mode 100644 plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.cxx delete mode 100644 plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.h delete mode 100644 plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.cxx delete mode 100644 plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.h delete mode 100644 plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.cxx delete mode 100644 plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.h delete mode 100644 plugins/VTKFilters/CylinderSource.cxx delete mode 100644 plugins/VTKFilters/CylinderSource.h delete mode 100644 plugins/VTKFilters/MarchingCubes.cxx delete mode 100644 plugins/VTKFilters/MarchingCubes.h delete mode 100644 plugins/VTKFilters/SphereSource.cxx delete mode 100644 plugins/VTKFilters/SphereSource.h delete mode 100644 plugins/VTKIO/MeshReader.cxx delete mode 100644 plugins/VTKIO/MeshReader.h delete mode 100644 plugins/VTKIO/MeshWriter.cxx delete mode 100644 plugins/VTKIO/MeshWriter.h delete mode 100644 plugins/VTKWidgets/LineWidget.cxx delete mode 100644 plugins/VTKWidgets/LineWidget.h delete mode 100644 plugins/VTKWidgets/SeedWidget.cxx delete mode 100644 plugins/VTKWidgets/SeedWidget.h delete mode 100644 plugins/VTKWidgets/SplineWidget.cxx delete mode 100644 plugins/VTKWidgets/SplineWidget.h delete mode 100644 plugins/change.csv delete mode 100644 plugins/cpExtensions/DiscontinuityMapImageFilter.cxx delete mode 100644 plugins/cpExtensions/DiscontinuityMapImageFilter.h delete mode 100644 plugins/cpExtensions/ImageFunctorFilter.cxx delete mode 100644 plugins/cpExtensions/ImageFunctorFilter.h delete mode 100644 plugins/cpExtensions/PolyLineParametricPathToPolyData.cxx delete mode 100644 plugins/cpExtensions/PolyLineParametricPathToPolyData.h delete mode 100644 plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.cxx delete mode 100644 plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.h delete mode 100644 plugins/cpExtensions/PolyLineParametricPathWriter.cxx delete mode 100644 plugins/cpExtensions/PolyLineParametricPathWriter.h delete mode 100644 plugins/cpExtensions/SkeletonReader.cxx delete mode 100644 plugins/cpExtensions/SkeletonReader.h delete mode 100644 plugins/cpExtensions/SkeletonToImageFilter.cxx delete mode 100644 plugins/cpExtensions/SkeletonToImageFilter.h delete mode 100644 plugins/cpExtensions/SkeletonWriter.cxx delete mode 100644 plugins/cpExtensions/SkeletonWriter.h delete mode 100644 plugins/cpExtensions/cpExtensions.i delete mode 100644 tools/CMakeLists.txt delete mode 100644 tools/ExecutePipeline.cxx delete mode 100644 tools/PrintDirInfo.cxx delete mode 100644 tools/PrintFileInfo.cxx delete mode 100644 tools/PrintGuessInfo.cxx delete mode 100644 tools/RenameImageFile.cxx diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index d584f6e..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 3.0) - -## ======================== -## == Project definition == -## ======================== - -SET(prj_NAME cpPlugins) -SET(prj_MAJ_VERSION 0) -SET(prj_MIN_VERSION 1) -SET(prj_REL_VERSION 0) -SET(_subdirs cmake bash lib tools plugins appli) -SET(_policies CMP0015 CMP0020 CMP0042) - -## ========================== -## == Some useful policies == -## ========================== - -FOREACH(_p ${_policies}) - IF(POLICY ${_p}) - CMAKE_POLICY(SET ${_p} NEW) - ENDIF(POLICY ${_p}) -ENDFOREACH(_p) - -## =========================== -## == Project configuration == -## =========================== - -PROJECT(${prj_NAME}) -SET(prj_VERSION"${prj_MAJ_VERSION}.${prj_MIN_VERSION}.${prj_REL_VERSION}") -SET(prj_SHORT_VERSION "${prj_MAJ_VERSION}") - -## ===================================== -## == Functions, packages and options == -## ===================================== - -INCLUDE(cmake/BaseConfig.cmake) -INCLUDE(cmake/Options.cmake) -INCLUDE(cmake/KitwareTools.cmake) -INCLUDE(cmake/QtTools.cmake) -INCLUDE(cmake/Functions.cmake) - -## =========================== -## == Build different parts == -## =========================== - -FOREACH(_s ${_subdirs}) - SUBDIRS(${_s}) -ENDFOREACH(_s) - -## eof - $RCSfile$ diff --git a/appli/CMakeLists.txt b/appli/CMakeLists.txt deleted file mode 100644 index 414db20..0000000 --- a/appli/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ - -## =================================== -## == One directory per application == -## =================================== - -SUBDIRS( - PipelineEditor - ) - -## eof - $RCSfile$ diff --git a/appli/PipelineEditor/CMakeLists.txt b/appli/PipelineEditor/CMakeLists.txt deleted file mode 100644 index 11b7d77..0000000 --- a/appli/PipelineEditor/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -IF(BUILD_QT4_COMPONENTS) - INCLUDE_DIRECTORIES( - ${PROJECT_SOURCE_DIR}/lib - ${PROJECT_BINARY_DIR}/lib - ${PROJECT_SOURCE_DIR}/appli/PipelineEditor - ${PROJECT_BINARY_DIR}/appli/PipelineEditor - ) - cpPlugins_BuildApplication(PipelineEditor ${CMAKE_CURRENT_SOURCE_DIR}) - IF(BUILD_PipelineEditor) - TARGET_LINK_LIBRARIES(PipelineEditor cpBaseQtApplication) - ENDIF(BUILD_PipelineEditor) -ENDIF(BUILD_QT4_COMPONENTS) - -## eof - $RCSfile$ diff --git a/appli/PipelineEditor/PipelineEditor.cxx b/appli/PipelineEditor/PipelineEditor.cxx deleted file mode 100644 index c55920f..0000000 --- a/appli/PipelineEditor/PipelineEditor.cxx +++ /dev/null @@ -1,157 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -PipelineEditor:: -PipelineEditor( int argc, char* argv[], QWidget* parent ) - : Superclass( argc, argv, parent ), - m_UI( new Ui::PipelineEditor ) -{ - // Basic configuration - this->m_BaseWindowTitle = "PipelineEditor - "; - this->m_UI->setupUi( this ); - this->setCanvas( this->m_UI->Canvas ); - this->setNavigator( this->m_UI->Navigator ); - this->m_UI->Navigator->Update( ); - - // Connect slots <-> signals - cpBaseQtApplication_ConnectAction( actionLoadDirectory, _loadPluginsFromPath ); - cpBaseQtApplication_ConnectAction( actionLoadLibrary, _loadPlugins ); - cpBaseQtApplication_ConnectAction( actionOpenWorkspace, _loadWorkspace ); - cpBaseQtApplication_ConnectAction( actionSaveWorkspace, _saveWorkspace ); - cpBaseQtApplication_ConnectAction( actionSaveWorkspaceAs, _saveWorkspace ); - cpBaseQtApplication_ConnectAction( actionActorsProperties, _actorsProperties ); - this->m_UI->Canvas->connectOutputPortSlot( - this, SLOT( _slotView( const std::string&, bool ) ) - ); - this->connect( - this->m_UI->actionPrintExecutionInformation, SIGNAL( triggered( bool ) ), - this, SLOT( _slotPrintExecutionInformation( bool ) ) - ); - - // Load command-line given workspace (if any) - if( argc > 1 ) - this->_loadWorkspace( argv[ 1 ] ); -} - -// ------------------------------------------------------------------------- -PipelineEditor:: -~PipelineEditor( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -void PipelineEditor:: -_slotView( const std::string& name, bool show ) -{ - typedef cpExtensions::QT::ActorsWidgetInterface _TViewer; - - // Get filter parameters - std::vector< std::string > tokens = - cpPlugins::OS::String::Tokenize( name, "@" ); - if( tokens.size( ) != 2 ) - return; - auto filter_name = tokens[ 1 ]; - auto output_name = tokens[ 0 ]; - - // Process data - if( show ) - { - try - { - auto ws = this->workspace( ); - auto filter = ws->GetFilter( filter_name ); - cpBaseQtApplication_Execute( filter->Update( ) ); - auto image = filter->GetOutputData< vtkImageData >( output_name ); - auto mesh = filter->GetOutputData< vtkPolyData >( output_name ); - _TViewer* viewer = NULL; - if( image != NULL ) - { - int dim = image->GetDataDimension( ); - if( dim == 2 ) - viewer = - this->_configureViewer< cpExtensions::QT::ImageWidget >( - this->m_UI->Viewer - ); - else if( dim == 3 ) - viewer = - this->_configureViewer< cpExtensions::QT::SimpleMPRWidget >( - this->m_UI->Viewer - ); - } - else if( mesh != NULL ) - { - viewer = - this->_configureViewer< cpExtensions::QT::SimpleMPRWidget >( - this->m_UI->Viewer - ); - - } // fi - if( - dynamic_cast< QWidget* >( viewer ) != - dynamic_cast< QWidget* >( this->m_UI->Viewer ) && - viewer != NULL - ) - { - delete this->m_UI->Viewer; - this->m_UI->Viewer = dynamic_cast< QWidget* >( viewer ); - this->m_UI->MainSplitter->insertWidget( 0, this->m_UI->Viewer ); - this->setViewer( viewer ); - - } // fi - if( image != NULL ) - { - this->m_Blocker.block( ); - auto mpr = dynamic_cast< cpExtensions::QT::SimpleMPRWidget* >( viewer ); - auto imv = dynamic_cast< cpExtensions::QT::ImageWidget* >( viewer ); - if( mpr != NULL ) - mpr->SetImage( image, name ); - else if( imv != NULL ) - imv->SetImage( image, name ); - this->m_Blocker.unblock( ); - } - else if( mesh != NULL ) - { - this->m_Blocker.block( ); - auto mpr = dynamic_cast< cpExtensions::QT::SimpleMPRWidget* >( viewer ); - if( mpr != NULL ) - mpr->Add( mesh, name ); - this->m_Blocker.unblock( ); - - } // fi - } - catch( std::exception& err ) - { - QMessageBox::critical( - NULL, - QMessageBox::tr( "Error showing data" ), - QMessageBox::tr( err.what( ) ) - ); - - } // yrt - - } // fi -} - -// ------------------------------------------------------------------------- -void PipelineEditor:: -_slotPrintExecutionInformation( bool show ) -{ - if( this->m_Workspace.IsNotNull( ) ) - this->m_Workspace->SetPrintExecution( show ); -} - -// ------------------------------------------------------------------------- -#include -cpBaseQtApplication_Main( PipelineEditor ); -cpBaseQtApplication_MainComplement; - -// eof - $RCSfile$ diff --git a/appli/PipelineEditor/PipelineEditor.h b/appli/PipelineEditor/PipelineEditor.h deleted file mode 100644 index 1b6674e..0000000 --- a/appli/PipelineEditor/PipelineEditor.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef __PipelineEditor__h__ -#define __PipelineEditor__h__ - -#include -#include - -namespace Ui { class PipelineEditor; } - -/** - */ -class PipelineEditor - : public cpBaseQtApplication::MainWindow -{ - Q_OBJECT; -public: - typedef PipelineEditor Self; - typedef cpBaseQtApplication::MainWindow Superclass; - -public: - explicit PipelineEditor( - int argc, char* argv[], - QWidget* parent = NULL - ); - virtual ~PipelineEditor( ); - -protected slots: - void _slotView( const std::string& name, bool show ); - void _slotPrintExecutionInformation( bool show ); - -private: - Ui::PipelineEditor* m_UI; -}; - -#endif // __PipelineEditor__h__ - -// eof - $RCSfile$ diff --git a/appli/PipelineEditor/PipelineEditor.ui b/appli/PipelineEditor/PipelineEditor.ui deleted file mode 100644 index 0e61512..0000000 --- a/appli/PipelineEditor/PipelineEditor.ui +++ /dev/null @@ -1,188 +0,0 @@ - - - PipelineEditor - - - - 0 - 0 - 800 - 600 - - - - PipelineEditor - - - - - 2 - - - 2 - - - - - Qt::Vertical - - - - - Qt::Horizontal - - - - - - - - - - - - 0 - 0 - 800 - 25 - - - - - &File - - - - - - - - - - &Properties - - - - - - Plu&gins - - - - - - - - - - - - toolBar - - - TopToolBarArea - - - false - - - - - - E&xit - - - - - &Open workspace - - - Ctrl+O - - - - - &Save workspace - - - Ctrl+S - - - - - Sa&ve workspace as... - - - Ctrl+Shift+S - - - - - &Actors - - - Ctrl+Shift+P - - - - - Load &library - - - Ctrl+Shift+L - - - - - Load &directory - - - Ctrl+Shift+D - - - - - true - - - Print execution information? - - - Print execution information? - - - - - - cpBaseQtApplication::Plugins::Navigator - QWidget -
cpBaseQtApplication/Plugins/Navigator.h
- 1 -
- - cpBaseQtApplication::Pipeline::Canvas - QWidget -
cpBaseQtApplication/Pipeline/Canvas.h
- 1 -
-
- - - - actionExit - triggered() - PipelineEditor - close() - - - -1 - -1 - - - 399 - 299 - - - - -
diff --git a/bash/CMakeLists.txt b/bash/CMakeLists.txt deleted file mode 100644 index 36c5075..0000000 --- a/bash/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -CONFIGURE_FILE( - ${CMAKE_CURRENT_SOURCE_DIR}/Config.h.in - ${CMAKE_CURRENT_BINARY_DIR}/Config.h - @ONLY - ) -INCLUDE_DIRECTORIES( - ${PROJECT_SOURCE_DIR} - ${PROJECT_BINARY_DIR} - ) -SET( - _progs - CreateDemanglers - CreateInstances - CreateRealConfig - HostCreator - ) -FOREACH(_p ${_progs}) - ADD_EXECUTABLE(cpPlugins_bash_${_p} ${_p}) - SET( - cpPlugins_bash_${_p}_APP cpPlugins_bash_${_p} - CACHE INTERNAL "bash program cpPlugins_bash_${_p}" - ) -ENDFOREACH(_p) - -## eof - $RCSfile$ diff --git a/bash/Config.h.in b/bash/Config.h.in deleted file mode 100644 index 1d53531..0000000 --- a/bash/Config.h.in +++ /dev/null @@ -1,274 +0,0 @@ -#ifndef __cpPlugins__bash__Config__h__ -#define __cpPlugins__bash__Config__h__ - -// ------------------------------------------------------------------------- -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -#define cpPlugins_PROCESS_DIMS "@cpPlugins_PROCESS_DIMS@" -#define cpPlugins_VISUAL_DIMS "@cpPlugins_VISUAL_DIMS@" -#define cpPlugins_ALL_CONFIGS "@cpPlugins_ALL_CONFIGS@" -#define cpPlugins_NUMBER_OF_FILES @cpPlugins_NUMBER_OF_FILES@ - -// ------------------------------------------------------------------------- -#define cpPlugins_bash_OS_@CMAKE_SYSTEM_NAME@ -#ifdef cpPlugins_bash_OS_Windows -# define cpPlugins_bash_STRTOK( A, B, N ) strtok_s( A, B, N ) -# define cpPlugins_bash_SPRINTF( B, S, O ) sprintf_s( B, S, "%s", O ); -#else // cpPlugins_bash_OS_Windows -# define cpPlugins_bash_STRTOK( A, B, N ) std::strtok( A, B ) -# define cpPlugins_bash_SPRINTF( B, S, O ) std::sprintf( B, "%s", O ); -#endif // cpPlugins_bash_OS_Windows - -// ------------------------------------------------------------------------- -typedef std::deque< std::string > TStrings; -typedef std::map< std::string, TStrings > TCommands; - -/** - */ -namespace cpPlugins_bash -{ - // ----------------------------------------------------------------------- - template< class _TTokens > - inline void Tokenize( - _TTokens& tokens, const std::string& str, const std::string& delims - ) - { - tokens.clear( ); - if( str.size( ) > 0 ) - { - auto ssize = str.size( ); - char* buffer = new char[ ssize + 1 ]; - for( unsigned long i = 0; i < ssize; ++i ) - buffer[ i ] = str[ i ]; - buffer[ ssize ] = '\0'; - char* next; - char* it = cpPlugins_bash_STRTOK( buffer, delims.c_str( ), &next ); - while( it != NULL ) - { - tokens.push_back( std::string( it ) ); - it = cpPlugins_bash_STRTOK( NULL, delims.c_str( ), &next ); - - } // elihw - delete [] buffer; - - } // fi - } - - // ----------------------------------------------------------------------- - inline std::string Replace( - const std::string& str, const std::string& sub, const std::string& nsub - ) - { - std::string res = str; - size_t index; - while( ( index = res.find( sub ) ) != std::string::npos ) - res.replace( index, sub.size( ), nsub ); - return( res ); - } - - // ----------------------------------------------------------------------- - inline bool Read( std::string& buffer, const std::string& fname ) - { - buffer = ""; - std::ifstream file_stream( fname.c_str( ) ); - if( !file_stream ) - return( false ); - file_stream.seekg( 0, std::ios::end ); - buffer.reserve( ( unsigned int )( file_stream.tellg( ) ) ); - file_stream.seekg( 0, std::ios::beg ); - buffer.assign( - ( std::istreambuf_iterator< char >( file_stream ) ), - std::istreambuf_iterator< char >( ) - ); - file_stream.close( ); - return( true ); - } - - // ----------------------------------------------------------------------- - inline bool Write( const std::string& buffer, const std::string& fname ) - { - std::ofstream file_stream( fname.c_str( ), std::ofstream::binary ); - if( !file_stream ) - return( false ); - file_stream.write( buffer.c_str( ), buffer.size( ) ); - return( true ); - } - - // ----------------------------------------------------------------------- - inline void Parse( TCommands& commands, const TStrings& lines ) - { - for( auto l = lines.begin( ); l != lines.end( ); ++l ) - { - auto line = l->substr( l->find_first_not_of( " " ) ); - if( line != "" ) - { - if( line[ 0 ] != '*' ) - { - auto cmd = line.substr( 0, line.find( " " ) ); - auto args = line.substr( line.find( " " ) + 1 ); - commands[ cmd ].push_back( args ); - - } // fi - - } // fi - - } // rof - } - - // ----------------------------------------------------------------------- - inline void LoadDefinitions( TCommands& commands ) - { - // Dimensions - commands[ "define" ].push_back( - std::string( "pdims=" ) + - std::string( cpPlugins_PROCESS_DIMS ) - ); - commands[ "define" ].push_back( - std::string( "vdims=" ) + - std::string( cpPlugins_VISUAL_DIMS ) - ); - - // Base c++ types - commands[ "define" ].push_back( - std::string( "int_types=char;short;int;long" ) - ); - commands[ "define" ].push_back( - std::string( "uint_types=unsigned #int_types#" ) - ); - commands[ "define" ].push_back( - std::string( "sint_types=signed char" ) - ); - commands[ "define" ].push_back( - std::string( "real_types=float;double" ) - ); - commands[ "define" ].push_back( - std::string( - "scalar_types=#int_types#;#uint_types#;#real_types#" - ) - ); - } - - // ----------------------------------------------------------------------- - inline void ExpandDefinitions( - TCommands& definitions, const TCommands& commands - ) - { - definitions.clear( ); - auto defs = commands.find( "define" ); - if( defs == commands.end( ) ) - return; - - std::map< std::string, std::string > values; - for( auto dIt = defs->second.begin( ); dIt != defs->second.end( ); ++dIt ) - { - TStrings toks; - cpPlugins_bash::Tokenize( toks, *dIt, "=" ); - if( toks.size( ) == 2 ) - { - auto name = toks[ 0 ].substr( toks[ 0 ].find_first_not_of( " " ) ); - auto val = toks[ 1 ].substr( toks[ 1 ].find_first_not_of( " " ) ); - values[ name ] = val; - - } // fi - - } // rof - for( auto vIt = values.begin( ); vIt != values.end( ); ++vIt ) - { - TStrings toks; - cpPlugins_bash::Tokenize( toks, vIt->second, ";" ); - for( auto tIt = toks.begin( ); tIt != toks.end( ); ++tIt ) - definitions[ vIt->first ].push_back( *tIt ); - - } // rof - for( auto dIt = definitions.begin( ); dIt != definitions.end( ); ++dIt ) - { - auto name = std::string( "#" ) + dIt->first + std::string( "#" ); - for( auto eIt = definitions.begin( ); eIt != definitions.end( ); ++eIt ) - { - if( eIt != dIt ) - { - auto vIt = eIt->second.begin( ); - while( vIt != eIt->second.end( ) ) - { - if( vIt->find( name ) != std::string::npos ) - { - for( - auto wIt = dIt->second.begin( ); - wIt != dIt->second.end( ); - ++wIt - ) - eIt->second.push_back( - cpPlugins_bash::Replace( *vIt, name, *wIt ) - ); - vIt = eIt->second.erase( vIt ); - } - else - ++vIt; - - } // elihw - - } // fi - - } // rof - - } // rof - } - - // ----------------------------------------------------------------------- - inline void Expand( - TStrings& tfiles, - const TCommands& definitions, - const TCommands& commands, - const std::string& cmd - ) - { - tfiles.clear( ); - auto tIt = commands.find( cmd ); - if( tIt == commands.end( ) ) - return; - - for( auto fIt = tIt->second.begin( ); fIt != tIt->second.end( ); ++fIt ) - { - std::queue< std::string > q; - q.push( *fIt ); - while( q.size( ) > 0 ) - { - auto value = q.front( ); - q.pop( ); - auto spos = value.find( "#" ); - if( spos != std::string::npos ) - { - auto name = value.substr( spos + 1 ); - auto epos = name.find( "#" ); - name = name.substr( 0, epos ); - auto dIt = definitions.find( name ); - if( dIt != definitions.end( ) ) - { - name = std::string( "#" ) + name + std::string( "#" ); - for( auto vIt = dIt->second.begin( ); vIt != dIt->second.end( ); ++vIt ) - q.push( cpPlugins_bash::Replace( value, name, *vIt ) ); - - } // fi - } - else - tfiles.push_back( value ); - - } // rof - - } // rof - } - -} // ecapseman - -#endif // __cpPlugins__bash__Config__h__ - -// eof - $RCSfile$ diff --git a/bash/CreateDemanglers.cxx b/bash/CreateDemanglers.cxx deleted file mode 100644 index a68117f..0000000 --- a/bash/CreateDemanglers.cxx +++ /dev/null @@ -1,121 +0,0 @@ -#include - -#define MAX_NUMBER_OF_INPUTS 9 - -// ------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - // Get inputs - if( argc < 4 ) - { - std::cerr - << "Usage: " << argv[ 0 ] - << " definitons_file object_name output_file" - << std::endl; - return( 1 ); - - } // fi - std::string definitions_filename = argv[ 1 ]; - std::string object_name = argv[ 2 ]; - std::string output_filename = argv[ 3 ]; - - // Read inputs - std::string definitions_buffer; - if( !( cpPlugins_bash::Read( definitions_buffer, definitions_filename ) ) ) - { - std::cerr - << argv[ 0 ] - << ": Error reading definitions file \"" << definitions_filename - << "\"" << std::endl; - return( 1 ); - - } // fi - - // Put it in a line-by-line structure - TStrings definitions_lines; - cpPlugins_bash::Tokenize( definitions_lines, definitions_buffer, "\n" ); - - // Parse input file - TCommands commands; - cpPlugins_bash::Parse( commands, definitions_lines ); - - // Load pre-compiled definitions - cpPlugins_bash::LoadDefinitions( commands ); - - // Expand definitions - TCommands definitions; - cpPlugins_bash::ExpandDefinitions( definitions, commands ); - - // Expand data - std::stringstream data; - data - << "#ifndef __cpPlugins__Demanglers__" << object_name << "__h__" << std::endl - << "#define __cpPlugins__Demanglers__" << object_name << "__h__" << std::endl - << std::endl; - - for( auto cIt = commands.begin( ); cIt != commands.end( ); ++cIt ) - { - if( cIt->first == "define" ) - continue; - - TStrings instances; - cpPlugins_bash::Expand( instances, definitions, commands, cIt->first ); - TStrings toks; - cpPlugins_bash::Tokenize( toks, cIt->first, "|" ); - for( unsigned int nIns = 1; nIns <= MAX_NUMBER_OF_INPUTS; ++nIns ) - { - if( toks.size( ) > 1 ) - { - data - << "#define cpPlugins_Demangle_" << object_name << "_" - << toks[ 0 ] << "_" << nIns << "( o, f"; - for( unsigned int i = 1; i < toks.size( ); ++i ) - data << ", " << toks[ i ]; - } - else - data - << "#define cpPlugins_Demangle_" << object_name << "_" - << toks[ 0 ] << "_" << nIns << "( o, f"; - - for( unsigned int i = 1; i < nIns; ++i ) - data << ", X" << i; - data << " ) \\"; - - data << std::endl; - std::string prefix = ""; - for( auto iIt = instances.begin( ); iIt != instances.end( ); ++iIt ) - { - data - << " " << prefix - << "if( dynamic_cast< " << *iIt << "* >( o ) != NULL ) \\" - << std::endl - << " this->f( dynamic_cast< " << *iIt << "* >( o )"; - - for( unsigned int i = 1; i < nIns; ++i ) - data << ", X" << i; - data - << " ); \\" - << std::endl; - prefix = "else "; - - } // rof - data << " " << prefix << std::endl << std::endl; - - } // rof - - } // rof - - data - << "#endif // __cpPlugins__Demanglers__" << object_name << "__h__" - << std::endl; - if( !( cpPlugins_bash::Write( data.str( ), output_filename ) ) ) - { - std::cerr << "Error writing file." << std::endl; - return( 1 ); - - } // fi - - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/bash/CreateInstances.cxx b/bash/CreateInstances.cxx deleted file mode 100644 index a107c26..0000000 --- a/bash/CreateInstances.cxx +++ /dev/null @@ -1,168 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - // Get inputs - if( argc < 4 ) - { - std::cerr - << "Usage: " << argv[ 0 ] - << " definitons_file library_name output_prefix" - << std::endl; - return( 1 ); - - } // fi - std::string definitions_filename = argv[ 1 ]; - std::string library_name = argv[ 2 ]; - std::string output_prefix = argv[ 3 ]; - unsigned int number_of_sources = cpPlugins_NUMBER_OF_FILES; - - // Read inputs - std::string definitions_buffer; - if( !( cpPlugins_bash::Read( definitions_buffer, definitions_filename ) ) ) - { - std::cerr - << argv[ 0 ] - << ": Error reading definitions file \"" << definitions_filename - << "\"" << std::endl; - return( 1 ); - - } // fi - - // Put it in a line-by-line structure - TStrings definitions_lines; - cpPlugins_bash::Tokenize( definitions_lines, definitions_buffer, "\n" ); - - // Parse input file - TCommands commands; - cpPlugins_bash::Parse( commands, definitions_lines ); - - // Load pre-compiled definitions - cpPlugins_bash::LoadDefinitions( commands ); - - // Expand definitions - TCommands definitions; - cpPlugins_bash::ExpandDefinitions( definitions, commands ); - definitions[ "_export_" ].clear( ); - definitions[ "_export_" ].push_back( library_name + std::string( "_EXPORT" ) ); - - // Expand data - TStrings tfiles, cfiles, instances, minstances; - cpPlugins_bash::Expand( tfiles, definitions, commands, "tinclude" ); - cpPlugins_bash::Expand( cfiles, definitions, commands, "cinclude" ); - cpPlugins_bash::Expand( instances, definitions, commands, "instances" ); - cpPlugins_bash::Expand( minstances, definitions, commands, "minstances" ); - - // Build all instances - TStrings all_instances; - for( auto iIt = instances.begin( ); iIt != instances.end( ); ++iIt ) - { - std::stringstream str; - str << "template class " << library_name << "_EXPORT " << *iIt; - all_instances.push_back( str.str( ) ); - - } // rof - for( auto iIt = minstances.begin( ); iIt != minstances.end( ); ++iIt ) - { - std::stringstream str; - str << "template " << *iIt; - all_instances.push_back( str.str( ) ); - - } // rof - - // Write source code - unsigned int instances_per_file = - ( unsigned int )( - std::floor( double( all_instances.size( ) ) / double( number_of_sources ) ) - ); - if( instances_per_file == 0 ) - instances_per_file = 1; - std::vector< std::vector< std::string > > all_lines( 1 ); - for( unsigned int c_id = 0; c_id < all_instances.size( ); ++c_id ) - { - all_lines[ all_lines.size( ) - 1 ].push_back( all_instances[ c_id ] ); - if( c_id % instances_per_file == instances_per_file - 1 ) - all_lines.push_back( std::vector< std::string >( ) ); - - } // rof - - // Paranoiac code - while( all_lines.size( ) > number_of_sources ) - { - all_lines[ all_lines.size( ) - 2 ].insert( - all_lines[ all_lines.size( ) - 2 ].end( ), - all_lines[ all_lines.size( ) - 1 ].begin( ), - all_lines[ all_lines.size( ) - 1 ].end( ) - ); - all_lines.pop_back( ); - - } // elihw - while( all_lines.size( ) < number_of_sources ) - all_lines.push_back( std::vector< std::string >( ) ); - - // Real write - for( unsigned int f_id = 0; f_id < all_lines.size( ); ++f_id ) - { - std::stringstream source; - source - << "#include <" << library_name << "_Export.h>" - << std::endl; - auto hIt = commands.find( "header" ); - if( hIt != commands.end( ) ) - { - source << std::endl; - for( auto vIt = hIt->second.begin( ); vIt != hIt->second.end( ); ++vIt ) - source << *vIt << std::endl; - source << std::endl; - - } // fi - - if( tfiles.size( ) > 0 ) - { - for( auto tIt = tfiles.begin( ); tIt != tfiles.end( ); ++tIt ) - { - TStrings toks; - cpPlugins_bash::Tokenize( toks, *tIt, ":|" ); - if( toks.size( ) == 3 ) - { - source << "#include <" << toks[ 0 ] << "." << toks[ 1 ] << ">" << std::endl; - source << "#include <" << toks[ 0 ] << "." << toks[ 2 ] << ">" << std::endl; - - } // fi - - } // rof - source << std::endl; - - } // fi - - if( cfiles.size( ) > 0 ) - { - for( auto cIt = cfiles.begin( ); cIt != cfiles.end( ); ++cIt ) - source << "#include <" << *cIt << ">" << std::endl; - source << std::endl; - - } // fi - - for( - auto c_it = all_lines[ f_id ].begin( ); - c_it != all_lines[ f_id ].end( ); - ++c_it - ) - source << *c_it << ";" << std::endl; - source << std::endl << "// eof" << std::endl; - std::stringstream source_file; - source_file - << output_prefix << "_" << f_id << ".cxx"; - if( !( cpPlugins_bash::Write( source.str( ), source_file.str( ) ) ) ) - { - std::cerr << "Error writing source code." << std::endl; - return( 1 ); - - } // fi - - } // rof - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/bash/CreateRealConfig.cxx b/bash/CreateRealConfig.cxx deleted file mode 100644 index e9737d5..0000000 --- a/bash/CreateRealConfig.cxx +++ /dev/null @@ -1,37 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - // Get inputs - if( argc < 2 ) - { - std::cerr << "Usage: " << argv[ 0 ] << " output_file" << std::endl; - return( 1 ); - - } // fi - std::string output_filename = argv[ 1 ]; - - std::stringstream data; - data - << "#ifndef __cpPlugins__RealConfig__h__" << std::endl - << "#define __cpPlugins__RealConfig__h__" << std::endl - << std::endl; - - TStrings tokens; - cpPlugins_bash::Tokenize( tokens, cpPlugins_ALL_CONFIGS, ";" ); - for( auto t = tokens.begin( ); t != tokens.end( ); ++t ) - data << "#define " << *t << std::endl; - - data << std::endl << "#endif // __cpPlugins__RealConfig__h__" << std::endl; - if( !( cpPlugins_bash::Write( data.str( ), output_filename ) ) ) - { - std::cerr << "Error writing file." << std::endl; - return( 1 ); - - } // fi - - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/bash/HostCreator.cxx b/bash/HostCreator.cxx deleted file mode 100644 index 8e6f274..0000000 --- a/bash/HostCreator.cxx +++ /dev/null @@ -1,193 +0,0 @@ -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -typedef std::pair< std::string, std::string > TPair; -typedef std::map< std::string, TPair > TInfo; - -// ------------------------------------------------------------------------- -bool is_valid_class( const std::string& str ) -{ - return( str.find( "cpPluginsObject" ) != std::string::npos ); -} - -// ------------------------------------------------------------------------- -void process_header( TInfo& info, const std::string& file_name ) -{ - std::string buffer; - if( !( cpPlugins_bash::Read( buffer, file_name ) ) ) - return; - - auto prev_pos = std::string::npos; - prev_pos = 0; - auto pos = buffer.find( "cpPluginsObject" ); - while( pos != std::string::npos ) - { - // Get class names - auto op = buffer.find( "(", pos ); - auto cl = buffer.find( ")", pos ); - std::vector< std::string > tokens; - cpPlugins_bash::Tokenize( - tokens, - buffer.substr( op + 1, cl - op - 2 ), - ",\n " - ); - - std::string namespace_name = ""; - auto preamble = buffer.substr( prev_pos, pos ); - auto napos = preamble.find( "namespace" ); - while( napos != std::string::npos ) - { - auto enapos = preamble.find( "{", napos + 1 ); - auto tmp = preamble.substr( napos, enapos - napos + 1 ); - std::vector< std::string > tokens2; - cpPlugins_bash::Tokenize( tokens2, tmp, " \n\t{" ); - namespace_name = tokens2.back( ); - napos = preamble.find( "namespace", napos + 1 ); - - } // elihw - - auto class_name = tokens[ 0 ]; - auto superclass_name = tokens[ 1 ]; - auto category_name = tokens[ 2 ]; - if( info.find( class_name ) == info.end( ) ) - info[ class_name ] = TPair( category_name, namespace_name ); - prev_pos = pos; - pos = buffer.find( "cpPluginsObject", pos + 1 ); - - } // elihw -} - -// ------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - if( argc < 4 ) - { - std::cerr - << "Usage: " << argv[ 0 ] - << " plugins_name output_file header_file_0.h header_file_0.h ..." - << std::endl; - return( 1 ); - - } // fi - std::string plugins_name = argv[ 1 ]; - std::string output_filename = argv[ 2 ]; - - // Parse all header files - TInfo info; - for( int i = 3; i < argc; ++i ) - process_header( info, argv[ i ] ); - if( info.size( ) == 0 ) - { - std::cerr << "ERROR: No valid input headers." << std::endl; - return( 1 ); - - } // fi - - // Prepare prefixes -#if defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) - std::string export_prefix = "__declspec(dllexport)"; -#else // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) - std::string export_prefix = "__attribute__((visibility(\"default\")))"; -#endif // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) - - // Output data - std::stringstream out; - - // Include section - out - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << std::endl; - for( int i = 3; i < argc; ++i ) - out << "#include \"" << argv[ i ] << "\"" < " - << plugins_name << "_Data;" << std::endl - << std::endl - << "// -------------------------------------------------------------------------" << std::endl - << "extern \"C\" void __attribute__ ((constructor))" << std::endl - << plugins_name << "_Init( )" << std::endl - << "{" << std::endl - << "}" << std::endl - << std::endl - << "// -------------------------------------------------------------------------" << std::endl - << "extern \"C\" void __attribute__ ((destructor))" << std::endl - << plugins_name << "_Finish( )" << std::endl - << "{" << std::endl - << " // " << plugins_name << "_Data.clear( );" << std::endl - << "}" << std::endl - << std::endl - << "// -------------------------------------------------------------------------" << std::endl - << "extern \"C\" " << export_prefix << std::endl - << "void " << plugins_name << "_LoadContents( )" << std::endl - << "{" << std::endl - << " if( " << plugins_name << "_Data.size( ) == 0 )" << std::endl - << " {" << std::endl - << " std::string sep = \"@\";" << std::endl; - - // Classes - int id = 1; - for( auto iIt = info.begin( ); iIt != info.end( ); ++iIt, ++id ) - { - std::string class_name = iIt->second.second; - if( class_name != "" ) - class_name += std::string( "::" ); - class_name += iIt->first; - out - << " " << class_name << "::Pointer ptr" << id << " =" << std::endl - << " " << class_name << "::New( );" << std::endl - << " std::string id" << id << " = ptr" << id << "->GetClassName( )" - << " + sep + ptr" << id << "->GetClassCategory( );" << std::endl - << " " << plugins_name << "_Data[ id" << id << " ] = ptr" << id << ";" - << std::endl; - - } // rof - - // Remaining header - out - << std::endl << " } // fi" << std::endl << "}" << std::endl << std::endl - << "// -------------------------------------------------------------------------" << std::endl - << "extern \"C\" " << export_prefix << std::endl - << "void cpPlugins_Contents( std::vector< std::string >* c )" << std::endl - << "{" << std::endl - << " " << plugins_name << "_LoadContents( );" << std::endl - << " for( auto d : " << plugins_name << "_Data )" << std::endl - << " c->push_back( d.first );" << std::endl - << "}" << std::endl - << std::endl - << "// -------------------------------------------------------------------------" << std::endl - << "extern \"C\" " << export_prefix << std::endl - << "void cpPlugins_Creator( itk::LightObject::Pointer& ptr, const std::string& c, const std::string& f )" << std::endl - << "{" << std::endl - << " " << plugins_name << "_LoadContents( );" << std::endl - << " ptr = NULL;" << std::endl - << " std::string id = f + \"@\" + c;" << std::endl - << " auto fIt = " << plugins_name << "_Data.find( id );" << std::endl - << " if( fIt != " << plugins_name << "_Data.end( ) )" << std::endl - << " ptr = fIt->second->CreateAnother( );" << std::endl - << "}" << std::endl << std::endl - << "// eof - $Automatic generated file$" - << std::endl; - - // Real write - if( !( cpPlugins_bash::Write( out.str( ), output_filename ) ) ) - { - std::cerr << "ERROR: Could not write file." << std::endl; - return( 1 ); - - } // fi - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/cmake/BaseConfig.cmake b/cmake/BaseConfig.cmake deleted file mode 100644 index d177604..0000000 --- a/cmake/BaseConfig.cmake +++ /dev/null @@ -1,51 +0,0 @@ -## ======================================================================= -## == Force c++11 language version == -## == NOTE: It seems that by default on Visual Studio Compiler supports == -## == c++11, so it only need to be tested on other OS. == -## ======================================================================= - -IF(NOT MSVC) - INCLUDE(CheckCXXCompilerFlag) - CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) - IF(COMPILER_SUPPORTS_CXX11) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - ELSE(COMPILER_SUPPORTS_CXX11) - CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) - IF(COMPILER_SUPPORTS_CXX0X) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") - ELSE(COMPILER_SUPPORTS_CXX0X) - MESSAGE( - FATAL_ERROR - "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support." - ) - ENDIF(COMPILER_SUPPORTS_CXX0X) - ENDIF(COMPILER_SUPPORTS_CXX11) -ENDIF(NOT MSVC) - -## =================================================== -## == Prepare header generator to build shared libs == -## =================================================== - -INCLUDE(GenerateExportHeader) - -## ================================================== -## == Do not allow to build inside the source tree == -## ================================================== - -IF(PROJECT_BINARY_DIR STREQUAL ${PROJECT_SOURCE_DIR}) - MESSAGE(FATAL_ERROR "Building in the source tree is not allowed.") -ENDIF(PROJECT_BINARY_DIR STREQUAL ${PROJECT_SOURCE_DIR}) - -## ================================================= -## == Where to put targets (executables and libs) == -## ================================================= - -SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}) -SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}) -MARK_AS_ADVANCED( - CMAKE_BACKWARDS_COMPATIBILITY - EXECUTABLE_OUTPUT_PATH - LIBRARY_OUTPUT_PATH - ) - -## eof - $RCSfile$ diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt deleted file mode 100644 index e942ae9..0000000 --- a/cmake/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -## ===================== -## == Configure files == -## ===================== - -CONFIGURE_FILE( - cpPluginsConfig.cmake.in - ${PROJECT_BINARY_DIR}/cpPluginsConfig.cmake - @ONLY - ) - -## eof - $RCSfile$ diff --git a/cmake/Functions.cmake b/cmake/Functions.cmake deleted file mode 100644 index d755587..0000000 --- a/cmake/Functions.cmake +++ /dev/null @@ -1,328 +0,0 @@ -## ------------------------------------------------------------------------- -FUNCTION(NormPaths output_files) -SET(_out) -FOREACH(_f ${ARGN}) - SET(_d) - FILE(TO_CMAKE_PATH ${_f} _d) - LIST(APPEND _out ${_d}) -ENDFOREACH(_f) -SET(${output_files} "${_out}" PARENT_SCOPE) -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION(Wrap_Qt_CPP output_files) -SET(_out) -FOREACH(_f ${ARGN}) - IF(EXISTS ${_f}) - FILE(READ ${_f} _txt) - STRING(FIND "${_txt}" "Q_OBJECT" _pos) - IF(NOT ${_pos} EQUAL -1) - SET(_s) - QT4_WRAP_CPP(_s ${_f}) - SET(_out ${_out} ${_s}) - ENDIF(NOT ${_pos} EQUAL -1) - ENDIF(EXISTS ${_f}) -ENDFOREACH(_f) -SET(${output_files} "${_out}" PARENT_SCOPE) -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION(Wrap_Qt_UI output_files) -NormPaths(_source_dir ${PROJECT_SOURCE_DIR}) -NormPaths(_binary_dir ${PROJECT_BINARY_DIR}) -SET(_out) -FOREACH(_f ${ARGN}) - IF(EXISTS ${_f}) - GET_FILENAME_COMPONENT(_name ${_f} NAME_WE) - GET_FILENAME_COMPONENT(_dir ${_f} DIRECTORY) - SET(_base_dir ${_source_dir}) - STRING(FIND "${_dir}" "${_base_dir}" _pos) - IF(${_pos} EQUAL -1) - SET(_base_dir ${_binary_dir}) - STRING(FIND "${_dir}" "${_base_dir}" _pos) - ENDIF(${_pos} EQUAL -1) - IF(NOT ${_pos} EQUAL -1) - STRING(REPLACE "${_base_dir}/" "" _dir ${_dir}) - SET(_out_f ${_binary_dir}/${_dir}/ui_${_name}.h) - LIST(APPEND _out ${_out_f}) - ADD_CUSTOM_COMMAND( - OUTPUT ${_out_f} - COMMAND Qt4::uic - ARGS -o ${_out_f} ${_f} - MAIN_DEPENDENCY ${_f} VERBATIM - ) - ENDIF(NOT ${_pos} EQUAL -1) - ENDIF(EXISTS ${_f}) -ENDFOREACH(_f) -SET(${output_files} "${_out}" PARENT_SCOPE) -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION( - PrepareSourceFiles - lib_name - out_sources_list - out_headers_list - out_headers_paths - ) -SET(_config_extensions .c.in .cpp.in .cxx.in .h.in .hpp.in .hxx.in .ui.in) -SET(_sources_extensions .c .cpp .cxx) -SET(_headers_extensions .h .hpp .hxx) -SET(_qt_ui_extensions .ui) -SET(_demangler_extensions .d) -SET(_instances_extensions .i) - -## -- Configure inputs -SET(_all_files) -FOREACH(_file ${ARGN}) - GET_FILENAME_COMPONENT(_ext ${_file} EXT) - LIST(FIND _config_extensions ${_ext} _cfg) - IF(NOT ${_cfg} EQUAL -1) - STRING( - REPLACE - ${PROJECT_SOURCE_DIR} - ${PROJECT_BINARY_DIR} - _file_bin - ${_file} - ) - STRING(LENGTH ${_file_bin} _file_bin_len) - MATH(EXPR _file_bin_len "${_file_bin_len}-3") - STRING(SUBSTRING ${_file_bin} 0 ${_file_bin_len} _file_bin) - CONFIGURE_FILE(${_file} ${_file_bin} @ONLY) - LIST(APPEND _all_files ${_file_bin}) - ELSE(NOT ${_cfg} EQUAL -1) - LIST(APPEND _all_files ${_file}) - ENDIF(NOT ${_cfg} EQUAL -1) -ENDFOREACH(_file) - -## -- Separate files -SET(_srcs) -SET(_hdrs) -SET(_qts) -SET(_demanglers) -SET(_instances) -FOREACH(_file ${_all_files}) - GET_FILENAME_COMPONENT(_ext ${_file} EXT) - LIST(FIND _sources_extensions ${_ext} _src) - LIST(FIND _headers_extensions ${_ext} _hdr) - LIST(FIND _qt_ui_extensions ${_ext} _ui) - LIST(FIND _demangler_extensions ${_ext} _dem) - LIST(FIND _instances_extensions ${_ext} _ins) - IF(NOT ${_src} EQUAL -1) - LIST(APPEND _srcs ${_file}) - ENDIF(NOT ${_src} EQUAL -1) - IF(NOT ${_hdr} EQUAL -1) - LIST(APPEND _hdrs ${_file}) - ENDIF(NOT ${_hdr} EQUAL -1) - IF(NOT ${_ui} EQUAL -1) - LIST(APPEND _qts ${_file}) - ENDIF(NOT ${_ui} EQUAL -1) - IF(NOT ${_dem} EQUAL -1) - LIST(APPEND _demanglers ${_file}) - ENDIF(NOT ${_dem} EQUAL -1) - IF(NOT ${_ins} EQUAL -1) - LIST(APPEND _instances ${_file}) - ENDIF(NOT ${_ins} EQUAL -1) -ENDFOREACH(_file) - -# -- Prepare Qt4-based code -IF(Qt4_FOUND) - ## -- Guess what headers sould be qt-moc'ed - Wrap_Qt_CPP(_moc ${_hdrs}) - IF(_moc) - LIST(APPEND _srcs ${_moc}) - ENDIF(_moc) - - ## -- Guess what qt-ui's sould be qt-uic'ed - ## -- Wrap qt-ui headers: this is equivalent to QT4_WRAP_UI except to change - ## -- the output file - Wrap_Qt_UI(_qt_hdrs ${_qts}) - IF(_qt_hdrs) - LIST(APPEND _hdrs ${_qt_hdrs}) - ENDIF(_qt_hdrs) -ENDIF(Qt4_FOUND) - -## -- Create demanglers -FOREACH(_d ${_demanglers}) - STRING( - REPLACE - ${PROJECT_SOURCE_DIR} - ${PROJECT_BINARY_DIR} - _d_bin - ${_d} - ) - GET_FILENAME_COMPONENT(_d_path ${_d_bin} DIRECTORY) - GET_FILENAME_COMPONENT(_out_name ${_d_bin} NAME_WE) - SET(_d_out ${_d_path}/${_out_name}_Demanglers.h) - ADD_CUSTOM_COMMAND( - OUTPUT ${_d_out} - COMMAND ${CMAKE_COMMAND} -E make_directory ${_d_path} - COMMAND ${cpPlugins_bash_CreateDemanglers_APP} ${_d} ${_out_name} ${_d_out} - DEPENDS ${cpPlugins_bash_CreateDemanglers_APP} ${_d} - ) - LIST(APPEND _hdrs ${_d_out}) -ENDFOREACH(_d) - -## -- Create instances -FOREACH(_i ${_instances}) - STRING( - REPLACE - ${PROJECT_SOURCE_DIR} - ${PROJECT_BINARY_DIR} - _i_bin - ${_i} - ) - GET_FILENAME_COMPONENT(_i_path ${_i_bin} DIRECTORY) - GET_FILENAME_COMPONENT(_out_name ${_i} NAME_WE) - - ## -- Infere source code filenames - MATH(EXPR _last_range "${cpPlugins_NUMBER_OF_FILES}-1") - SET(_out_code) - FOREACH(_n RANGE 0 ${_last_range}) - LIST(APPEND _out_code ${_i_path}/${_out_name}_${_n}.cxx) - LIST(APPEND _srcs ${_i_path}/${_out_name}_${_n}.cxx) - ENDFOREACH(_n) - - ## -- Command to write source code - ADD_CUSTOM_COMMAND( - OUTPUT ${_out_code} - DEPENDS ${cpPlugins_bash_CreateInstances_APP} ${_i} - COMMAND ${CMAKE_COMMAND} -E make_directory ${_i_path} - COMMAND ${cpPlugins_bash_CreateInstances_APP} ${_i} ${lib_name} ${_i_path}/${_out_name} - ) -ENDFOREACH(_i) - -## -- Real compilation -SET(_hdrs_paths) -FOREACH(_hdr ${_hdrs}) - GET_FILENAME_COMPONENT(_path ${_hdr} DIRECTORY) - LIST(FIND _hdrs_paths ${_path} _path_idx) - IF(${_path_idx} EQUAL -1) - LIST(APPEND _hdrs_paths ${_path}) - ENDIF(${_path_idx} EQUAL -1) -ENDFOREACH(_hdr) - -SET(${out_sources_list} ${_srcs} PARENT_SCOPE) -SET(${out_headers_list} ${_hdrs} PARENT_SCOPE) -SET(${out_headers_paths} ${_hdrs_paths} PARENT_SCOPE) - -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION(cpPlugins_BuildLibrary lib_name lib_type) -# -- Detect all source files -SET(_all_files) -FOREACH(_c ${ARGN}) - GET_FILENAME_COMPONENT(_cname ${_c} ABSOLUTE) - SET(_files) - IF(IS_DIRECTORY ${_cname}) - FILE(GLOB_RECURSE _files "${_cname}/*") - ELSE(IS_DIRECTORY ${_cname}) - SET(_files ${_cname}) - ENDIF(IS_DIRECTORY ${_cname}) - LIST(APPEND _all_files ${_files}) -ENDFOREACH(_c ${ARGN}) - -## -- Prepare sources by types -PrepareSourceFiles(${lib_name} _srcs _hdrs _paths ${_all_files}) - -## -- Build library -IF(_srcs) - INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ) - ADD_LIBRARY(${lib_name} ${lib_type} ${_srcs} ${_hdrs}) - GENERATE_EXPORT_HEADER( - ${lib_name} - BASE_NAME ${lib_name} - EXPORT_MACRO_NAME ${lib_name}_EXPORT - EXPORT_FILE_NAME ${lib_name}_Export.h - STATIC_DEFINE ${lib_name}_BUILT_AS_STATIC - ) -ENDIF(_srcs) - -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION(cpPlugins_BuildPluginsLibrary lib_name) -# -- Detect all source files -SET(_all_files) -FOREACH(_c ${ARGN}) - GET_FILENAME_COMPONENT(_cname ${_c} ABSOLUTE) - SET(_files) - IF(IS_DIRECTORY ${_cname}) - FILE(GLOB_RECURSE _files "${_cname}/*") - ELSE(IS_DIRECTORY ${_cname}) - SET(_files ${_cname}) - ENDIF(IS_DIRECTORY ${_cname}) - LIST(APPEND _all_files ${_files}) -ENDFOREACH(_c ${ARGN}) - -## -- Prepare sources by types -PrepareSourceFiles(${lib_name} _srcs _hdrs _paths ${_all_files}) - -## -- Check which headers need to be wrapped to build host code -SET(_hdrs_to_wrap) -FOREACH(_hdr ${_hdrs}) - IF(EXISTS ${_hdr}) - FILE(READ ${_hdr} _txt) - STRING(FIND "${_txt}" "cpPluginsObject" _res) - IF(NOT ${_res} EQUAL -1) - LIST(APPEND _hdrs_to_wrap ${_hdr}) - ENDIF(NOT ${_res} EQUAL -1) - ENDIF(EXISTS ${_hdr}) -ENDFOREACH(_hdr) - -## -- Wrap headers -IF(_hdrs_to_wrap) - SET(_host ${CMAKE_CURRENT_BINARY_DIR}/${lib_name}_host.cxx) - ADD_CUSTOM_COMMAND( - OUTPUT ${_host} - DEPENDS ${cpPlugins_bash_HostCreator_APP} ${_hdrs_to_wrap} - COMMAND ${cpPlugins_bash_HostCreator_APP} ${lib_name} ${_host} ${_hdrs_to_wrap} - ) - LIST(APPEND _all_files ${_host}) -ENDIF(_hdrs_to_wrap) - -cpPlugins_BuildLibrary(${lib_name} SHARED ${_all_files}) -ENDFUNCTION() - -## ------------------------------------------------------------------------- -FUNCTION(cpPlugins_BuildApplication app_name) -OPTION(BUILD_${app_name} "Build \"${app_name}\" application?" OFF) -IF(BUILD_${app_name}) - # -- Detect all source files - SET(_all_files) - FOREACH(_c ${ARGN}) - GET_FILENAME_COMPONENT(_cname ${_c} ABSOLUTE) - SET(_files) - IF(IS_DIRECTORY ${_cname}) - FILE(GLOB_RECURSE _files "${_cname}/*") - ELSE(IS_DIRECTORY ${_cname}) - SET(_files ${_cname}) - ENDIF(IS_DIRECTORY ${_cname}) - LIST(APPEND _all_files ${_files}) - ENDFOREACH(_c ${ARGN}) - - ## -- Prepare sources by types - PrepareSourceFiles(${app_name} _srcs _hdrs _paths ${_all_files}) - - ## -- Build library - IF(_srcs) - INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ) - SET(_app_os_target) - IF(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") - SET(_app_os_target WIN32) - ELSEIF(${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") - SET(_app_os_target MACOSX_BUNDLE) - ENDIF(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") - ADD_EXECUTABLE(${app_name} ${_app_os_target} ${_srcs} ${_hdrs}) - ENDIF(_srcs) -ENDIF(BUILD_${app_name}) -ENDFUNCTION() - -## eof - $RCSfile$ diff --git a/cmake/KitwareTools.cmake b/cmake/KitwareTools.cmake deleted file mode 100644 index b4493d2..0000000 --- a/cmake/KitwareTools.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# ====================== -# == Find ITK and VTK == -# ====================== - -FIND_PACKAGE(ITK REQUIRED) -FIND_PACKAGE(VTK REQUIRED) - -INCLUDE(${ITK_USE_FILE}) -INCLUDE(${VTK_USE_FILE}) - -# =================================================== -# == Do not use itk-vtk glue --> problems ahead!!! == -# =================================================== - -IF(ITKVtkGlue_LOADED) - MESSAGE(FATAL_ERROR "ITKVtkGlue module is available. Please re-compile your ITK without it. It could lead to nasty compilation problems... Just waiting for Kitware to solve it.") -ENDIF(ITKVtkGlue_LOADED) - -## eof - $RCSfile$ diff --git a/cmake/Options.cmake b/cmake/Options.cmake deleted file mode 100644 index 6800c63..0000000 --- a/cmake/Options.cmake +++ /dev/null @@ -1,25 +0,0 @@ -## =============================== -## == Some configurable options == -## =============================== - -SET(cpPlugins_NUMBER_OF_FILES "10" CACHE STRING "Number of compiled files.") -SET(cpPlugins_PROCESS_DIMS "1;2;3" CACHE STRING "Accepted processing dimensions.") -SET(cpPlugins_VISUAL_DIMS "2;3" CACHE STRING "Accepted visual dimensions.") - -OPTION(BUILD_EXAMPLES "Build examples" OFF) -OPTION(BUILD_QT4_COMPONENTS "Build Qt4-based code" OFF) - -SET( - _all_configs - cpPlugins_PROCESS_DIMS - cpPlugins_VISUAL_DIMS - ) -SET(_real_configs) -FOREACH(_cfg ${_all_configs}) - FOREACH(_type ${${_cfg}}) - LIST(APPEND _real_configs "${_cfg}_${_type}") - ENDFOREACH(_type) -ENDFOREACH(_cfg) -SET(cpPlugins_ALL_CONFIGS "${_real_configs}" CACHE INTERNAL "All valid configurations." FORCE) - -## eof - $RCSfile$ diff --git a/cmake/QtTools.cmake b/cmake/QtTools.cmake deleted file mode 100644 index f4dd0cd..0000000 --- a/cmake/QtTools.cmake +++ /dev/null @@ -1,26 +0,0 @@ -## ================================================== -## == Find Qt4 and check if it was well configured == -## ================================================== - -IF(BUILD_QT4_COMPONENTS) - FIND_PACKAGE(Qt4 REQUIRED) - INCLUDE(${QT_USE_FILE}) - SET( - _modules - vtkGUISupportQt - ) - FOREACH(_m ${_modules}) - IF(NOT ${_m}_LOADED) - MESSAGE(FATAL_ERROR "${_m} module is required but not available.") - BREAK() - ENDIF(NOT ${_m}_LOADED) - ENDFOREACH(_m) - SET( - cpPlugins_Qt4_VTKWidget - QVTKWidget - CACHE STRING "Base Qt4-based vtkRenderWindow" - ) - MARK_AS_ADVANCED(CLEAR cpPlugins_Qt4_VTKWidget) -ENDIF(BUILD_QT4_COMPONENTS) - -## eof - $RCSfile$ diff --git a/cmake/cpPluginsConfig.cmake.in b/cmake/cpPluginsConfig.cmake.in deleted file mode 100644 index 0a65b42..0000000 --- a/cmake/cpPluginsConfig.cmake.in +++ /dev/null @@ -1,120 +0,0 @@ -## ================================ -## == Find cpPlugins-cmake tools == -## ================================ - -SET(ITK_DIR "@ITK_DIR@") -SET(VTK_DIR "@VTK_DIR@") -IF("@Qt4_FOUND@" STREQUAL "TRUE") - SET(BUILD_QT4_COMPONENTS ON) - SET(QT_QMAKE_EXECUTABLE "@QT_QMAKE_EXECUTABLE@") -ENDIF("@Qt4_FOUND@" STREQUAL "TRUE") - -## ==================== -## == Find libraries == -## ==================== - -SET( - cpPlugins_AllInstances - cpInstances_BaseObjects - cpInstances_Images - cpInstances_Geometries - cpInstances_Extensions - CACHE STRING "All instances from templated code" - ) -MARK_AS_ADVANCED(FORCE cpPlugins_AllInstances) - -SET( - _all_libs - cpExtensions - cpPlugins - cpPluginsDataObjects - ) -IF(USE_QT4) - LIST(APPEND _all_libs cpBaseQtApplication) - LIST(APPEND _all_libs cp_QCustomPlot) -ENDIF(USE_QT4) -SET(cpPlugins_Libraries ${_all_libs} CACHE STRING "cpPlugins base libraries") -MARK_AS_ADVANCED(FORCE cpPlugins_Libraries) - -SET(_all_libs ${cpPlugins_AllInstances} ${cpPlugins_Libraries}) -SET(_l_locations) -FOREACH(_l ${_all_libs}) - FIND_LIBRARY( - ${_l}_LIB NAMES ${_l} - PATHS - @PROJECT_BINARY_DIR@ - @CMAKE_INSTALL_PREFIX@/bin - @CMAKE_INSTALL_PREFIX@/lib - ${_l_locations} - ) - IF(${_l}_LIB) - MARK_AS_ADVANCED(FORCE ${_l}_LIB) - GET_FILENAME_COMPONENT(_dir ${${_l}_LIB} DIRECTORY) - LIST(APPEND _l_locations ${_dir}) - LIST(REMOVE_DUPLICATES _l_locations) - ENDIF(${_l}_LIB) -ENDFOREACH(_l) -IF(_l_locations) - LINK_DIRECTORIES(${_l_locations}) -ENDIF(_l_locations) - -## ============================== -## == Find include directories == -## ============================== - -## TODO: this is not completely correct!!! -INCLUDE_DIRECTORIES( - @CMAKE_INSTALL_PREFIX@/include - @CMAKE_INSTALL_PREFIX@/include/cpPlugins/cpInstances - @PROJECT_SOURCE_DIR@ - @PROJECT_BINARY_DIR@ - @PROJECT_SOURCE_DIR@/lib - @PROJECT_BINARY_DIR@/lib - @PROJECT_SOURCE_DIR@/lib/cpInstances - @PROJECT_BINARY_DIR@/lib/cpInstances - ) - -## ============================ -## == Find bash applications == -## ============================ - -SET( - _exec_programs - "@cpPlugins_bash_CreateRealConfig_APP@" - "@cpPlugins_bash_CreateInstances_APP@" - "@cpPlugins_bash_CreateDemanglers_APP@" - "@cpPlugins_bash_CreatePlugins_APP@" - "@cpPlugins_bash_HostCreator_APP@" - ) - -SET(_b_locations) -FOREACH(_p ${_exec_programs}) - FIND_PROGRAM( - ${_p}_APP - NAMES ${_p} - HINTS /usr /usr/local - PATHS @CMAKE_INSTALL_PREFIX@/bin @PROJECT_BINARY_DIR@ ${_b_locations} - PATH_SUFFIXES bin sbin - DOC "Where is ${_prog}?" - ) - IF(${_p}_APP) - MARK_AS_ADVANCED(FORCE ${_p}_APP) - GET_FILENAME_COMPONENT(_dir ${${_p}_APP} DIRECTORY) - LIST(APPEND _b_locations ${_dir}) - LIST(REMOVE_DUPLICATES _b_locations) - ENDIF(${_p}_APP) -ENDFOREACH(_p) - -## ========================== -## == Configuration values == -## ========================== - -SET(cpPlugins_NUMBER_OF_FILES "@cpPlugins_NUMBER_OF_FILES@" CACHE STRING "Internal") -SET(cpPlugins_PROCESS_DIMS "@cpPlugins_PROCESS_DIMS@" CACHE STRING "Internal") -SET(cpPlugins_VISUAL_DIMS "@cpPlugins_VISUAL_DIMS@" CACHE STRING "Internal") - -MARK_AS_ADVANCED(FORCE cpPlugins_NUMBER_OF_FILES) -MARK_AS_ADVANCED(FORCE cpPlugins_PROCESS_DIMS) -MARK_AS_ADVANCED(FORCE cpPlugins_VISUAL_DIMS) - -## eof - $RCSfile$ diff --git a/data/data.wxml b/data/data.wxml deleted file mode 100644 index 052e856..0000000 --- a/data/data.wxml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/data/read_write_image.wxml b/data/read_write_image.wxml deleted file mode 100644 index 5277ad1..0000000 --- a/data/read_write_image.wxml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/dependencies/cpPlugins_Install_CMAKE.sh b/dependencies/cpPlugins_Install_CMAKE.sh deleted file mode 100755 index 191927c..0000000 --- a/dependencies/cpPlugins_Install_CMAKE.sh +++ /dev/null @@ -1,198 +0,0 @@ -#!/bin/bash - -## ------------------------------------------------------------------------- -function abspath() -{ - pushd . > /dev/null - if [ -d "$1" ]; then - cd "$1" - dirs -l +0 - else - cd "`dirname \"$1\"`" - cur_dir=`dirs -l +0` - if [ "$cur_dir" == "/" ]; then - echo "$cur_dir`basename \"$1\"`" - else - echo "$cur_dir/`basename \"$1\"`" - fi - fi - popd > /dev/null -} - -## ------------------------------------------------------------------------- -function get_file_extension -{ - valid_extensions=("zip" "tar" "tar.gz" "tar.bz2") - actual_file=`abspath $1` - actual_ext="" - for ext in ${valid_extensions[@]}; do - test_str=`dirname $actual_file`/`basename $actual_file $ext` - if [ $test_str != $actual_file ]; then - actual_ext=$ext - fi - done - echo "$actual_ext" -} - -## ------------------------------------------------------------------------- -function print_help() -{ - echo "Usage: `basename $0` -f=compressed_code -c=source_dir -b=build_dir [-p=instalation_prefix] [-q=qmake_executable]" -} - -## ------------------------------------------------------------------------- -## Analyze command-line arguments -if [ $# -eq 0 ]; then - print_help - exit 1 -fi -prefix="${HOME}/local" -for i in "$@"; do - case $i in - -f=*|--file=*) - source_file="${i#*=}" - shift - ;; - -c=*|--source_dir=*) - source_dir="${i#*=}" - shift - ;; - -b=*|--build_dir=*) - build_dir="${i#*=}" - shift - ;; - -p=*|--prefix=*) - prefix="${i#*=}" - shift - ;; - -q=*|--qmake=*) - qmake_exec="${i#*=}" - shift - ;; - *) - ;; - esac -done - -## Check command line arguments -if [ "x$source_dir" == "x" ]; then - if [ "x$source_file" != "x" ]; then - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - base_dir=`dirname $base_path` - if [ "x$base_ext" != "x" ]; then - source_dir="$base_dir"/`basename $base_path .$base_ext` - else - echo "Error: Input compressed file extension not recognized." - exit 1 - fi - else - print_help - exit 1 - fi -fi -if [ "x$build_dir" == "x" ]; then - if [ "x$source_dir" != "x" ]; then - base_dir=$source_dir - if [ "${source_dir:$((${#str}-1)):1}" == "/" ]; then - base_dir=`echo $source_dir | rev | cut -c 2- | rev` - fi - build_dir="$base_dir-build" - else - print_help - exit 1 - fi -fi - -# Locate qmake executable -if [ "x$qmake_exec" == "x" ]; then - qmake_locations=("/usr/bin" "/usr/local/bin" "${HOME}/local/bin") - for loc in ${qmake_locations[@]}; do - qmake_file="$loc/qmake" - if [ -x $qmake_file ]; then - version=`$qmake_file --version | grep Using\ Qt\ version | cut -d ' ' -f 4` - if [ "${version:0:3}" == "4.8" ]; then - qmake_exec=$qmake_file - fi - fi - done -fi -qmake_exec=`abspath $qmake_exec` -if [ -x $qmake_exec ]; then - qt_options="--qt-gui --qt-qmake=$qmake_exec" -else - qt_options="--no-qt-gui" -fi - -## Other configuration variables -platform=`uname` -number_of_cores=`grep -c ^processor /proc/cpuinfo` -number_of_threads=`expr $number_of_cores / 2` -if [ "x$source_file" != "x" ]; then - source_file=`abspath $source_file` -fi -source_dir=`abspath $source_dir` -build_dir=`abspath $build_dir` - -echo "=====================================================================" -echo "==> Source file : $source_file" -echo "==> Source dir : $source_dir" -echo "==> Build dir : $build_dir" -echo "==> Prefix : $prefix" -echo "==> qmake : $qmake_exec" -echo "==> Qt options : $qt_options" -echo "==> Platform : $platform" -echo "==> Number of cores : $number_of_cores" -echo "==> Number of threads : $number_of_threads" -echo "=====================================================================" -read -n1 -r -p "Continue? [Y/N]... " key -echo -if [ "$key" != 'Y' -a "$key" != 'y' ] ; then - exit 1 -fi - -## Create paths -if [ "x$source_file" != "x" ]; then - echo -n "==> Cleaning directories... " - rm -rf $source_dir - rm -rf $build_dir - echo "done." - echo -n "==> Creating directories... " - mkdir -p $source_dir - mkdir -p $build_dir - echo "done." -fi - -## Extract source code -if [ "x$source_file" != "x" ]; then - echo -n "==> Extracting sources... " - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - if [ "$base_ext" == "zip" ]; then - echo unzip $base_path - elif [ "$base_ext" == "tar" ]; then - tar xf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.gz" ]; then - tar xzf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.bz2" ]; then - tar xjf $base_path -C $source_dir --strip-components=1 - fi - echo "done." -fi - -echo "==> Configuring sources... " -cd $build_dir -$source_dir/bootstrap --prefix=$prefix $qt_options -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $build_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $build_dir -make -j install -echo "==> Installing package... done." - -## eof - $RCSfile$ diff --git a/dependencies/cpPlugins_Install_Dependencies.py b/dependencies/cpPlugins_Install_Dependencies.py deleted file mode 100644 index b1d7813..0000000 --- a/dependencies/cpPlugins_Install_Dependencies.py +++ /dev/null @@ -1,383 +0,0 @@ -#!/usr/bin/python - -import glob, multiprocessing, os, platform, readline -from distutils import spawn - -## -------------------- -## -- Various values -- -## -------------------- - -system_name = platform.system( ) -process_count = multiprocessing.cpu_count( ) / 2 -home_dir = os.environ[ "HOME" ] - -## ------------------------ -## -- Filename completer -- -## ------------------------ - -def filename_completer( text, state ): - return ( glob.glob( text + '*' ) + [ None ] )[ state ] -# fed - -def get_filepath( message ): - readline.set_completer_delims( ' \t\n;' ) - readline.parse_and_bind( "tab: complete" ) - readline.set_completer( filename_completer ) - return os.path.abspath( raw_input( message ) ) -# fed - -## -------------------- -## -- File extractor -- -## -------------------- - -def file_extract( filename, outdir ): - real_ext = None - for ext in [ ".zip", ".tar", ".tar.gz", ".tar.bz2" ]: - if filename[ len( filename ) - len( ext ) : ] == ext: - real_ext = ext - # fi - # rof - command = None - if real_ext == ".zip": - command = "unzip " + filename + " -d " + outdir - elif real_ext == ".tar": - command = "tar xf " + filename + " -C " + outdir + " --strip-components=1" - elif real_ext == ".tar.gz": - command = "tar xzf " + filename + " -C " + outdir + " --strip-components=1" - elif real_ext == ".tar.bz2": - command = "tar xjf " + filename + " -C " + outdir + " --strip-components=1" - # fi - if command <> None: - print( "\tExtracting " + filename + "..." ) - res = os.system( "mkdir -p " + outdir + " && " + command ) - print( "\t\tdone." ) - if res == 0: - return True - else: - return False - else: - return False - # fi -# fed - -## ------------------ -## -- Look for Qt4 -- -## ------------------ - -qmake_locations = [] -qmake_progs = [] -if system_name == "Linux": - qmake_locations = [ - "/usr/bin", - "/usr/local/bin", - home_dir + "/bin", - home_dir + "/local/bin" - ] - qmake_progs = [ "qmake", "qmake-qt4" ] -# fi - -qmake_paths = [] -for prog in qmake_progs: - for loc in qmake_locations: - path = spawn.find_executable( loc + "/" + prog ) - if path <> None: - qmake_paths.append( path ) - # rof -# rof - -print( "Please choose one configuration for Qt4:" ) -for i in range( len( qmake_paths ) ): - print( "\t" + str( i ) + ": " + qmake_paths[ i ] ) -# rof -print( "\t" + str( len( qmake_paths ) + 0 ) + ": Give another installation path (path to qmake)." ) -print( "\t" + str( len( qmake_paths ) + 1 ) + ": Build from scratch." ) -qmake_opt = -1 -while qmake_opt == -1: - qmake_opt = int( raw_input( "\t---> " ) ) - if qmake_opt < 0 or qmake_opt > len( qmake_paths ) + 1: - qmake_opt = -1 - # fi -# elihw - -qmake_exec = None -qmake_src = None -if qmake_opt == len( qmake_paths ): - qmake_exec = get_filepath( "Choose your own Qt4 installation: " ) - while not os.path.isfile( qmake_exec ): - qmake_exec = get_filepath( "Choose your own Qt4 installation: " ) - # elihw -elif qmake_opt == len( qmake_paths ) + 1: - qmake_src = get_filepath( "Choose your own Qt4 source file: " ) - while not os.path.isfile( qmake_src ): - qmake_src = get_filepath( "Choose your own Qt4 source file: " ) - # elihw -else: - qmake_exec = qmake_paths[ qmake_opt ] -# fi - -## -------------------- -## -- Look for CMake -- -## -------------------- - -cmake_locations = [] -cmake_progs = [] -if system_name == "Linux": - cmake_locations = [ - "/usr/bin", - "/usr/local/bin", - home_dir + "/bin", - home_dir + "/local/bin" - ] - cmake_progs = [ "cmake" ] -# fi - -cmake_paths = [] -for prog in cmake_progs: - for loc in cmake_locations: - path = spawn.find_executable( loc + "/" + prog ) - if path <> None: - cmake_paths.append( path ) - # rof -# rof - -print( "Please choose one configuration for CMake:" ) -for i in range( len( cmake_paths ) ): - print( "\t" + str( i ) + ": " + cmake_paths[ i ] ) -# rof -print( "\t" + str( len( cmake_paths ) + 0 ) + ": Give another installation path (path to cmake)." ) -print( "\t" + str( len( cmake_paths ) + 1 ) + ": Build from scratch." ) -cmake_opt = -1 -while cmake_opt == -1: - cmake_opt = int( raw_input( "\t---> " ) ) - if cmake_opt < 0 or cmake_opt > len( cmake_paths ) + 1: - cmake_opt = -1 - # fi -# elihw - -cmake_exec = None -cmake_src = None -if cmake_opt == len( cmake_paths ): - cmake_exec = get_filepath( "Choose your own CMake installation: " ) - while not os.path.isfile( cmake_exec ): - cmake_exec = get_filepath( "Choose your own CMake installation: " ) - # elihw -elif cmake_opt == len( cmake_paths ) + 1: - cmake_src = get_filepath( "Choose your own CMake source file: " ) - while not os.path.isfile( cmake_src ): - cmake_src = get_filepath( "Choose your own CMake source file: " ) - # elihw -else: - cmake_exec = cmake_paths[ cmake_opt ] -# fi - -## ------------------ -## -- Look for ITK -- -## ------------------ - -itk_src = get_filepath( "Choose your own ITK source file: " ) -while not os.path.isfile( itk_src ): - itk_src = get_filepath( "Choose your own ITK source file: " ) -# elihw - -## ------------------ -## -- Look for VTK -- -## ------------------ - -vtk_src = get_filepath( "Choose your own VTK source file: " ) -while not os.path.isfile( vtk_src ): - vtk_src = get_filepath( "Choose your own VTK source file: " ) -# elihw - -## -------------------------- -## -- Miscelaneous options -- -## -------------------------- - -build_prefix = get_filepath( "Build prefix: " ) -install_prefix = get_filepath( "Installation prefix: " ) -build_type = raw_input( "Build type [release/debug]: " ).lower( ) - -os.system( "mkdir -p " + build_prefix ) -os.system( "mkdir -p " + install_prefix ) - -## ------------------- -## -- Extract files -- -## ------------------- - -print( "Extracting source code... " ) -if qmake_src <> None: - file_extract( qmake_src, build_prefix + "/qt4-source" ) -# fi -if cmake_src <> None: - file_extract( cmake_src, build_prefix + "/cmake-source" ) -# fi -file_extract( itk_src, build_prefix + "/itk-source" ) -file_extract( vtk_src, build_prefix + "/vtk-source" ) -print( " done!" ) - -## --------------- -## -- Build Qt4 -- -## --------------- - -if qmake_src <> None: - full = raw_input( "\tWould you like to perform a full Qt4 build [y/n]? " ) - full.lower( ) - - qt4_source = os.path.abspath( build_prefix + "/qt4-source" ) - qt4_build = os.path.abspath( build_prefix + "/qt4-build" ) - os.system( "mkdir -p " + qt4_build ) - - config_command = qt4_source + "/configure" - config_command += " -prefix " + install_prefix - config_command += " -" + build_type - config_command += " -opensource -shared -fast -no-webkit -optimized-qmake -confirm-license" - if full[ 0 ] == "n": - config_command += " -no-phonon -no-phonon-backend -no-openvg -nomake demos -nomake examples" - # fi - ## MACOS: -no-framework - - ## Build and install - res = os.system( "cd " + qt4_build + " && " + config_command ) - if res <> 0: - print( "Error configuring Qt4." ) - exit( 1 ) - # fi - res = os.system( "cd " + qt4_build + " && make -j" + str( process_count ) ) - if res <> 0: - print( "Error compiling Qt4." ) - exit( 1 ) - # fi - res = os.system( "cd " + qt4_build + " && make -j install" ) - if res <> 0: - print( "Error installing Qt4." ) - exit( 1 ) - # fi - qmake_exec = install_prefix + "/bin/qmake" -# fi - -## ----------------- -## -- Build CMake -- -## ----------------- - -if cmake_src <> None: - cmake_source = os.path.abspath( build_prefix + "/cmake-source" ) - cmake_build = os.path.abspath( build_prefix + "/cmake-build" ) - os.system( "mkdir -p " + cmake_build ) - - config_command = cmake_source + "/bootstrap" - config_command += " --prefix " + install_prefix - if qmake_exec <> None: - config_command += " --qt-gui --qt-qmake=" + qmake_exec - else: - config_command += " --no-qt-gui" - # fi - - ## Build and install - res = os.system( "cd " + cmake_build + " && " + config_command ) - if res <> 0: - print( "Error configuring CMake." ) - exit( 1 ) - # fi - res = os.system( "cd " + cmake_build + " && make -j" + str( process_count ) ) - if res <> 0: - print( "Error compiling CMake." ) - exit( 1 ) - # fi - res = os.system( "cd " + cmake_build + " && make -j install" ) - if res <> 0: - print( "Error installing CMake." ) - exit( 1 ) - # fi - cmake_exec = install_prefix + "/bin/cmake" -# fi - -## --------------- -## -- Build VTK -- -## --------------- - -vtk_source = os.path.abspath( build_prefix + "/vtk-source" ) -vtk_build = os.path.abspath( build_prefix + "/vtk-build" ) -os.system( "mkdir -p " + vtk_build ) - -kitware_build = "MinSizeRel" -if build_type == "debug": - kitware_build = "Debug" -# fi - -vtk_configure = cmake_exec -vtk_configure += " -DCMAKE_CXX_FLAGS:STRING=-std=c++11" -vtk_configure += " -DBUILD_DOCUMENTATION:BOOL=OFF" -vtk_configure += " -DBUILD_EXAMPLES:BOOL=OFF" -vtk_configure += " -DBUILD_SHARED_LIBS:BOOL=ON" -vtk_configure += " -DBUILD_TESTING:BOOL=OFF" -vtk_configure += " -DCMAKE_BUILD_TYPE:STRING=" + kitware_build -if qmake_exec <> None: - vtk_configure += " -DQT_QMAKE_EXECUTABLE:PATH=" + qmake_exec - vtk_configure += " -DModule_vtkGUISupportQt:BOOL=ON" - vtk_configure += " -DModule_vtkGUISupportQtOpenGL:BOOL=ON" - vtk_configure += " -DModule_vtkGUISupportQtSQL:BOOL=OFF" - vtk_configure += " -DModule_vtkGUISupportQtWebkit:BOOL=OFF" -# fi -vtk_configure += " -DCMAKE_INSTALL_PREFIX:PATH=" + install_prefix -vtk_configure += " " + vtk_source - -## Build and install -res = os.system( "cd " + vtk_build + " && " + vtk_configure ) -if res <> 0: - print( "Error configuring VTK." ) - exit( 1 ) -# fi -res = os.system( "cd " + vtk_build + " && make -j" + str( process_count ) ) -if res <> 0: - print( "Error compiling VTK." ) - exit( 1 ) -# fi -res = os.system( "cd " + vtk_build + " && make -j install" ) -if res <> 0: - print( "Error installing VTK." ) - exit( 1 ) -# fi - -## --------------- -## -- Build ITK -- -## --------------- - -itk_source = os.path.abspath( build_prefix + "/itk-source" ) -itk_build = os.path.abspath( build_prefix + "/itk-build" ) -os.system( "mkdir -p " + itk_build ) - -kitware_build = "MinSizeRel" -if build_type == "debug": - kitware_build = "Debug" -# fi - -itk_configure = cmake_exec -itk_configure += " -DCMAKE_CXX_FLAGS:STRING=-std=c++11" -itk_configure += " -DBUILD_DOCUMENTATION:BOOL=OFF" -itk_configure += " -DBUILD_EXAMPLES:BOOL=OFF" -itk_configure += " -DBUILD_SHARED_LIBS:BOOL=ON" -itk_configure += " -DBUILD_TESTING:BOOL=OFF" -itk_configure += " -DCMAKE_BUILD_TYPE:STRING=" + kitware_build -itk_configure += " -DModule_ITKReview:BOOL=ON" -itk_configure += " -DModule_ITKVtkGlue:BOOL=OFF" -itk_configure += " -DModule_ParabolicMorphology:BOOL=ON" -itk_configure += " -DCMAKE_INSTALL_PREFIX:PATH=" + install_prefix -itk_configure += " " + itk_source - -## Build and install -res = os.system( "cd " + itk_build + " && " + itk_configure ) -if res <> 0: - print( "Error configuring ITK." ) - exit( 1 ) -# fi -res = os.system( "cd " + itk_build + " && make -j" + str( process_count ) ) -if res <> 0: - print( "Error compiling ITK." ) - exit( 1 ) -# fi -res = os.system( "cd " + itk_build + " && make -j install" ) -if res <> 0: - print( "Error installing ITK." ) - exit( 1 ) -# fi - -## eof - $RCSfile$ diff --git a/dependencies/cpPlugins_Install_ITK.sh b/dependencies/cpPlugins_Install_ITK.sh deleted file mode 100755 index d4b90c5..0000000 --- a/dependencies/cpPlugins_Install_ITK.sh +++ /dev/null @@ -1,216 +0,0 @@ -#!/bin/bash - -## ------------------------------------------------------------------------- -function abspath() -{ - pushd . > /dev/null - if [ -d "$1" ]; then - cd "$1" - dirs -l +0 - else - cd "`dirname \"$1\"`" - cur_dir=`dirs -l +0` - if [ "$cur_dir" == "/" ]; then - echo "$cur_dir`basename \"$1\"`" - else - echo "$cur_dir/`basename \"$1\"`" - fi - fi - popd > /dev/null -} - -## ------------------------------------------------------------------------- -function get_file_extension -{ - valid_extensions=("zip" "tar" "tar.gz" "tar.bz2") - actual_file=`abspath $1` - actual_ext="" - for ext in ${valid_extensions[@]}; do - test_str=`dirname $actual_file`/`basename $actual_file $ext` - if [ $test_str != $actual_file ]; then - actual_ext=$ext - fi - done - echo "$actual_ext" -} - -## ------------------------------------------------------------------------- -function print_help() -{ - echo "Usage: `basename $0` -f=compressed_code -c=source_dir -b=build_dir [-p=instalation_prefix] [-m=cmake_executable] [-t=build_type[MinSizeRel/Debug/Release]]" -} - -## ------------------------------------------------------------------------- -## Analyze command-line arguments -if [ $# -eq 0 ]; then - print_help - exit 1 -fi -prefix="${HOME}/local" -build_type="MinSizeRel" -for i in "$@"; do - case $i in - -f=*|--file=*) - source_file="${i#*=}" - shift - ;; - -c=*|--source_dir=*) - source_dir="${i#*=}" - shift - ;; - -b=*|--build_dir=*) - build_dir="${i#*=}" - shift - ;; - -t=*|--build_type=*) - build_type="${i#*=}" - shift - ;; - -p=*|--prefix=*) - prefix="${i#*=}" - shift - ;; - -m=*|--cmake=*) - cmake_exec="${i#*=}" - shift - ;; - *) - ;; - esac -done - -## Check command line arguments -if [ "x$source_dir" == "x" ]; then - if [ "x$source_file" != "x" ]; then - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - base_dir=`dirname $base_path` - if [ "x$base_ext" != "x" ]; then - source_dir="$base_dir"/`basename $base_path .$base_ext` - else - echo "Error: Input compressed file extension not recognized." - exit 1 - fi - else - print_help - exit 1 - fi -fi -if [ "x$build_dir" == "x" ]; then - if [ "x$source_dir" != "x" ]; then - base_dir=$source_dir - if [ "${source_dir:$((${#str}-1)):1}" == "/" ]; then - base_dir=`echo $source_dir | rev | cut -c 2- | rev` - fi - build_dir="$base_dir-build" - else - print_help - exit 1 - fi -fi - -## Locate cmake executable -if [ "x$cmake_exec" == "x" ]; then - cmake_locations=("/usr/bin" "/usr/local/bin" "${HOME}/local/bin") - cmake_ver="" - for loc in ${cmake_locations[@]}; do - cmake_file="$loc/cmake" - if [ -x $cmake_file ]; then - str=`$cmake_file --version | grep version` - version=${str:14} - if [ "$cmake_ver" \< "$version" ]; then - cmake_ver=$version - cmake_exec=$cmake_file - fi - fi - done -fi -if [ ! -x $cmake_exec ]; then - echo "ERROR: no valid cmake found." - exit 1 -fi -cmake_exec=`abspath $cmake_exec` - -## Other configuration variables -platform=`uname` -number_of_cores=`grep -c ^processor /proc/cpuinfo` -number_of_threads=`expr $number_of_cores / 2` -if [ "x$source_file" != "x" ]; then - source_file=`abspath $source_file` -fi -source_dir=`abspath $source_dir` -build_dir=`abspath $build_dir` - -echo "=====================================================================" -echo "==> Source file : $source_file" -echo "==> Source dir : $source_dir" -echo "==> Build dir : $build_dir" -echo "==> Build type : $build_type" -echo "==> Prefix : $prefix" -echo "==> cmake : $cmake_exec" -echo "==> Platform : $platform" -echo "==> Number of cores : $number_of_cores" -echo "==> Number of threads : $number_of_threads" -echo "=====================================================================" -read -n1 -r -p "Continue? [Y/N]... " key -echo -if [ "$key" != 'Y' -a "$key" != 'y' ] ; then - exit 1 -fi - -## Create paths -if [ "x$source_file" != "x" ]; then - echo -n "==> Cleaning directories... " - rm -rf $source_dir - rm -rf $build_dir - echo "done." - echo -n "==> Creating directories... " - mkdir -p $source_dir - mkdir -p $build_dir - echo "done." -fi - -## Extract source code -if [ "x$source_file" != "x" ]; then - echo -n "==> Extracting sources... " - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - if [ "$base_ext" == "zip" ]; then - echo unzip $base_path - elif [ "$base_ext" == "tar" ]; then - tar xf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.gz" ]; then - tar xzf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.bz2" ]; then - tar xjf $base_path -C $source_dir --strip-components=1 - fi - echo "done." -fi - -echo "==> Configuring sources... " -cd $build_dir -$cmake_exec \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DCMAKE_BUILD_TYPE:STRING=$build_type \ - -DModule_ITKReview:BOOL=ON \ - -DModule_ITKVtkGlue:BOOL=OFF \ - -DModule_ParabolicMorphology:BOOL=ON \ - -DCMAKE_INSTALL_PREFIX:PATH=$prefix \ - ${source_dir} -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $build_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $build_dir -make -j install -echo "==> Installing package... done." - -## eof - $RCSfile$ diff --git a/dependencies/cpPlugins_Install_QT4.sh b/dependencies/cpPlugins_Install_QT4.sh deleted file mode 100755 index 36c5d13..0000000 --- a/dependencies/cpPlugins_Install_QT4.sh +++ /dev/null @@ -1,219 +0,0 @@ -#!/bin/bash - -function abspath() -{ - pushd . > /dev/null - if [ -d "$1" ]; then - cd "$1" - dirs -l +0 - else - cd "`dirname \"$1\"`" - cur_dir=`dirs -l +0` - if [ "$cur_dir" == "/" ]; then - echo "$cur_dir`basename \"$1\"`" - else - echo "$cur_dir/`basename \"$1\"`" - fi - fi - popd > /dev/null -} - -function get_file_extension -{ - valid_extensions=("zip" "tar" "tar.gz" "tar.bz2") - actual_file=`abspath $1` - actual_ext="" - for ext in ${valid_extensions[@]}; do - test_str=`dirname $actual_file`/`basename $actual_file $ext` - if [ $test_str != $actual_file ]; then - actual_ext=$ext - fi - done - echo "$actual_ext" -} - -function print_help() -{ - echo "Usage: `basename $0` -f=compressed_code -c=source_dir -b=build_dir [-t=build_type[release/debug]] [-p=instalation_prefix] [--full]" -} - -## Analyze command-line arguments -if [ $# -eq 0 ]; then - print_help - exit 1 -fi -full_compile="0" -prefix="${HOME}/local" -build_type="release" -for i in "$@"; do - case $i in - -f=*|--file=*) - source_file="${i#*=}" - shift - ;; - -c=*|--source_dir=*) - source_dir="${i#*=}" - shift - ;; - -b=*|--build_dir=*) - build_dir="${i#*=}" - shift - ;; - -t=*|--build_type=*) - build_type="${i#*=}" - shift - ;; - -p=*|--prefix=*) - prefix="${i#*=}" - shift - ;; - --full) - full_compile="1" - shift - ;; - *) - ;; - esac -done - -## Check command line arguments -if [ "x$source_dir" == "x" ]; then - if [ "x$source_file" != "x" ]; then - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - base_dir=`dirname $base_path` - if [ "x$base_ext" != "x" ]; then - source_dir="$base_dir"/`basename $base_path .$base_ext` - else - echo "Error: Input compressed file extension not recognized." - exit 1 - fi - else - print_help - exit 1 - fi -fi -if [ "x$build_dir" == "x" ]; then - if [ "x$source_dir" != "x" ]; then - base_dir=$source_dir - if [ "${source_dir:$((${#str}-1)):1}" == "/" ]; then - base_dir=`echo $source_dir | rev | cut -c 2- | rev` - fi - build_dir="$base_dir-build" - else - print_help - exit 1 - fi -fi - -## Other configuration variables -platform=`uname` -particular_options="" -patch_file="" -if [ "$platform" == "Darwin" ]; then - particular_options=-no-framework - bash_path=`abspath $0` - bash_dir=`dirname $bash_path` - patch_file=$bash_dir/qt-4.8.6.patch -fi -number_of_cores=`grep -c ^processor /proc/cpuinfo` -number_of_threads=`expr $number_of_cores / 2` -if [ "x$source_file" != "x" ]; then - source_file=`abspath $source_file` -fi -source_dir=`abspath $source_dir` -build_dir=`abspath $build_dir` - -echo "=====================================================================" -echo "==> Source file : $source_file" -echo "==> Source dir : $source_dir" -echo "==> Build dir : $build_dir" -echo "==> Build type : $build_type" -echo "==> Prefix : $prefix" -echo "==> Full compile : $full_compile" -echo "==> Platform : $platform" -echo "==> Number of cores : $number_of_cores" -echo "==> Number of threads : $number_of_threads" -echo "==> Patch file : $patch_file" -echo "=====================================================================" -read -n1 -r -p "Continue? [Y/N]... " key -echo -if [ "$key" != 'Y' -a "$key" != 'y' ] ; then - exit 1 -fi - -## Create paths -if [ "x$source_file" != "x" ]; then - echo -n "==> Cleaning directories... " - rm -rf $source_dir - rm -rf $build_dir - echo "done." - echo -n "==> Creating directories... " - mkdir -p $source_dir - mkdir -p $build_dir - echo "done." -fi - -## Extract source code -if [ "x$source_file" != "x" ]; then - echo -n "==> Extracting sources... " - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - if [ "$base_ext" == "zip" ]; then - echo unzip $base_path - elif [ "$base_ext" == "tar" ]; then - tar xf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.gz" ]; then - tar xzf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.bz2" ]; then - tar xjf $base_path -C $source_dir --strip-components=1 - fi - echo "done." -fi - -# Apply patch -if [ "x$patch_file" != "x" ]; then - echo -n "==> Applying patch... " - cd $source_dir - patch -p0 < $patch_file - echo "done." -fi - -echo "==> Configuring sources... " -cd $build_dir -if [ "x$full_compile" == "xfull" ]; then - $source_dir/configure \ - -prefix $prefix \ - -$build_type \ - -opensource -shared -fast \ - -no-webkit \ - -optimized-qmake \ - $particular_options \ - -confirm-license -else - $source_dir/configure \ - -prefix $prefix \ - -$build_type \ - -opensource -shared -fast \ - -no-phonon \ - -no-phonon-backend \ - -no-webkit \ - -no-openvg \ - -nomake demos -nomake examples \ - -optimized-qmake \ - $particular_options \ - -confirm-license -fi -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $build_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $build_dir -make -j install -echo "==> Installing package... done." - -## eof - $RCSfile$ diff --git a/dependencies/cpPlugins_Install_VTK.sh b/dependencies/cpPlugins_Install_VTK.sh deleted file mode 100755 index 9c5776a..0000000 --- a/dependencies/cpPlugins_Install_VTK.sh +++ /dev/null @@ -1,256 +0,0 @@ -#!/bin/bash - -## ------------------------------------------------------------------------- -function abspath() -{ - pushd . > /dev/null - if [ -d "$1" ]; then - cd "$1" - dirs -l +0 - else - cd "`dirname \"$1\"`" - cur_dir=`dirs -l +0` - if [ "$cur_dir" == "/" ]; then - echo "$cur_dir`basename \"$1\"`" - else - echo "$cur_dir/`basename \"$1\"`" - fi - fi - popd > /dev/null -} - -## ------------------------------------------------------------------------- -function get_file_extension -{ - valid_extensions=("zip" "tar" "tar.gz" "tar.bz2") - actual_file=`abspath $1` - actual_ext="" - for ext in ${valid_extensions[@]}; do - test_str=`dirname $actual_file`/`basename $actual_file $ext` - if [ $test_str != $actual_file ]; then - actual_ext=$ext - fi - done - echo "$actual_ext" -} - -## ------------------------------------------------------------------------- -function print_help() -{ - echo "Usage: `basename $0` -f=compressed_code -c=source_dir -b=build_dir [-p=instalation_prefix] [-q=qmake_executable] [-m=cmake_executable] [-t=build_type[MinSizeRel/Debug/Release]]" -} - -## ------------------------------------------------------------------------- -## Analyze command-line arguments -if [ $# -eq 0 ]; then - print_help - exit 1 -fi -prefix="${HOME}/local" -build_type="MinSizeRel" -for i in "$@"; do - case $i in - -f=*|--file=*) - source_file="${i#*=}" - shift - ;; - -c=*|--source_dir=*) - source_dir="${i#*=}" - shift - ;; - -b=*|--build_dir=*) - build_dir="${i#*=}" - shift - ;; - -t=*|--build_type=*) - build_type="${i#*=}" - shift - ;; - -p=*|--prefix=*) - prefix="${i#*=}" - shift - ;; - -m=*|--cmake=*) - cmake_exec="${i#*=}" - shift - ;; - -q=*|--qmake=*) - qmake_exec="${i#*=}" - shift - ;; - *) - ;; - esac -done - -## Check command line arguments -if [ "x$source_dir" == "x" ]; then - if [ "x$source_file" != "x" ]; then - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - base_dir=`dirname $base_path` - if [ "x$base_ext" != "x" ]; then - source_dir="$base_dir"/`basename $base_path .$base_ext` - else - echo "Error: Input compressed file extension not recognized." - exit 1 - fi - else - print_help - exit 1 - fi -fi -if [ "x$build_dir" == "x" ]; then - if [ "x$source_dir" != "x" ]; then - base_dir=$source_dir - if [ "${source_dir:$((${#str}-1)):1}" == "/" ]; then - base_dir=`echo $source_dir | rev | cut -c 2- | rev` - fi - build_dir="$base_dir-build" - else - print_help - exit 1 - fi -fi - -## Locate cmake executable -if [ "x$cmake_exec" == "x" ]; then - cmake_locations=("/usr/bin" "/usr/local/bin" "${HOME}/local/bin") - cmake_ver="" - for loc in ${cmake_locations[@]}; do - cmake_file="$loc/cmake" - if [ -x $cmake_file ]; then - str=`$cmake_file --version | grep version` - version=${str:14} - if [ "$cmake_ver" \< "$version" ]; then - cmake_ver=$version - cmake_exec=$cmake_file - fi - fi - done -fi -if [ ! -x $cmake_exec ]; then - echo "ERROR: no valid cmake found." - exit 1 -fi -cmake_exec=`abspath $cmake_exec` - -# Locate qmake executable -if [ "x$qmake_exec" == "x" ]; then - qmake_locations=("/usr/bin" "/usr/local/bin" "${HOME}/local/bin") - for loc in ${qmake_locations[@]}; do - qmake_file="$loc/qmake" - if [ -x $qmake_file ]; then - version=`$qmake_file --version | grep Using\ Qt\ version | cut -d ' ' -f 4` - if [ "${version:0:3}" == "4.8" ]; then - qmake_exec=$qmake_file - fi - fi - done -fi -qmake_exec=`abspath $qmake_exec` -if [ -x $qmake_exec ]; then - use_qt="1" -else - use_qt="0" -fi - -## Other configuration variables -platform=`uname` -number_of_cores=`grep -c ^processor /proc/cpuinfo` -number_of_threads=`expr $number_of_cores / 2` -if [ "x$source_file" != "x" ]; then - source_file=`abspath $source_file` -fi -source_dir=`abspath $source_dir` -build_dir=`abspath $build_dir` - -echo "=====================================================================" -echo "==> Source file : $source_file" -echo "==> Source dir : $source_dir" -echo "==> Build dir : $build_dir" -echo "==> Build type : $build_type" -echo "==> Prefix : $prefix" -echo "==> cmake : $cmake_exec" -echo "==> qmake : $qmake_exec" -echo "==> Use Qt : $use_qt" -echo "==> Platform : $platform" -echo "==> Number of cores : $number_of_cores" -echo "==> Number of threads : $number_of_threads" -echo "=====================================================================" -read -n1 -r -p "Continue? [Y/N]... " key -echo -if [ "$key" != 'Y' -a "$key" != 'y' ] ; then - exit 1 -fi - -## Create paths -if [ "x$source_file" != "x" ]; then - echo -n "==> Cleaning directories... " - rm -rf $source_dir - rm -rf $build_dir - echo "done." - echo -n "==> Creating directories... " - mkdir -p $source_dir - mkdir -p $build_dir - echo "done." -fi - -## Extract source code -if [ "x$source_file" != "x" ]; then - echo -n "==> Extracting sources... " - base_path=`abspath $source_file` - base_ext=`get_file_extension $base_path` - if [ "$base_ext" == "zip" ]; then - echo unzip $base_path - elif [ "$base_ext" == "tar" ]; then - tar xf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.gz" ]; then - tar xzf $base_path -C $source_dir --strip-components=1 - elif [ "$base_ext" == "tar.bz2" ]; then - tar xjf $base_path -C $source_dir --strip-components=1 - fi - echo "done." -fi - -echo "==> Configuring sources... " -cd $build_dir -if [ "$use_qt" == "1" ]; then - $cmake_exec \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DQT_QMAKE_EXECUTABLE:PATH=$qmake_exec \ - -DCMAKE_BUILD_TYPE:STRING=$build_type \ - -DModule_vtkGUISupportQt:BOOL=ON \ - -DModule_vtkGUISupportQtOpenGL:BOOL=ON \ - -DModule_vtkGUISupportQtSQL:BOOL=OFF \ - -DModule_vtkGUISupportQtWebkit:BOOL=OFF \ - -DCMAKE_INSTALL_PREFIX:PATH=$prefix \ - ${source_dir} -else - $cmake_exec \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DCMAKE_BUILD_TYPE:STRING=$build_type \ - -DCMAKE_INSTALL_PREFIX:PATH=$prefix \ - ${source_dir} -fi -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $build_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $build_dir -make -j install -echo "==> Installing package... done." - -## eof - $RCSfile$ diff --git a/dependencies/cpPlugins_ThirdParty_Install_linux.sh b/dependencies/cpPlugins_ThirdParty_Install_linux.sh deleted file mode 100755 index a2c92dc..0000000 --- a/dependencies/cpPlugins_ThirdParty_Install_linux.sh +++ /dev/null @@ -1,317 +0,0 @@ -#!/bin/bash - -## ==================================== -## == Some base configuration values == -## ==================================== - -cmake_min_version="3.0" -qt_min_version="4.8" -number_of_cores=`grep -c ^processor /proc/cpuinfo` -number_of_threads=`expr $number_of_cores / 2` - -## ================================= -## == Compare two version strings == -## ================================= - -function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; } - -## ============================== -## == Try to locate base tools == -## ============================== - -gpp_exe=`which g++` -if [ -z "gpp_exe" ]; then - echo "ERROR: \"g++\" program was not found." - echo "ERROR: Please install \"g++\"" -fi - -make_exe=`which make` -if [ -z "$make_exe" ]; then - echo "ERROR: \"make\" program was not found." - echo "ERROR: Please install \"make\"" -fi - -## =============== -## == Verify Qt == -## =============== - -read -p "Do you want to use Qt4.8? [y/N] " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - cont=true - qmake_exe=`which qmake` - while [ $cont == true ]; do - if [ -z "$qmake_exe" ]; then - read -e -p "Please provide a valid location for qmake: " tmp - eval tmp=$tmp - qmake_exe=`readlink -f $tmp` - fi - read -p "I am going to use \"$qmake_exe\" as the entry tool for Qt. Is this ok? [y/N] " -n 1 -r - echo - if [[ $REPLY =~ ^[Nn]$ ]]; then - qmake_exe="" - else - cont=false - fi - done - qt_version=`$qmake_exe -v | grep Using\ Qt\ version | sed 's/Using\ Qt\ version\ //g'` - if version_gt $qt_min_version $qt_version; then - echo "FATAL ERROR: your Qt version is $qt_version, but needed version should be at least $qt_min_version" - fi -fi - -## ================== -## == Verify cmake == -## ================== - -cmake_qt_options="--no-qt-gui" -if [ -x "$qmake_exe" ]; then - cmake_qt_options="--qt-gui --qt-qmake=$qmake_exe" -fi - -cont=true -cmake_exe=`which cmake` -while [ $cont == true ]; do - if [ -z "$cmake_exe" ]; then - read -e -p "Please provide a valid location for cmake: " tmp - eval tmp=$tmp - cmake_exe=`readlink -f $tmp` - fi - read -p "I am going to use \"$cmake_exe\". Is this ok? [y/N] " -n 1 -r - echo - if [[ $REPLY =~ ^[Nn]$ ]]; then - cmake_exe="" - else - cont=false - fi -done -if [ -z $cmake_exe ]; then - echo "FATAL ERROR: cmake is really needed to build cpPlugins." - exit 1 -fi - -cmake_mime=`file -bzk --mime-type $cmake_exe` -if [ "$cmake_mime" != "application/x-executable" ]; then - echo "WARNING: I will try to compile cmake..." - if [[ -f $cmake_exe ]]; then - if [ "$cmake_mime" == "application/x-tar" ]; then - sub_mime=`file -b --mime-type $cmake_exe` - if [ $sub_mime == "application/gzip" ]; then - cmake_source_dir=`dirname $cmake_exe`/`basename $cmake_exe .tar.gz` - cmake_binary_dir=`dirname $cmake_exe`/`basename $cmake_exe .tar.gz`-build - echo -n "==> Extracting cmake sources... " - rm -rf $cmake_source_dir $cmake_binary_dir - mkdir -p $cmake_source_dir $cmake_binary_dir - tar xzf $cmake_exe -C $cmake_source_dir --strip-components=1 - echo "done." - fi - fi - elif [[ -d $cmake_exe ]]; then - cmake_source_dir="$cmake_exe" - cmake_binary_dir="$cmake_exe"-build - else - echo "FATAL ERROR: $cmake_exe is not a valid file/directory" - exit 1 - fi - - read -e -p "==> Please provide instalation location for \"cmake\": " tmp - eval tmp=$tmp - cmake_prefix=`readlink -f $tmp` - - echo "==> Configuring sources... " - cd $cmake_binary_dir - $cmake_source_dir/bootstrap --prefix=$cmake_prefix $cmake_qt_options - echo "==> Configuring sources... done." - - echo "==> Compiling sources..." - cd $cmake_binary_dir - make -j$number_of_threads - echo "==> Compiling sources... done." - - echo "==> Installing package..." - cd $cmake_binary_dir - make -j install - echo "==> Installing package... done." - cmake_exe=$cmake_binary_dir/bin/cmake -fi -cmake_version=`$cmake_exe --version | grep version | sed 's/cmake\ version\ //g'` - -if version_gt $cmake_min_version $cmake_version; then - echo "FATAL ERROR: your cmake version is $cmake_version, but needed version should be at least $cmake_min_version" -fi - -## =============== -## == Build VTK == -## =============== - -cont=true -vtk_sources="" -while [ $cont == true ]; do - if [ -z "$vtk_sources" ]; then - read -e -p "Please provide a valid location for VTK: " tmp - eval tmp=$tmp - vtk_sources=`readlink -f $tmp` - fi - read -p "I am going to use \"$vtk_sources\". Is this ok? [y/N] " -n 1 -r - echo - if [[ $REPLY =~ ^[Nn]$ ]]; then - vtk_sources="" - else - cont=false - fi -done -if [ -z $vtk_sources ]; then - echo "FATAL ERROR: VTK is really needed to build cpPlugins." - exit 1 -fi - -echo "Now, I will try to compile VTK..." -vtk_mime=`file -bzk --mime-type $vtk_sources` -if [[ -f $vtk_sources ]]; then - if [ "$vtk_mime" == "application/x-tar" ]; then - sub_mime=`file -b --mime-type $vtk_sources` - if [ $sub_mime == "application/gzip" ]; then - vtk_source_dir=`dirname $vtk_sources`/`basename $vtk_sources .tar.gz` - vtk_binary_dir=`dirname $vtk_sources`/`basename $vtk_sources .tar.gz`-build - echo -n "==> Extracting VTK sources... " - rm -rf $vtk_source_dir $vtk_binary_dir - mkdir -p $vtk_source_dir $vtk_binary_dir - tar xzf $vtk_sources -C $vtk_source_dir --strip-components=1 - echo "done." - fi - fi -elif [[ -d $vtk_sources ]]; then - vtk_source_dir="$vtk_sources" - vtk_binary_dir="$vtk_sources"-build -else - echo "FATAL ERROR: $vtk_sources is not a valid file/directory" - exit 1 -fi - -read -e -p "==> Please provide instalation location for \"VTK\": " tmp -eval tmp=$tmp -vtk_prefix=`readlink -f $tmp` - -vtk_build_type=MinSizeRel - -echo "==> Configuring sources... " -cd $vtk_binary_dir -if [ -x "$qmake_exe" ]; then - $cmake_exe \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DQT_QMAKE_EXECUTABLE:PATH=$qmake_exe \ - -DCMAKE_BUILD_TYPE:STRING=$vtk_build_type \ - -DModule_vtkGUISupportQt:BOOL=ON \ - -DModule_vtkGUISupportQtOpenGL:BOOL=ON \ - -DModule_vtkGUISupportQtSQL:BOOL=OFF \ - -DModule_vtkGUISupportQtWebkit:BOOL=OFF \ - -DCMAKE_INSTALL_PREFIX:PATH=$vtk_prefix \ - $vtk_source_dir -else - $cmake_exe \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DCMAKE_BUILD_TYPE:STRING=$build_type \ - -DCMAKE_INSTALL_PREFIX:PATH=$vtk_prefix \ - $vtk_source_dir -fi -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $vtk_binary_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $vtk_binary_dir -make -j install -echo "==> Installing package... done." - -## =============== -## == Build ITK == -## =============== - -cont=true -itk_sources="" -while [ $cont == true ]; do - if [ -z "$itk_sources" ]; then - read -e -p "Please provide a valid location for ITK: " tmp - eval tmp=$tmp - itk_sources=`readlink -f $tmp` - fi - read -p "I am going to use \"$itk_sources\". Is this ok? [y/N] " -n 1 -r - echo - if [[ $REPLY =~ ^[Nn]$ ]]; then - itk_sources="" - else - cont=false - fi -done -if [ -z $itk_sources ]; then - echo "FATAL ERROR: ITK is really needed to build cpPlugins." - exit 1 -fi - -echo "Now, I will try to compile ITK..." -itk_mime=`file -bzk --mime-type $itk_sources` -if [[ -f $itk_sources ]]; then - if [ "$itk_mime" == "application/x-tar" ]; then - sub_mime=`file -b --mime-type $itk_sources` - if [ $sub_mime == "application/gzip" ]; then - itk_source_dir=`dirname $itk_sources`/`basename $itk_sources .tar.gz` - itk_binary_dir=`dirname $itk_sources`/`basename $itk_sources .tar.gz`-build - echo -n "==> Extracting ITK sources... " - rm -rf $itk_source_dir $itk_binary_dir - mkdir -p $itk_source_dir $itk_binary_dir - tar xzf $itk_sources -C $itk_source_dir --strip-components=1 - echo "done." - fi - fi -elif [[ -d $itk_sources ]]; then - itk_source_dir="$itk_sources" - itk_binary_dir="$itk_sources"-build -else - echo "FATAL ERROR: $itk_sources is not a valid file/directory" - exit 1 -fi - -read -e -p "==> Please provide instalation location for \"ITK\": " tmp -eval tmp=$tmp -itk_prefix=`readlink -f $tmp` - -itk_build_type=MinSizeRel - -echo "==> Configuring sources... " -cd $itk_binary_dir -$cmake_exe \ - -DCMAKE_CXX_FLAGS:STRING=-std=c++11 \ - -DBUILD_DOCUMENTATION:BOOL=OFF \ - -DBUILD_EXAMPLES:BOOL=OFF \ - -DBUILD_SHARED_LIBS:BOOL=ON \ - -DBUILD_TESTING:BOOL=OFF \ - -DCMAKE_BUILD_TYPE:STRING=$itk_build_type \ - -DModule_ITKReview:BOOL=ON \ - -DModule_ITKVtkGlue:BOOL=OFF \ - -DModule_ParabolicMorphology:BOOL=ON \ - -DCMAKE_INSTALL_PREFIX:PATH=$itk_prefix \ - $itk_source_dir -echo "==> Configuring sources... done." - -echo "==> Compiling sources..." -cd $itk_binary_dir -make -j$number_of_threads -echo "==> Compiling sources... done." - -echo "==> Installing package..." -cd $itk_binary_dir -make -j install -echo "==> Installing package... done." - -## eof - $RCSfile$ diff --git a/dependencies/dependencies.py b/dependencies/dependencies.py deleted file mode 100644 index c232380..0000000 --- a/dependencies/dependencies.py +++ /dev/null @@ -1,328 +0,0 @@ -import errno, glob, os, math, mimetypes, multiprocessing -import platform, readline, tarfile -from distutils import spawn - -## ------------------------ -## -- Create directories -- -## ------------------------ - -def create_dir( path ): - try: - os.makedirs(path) - except OSError as exception: - if exception.errno != errno.EEXIST: - raise - # yrt -# fed - -## ------------------------ -## -- Filename completer -- -## ------------------------ - -def filename_completer( text, state ): - return ( glob.glob( text + '*' ) + [ None ] )[ state ] -# fed - -def get_filepath( message ): - readline.set_completer_delims( ' \t\n;' ) - readline.parse_and_bind( "tab: complete" ) - readline.set_completer( filename_completer ) - return os.path.abspath( raw_input( message ) ) -# fed - -## ---------------- -## -- Find paths -- -## ---------------- - -def find_paths( locs, progs ): - paths = [] - for prog in progs: - for loc in locs: - path = spawn.find_executable( loc + "/" + prog ) - if path <> None: - paths.append( path ) - # rof - # rof - return paths -# def - -## ------------------------------ -## -- Extract compressed files -- -## ------------------------------ - -def extract( src ): - tar_gz_type = ( "application/x-tar", "gzip" ) - src_type = mimetypes.guess_type( src ) - print( "Extracting " + src + ": " ) - if src_type == tar_gz_type: - src_dir = os.path.splitext( src )[ 0 ] - src_file = tarfile.open( src, "r|gz" ) - src_file.extractall( src_dir ) - src_file.close( ) - #elif src_type == tar_bz2_type: - #elif src_type == zip_type: - #else: - # fi - print( " done!" ) - return src_dir - -## ------------------- -## -- Choose config -- -## ------------------- - -def choose_config( paths, name ): - print( "Please choose one configuration for " + name + ":" ) - for i in range( len( paths ) ): - print( "\t" + str( i ) + ": " + paths[ i ] ) - # rof - print( "\t" + str( len( paths ) + 0 ) + ": Give another installation." ) - print( "\t" + str( len( paths ) + 1 ) + ": Build from scratch." ) - opt = -1 - while opt == -1: - opt = int( raw_input( "\t---> " ) ) - if opt < 0 or opt > len( paths ) + 1: - qmake_opt = -1 - # fi - # elihw - return opt -# def - -## -------------------- -## -- Some variables -- -## -------------------- - -home_dir = os.environ[ "HOME" ] -process_count = str( multiprocessing.cpu_count( ) / 2 ) - -## ----------------------------------------------- -## -- qmake and cmake locations and executables -- -## ----------------------------------------------- - -locations = [] -qmake_progs = [] -cmake_progs = [] -if platform.system( ) == "Linux": - locations = [ - "/usr/bin", - "/usr/local/bin", - home_dir + "/bin", - home_dir + "/local/bin" - ] - qmake_progs = [ "qmake", "qmake-qt4" ] - cmake_progs = [ "cmake" ] -# fi -qmake_paths = find_paths( locations, qmake_progs ) -cmake_paths = find_paths( locations, cmake_progs ) - -qmake_opt = choose_config( qmake_paths, "Qt4" ) -qmake_src = None -if qmake_opt == len( qmake_paths ): - qmake_exec = get_filepath( "Choose your own Qt4 installation: " ) - while not os.path.isfile( qmake_exec ): - qmake_exec = get_filepath( "Choose your own Qt4 installation: " ) - # elihw -elif qmake_opt == len( qmake_paths ) + 1: - qmake_src = get_filepath( "Choose your own Qt4 source file: " ) - while not os.path.isfile( qmake_src ): - qmake_src = get_filepath( "Choose your own Qt4 source file: " ) - # elihw -else: - qmake_exec = qmake_paths[ qmake_opt ] -# fi - -cmake_opt = choose_config( cmake_paths, "CMake" ) -cmake_src = None -if cmake_opt == len( cmake_paths ): - cmake_exec = get_filepath( "Choose your own CMake installation: " ) - while not os.path.isfile( cmake_exec ): - cmake_exec = get_filepath( "Choose your own CMake installation: " ) - # elihw -elif cmake_opt == len( cmake_paths ) + 1: - cmake_src = get_filepath( "Choose your own CMake source file: " ) - while not os.path.isfile( cmake_src ): - cmake_src = get_filepath( "Choose your own CMake source file: " ) - # elihw -else: - cmake_exec = cmake_paths[ cmake_opt ] -# fi - -## ----------------------- -## -- ITK and VTK files -- -## ----------------------- - -itk_src = get_filepath( "Choose your own ITK source file: " ) -while not os.path.isfile( itk_src ): - itk_src = get_filepath( "Choose your own ITK source file: " ) -# elihw -itk_extra = raw_input( "Type an extra configurations for ITK:" ) - -vtk_src = get_filepath( "Choose your own VTK source file: " ) -while not os.path.isfile( vtk_src ): - vtk_src = get_filepath( "Choose your own VTK source file: " ) -# elihw -vtk_extra = raw_input( "Type an extra configurations for VTK:" ) - -## ------------------------ -## -- More configuration -- -## ------------------------ - -install_prefix = get_filepath( "Choose your installation prefix: " ) -build_type = raw_input( "Type your build type [(r)elease/(d)ebug]: " ) -build_type.lower( ) -qmake_full = "n" -if qmake_src <> None: - qmake_full = raw_input( "Would you like a full Qt4 install [y/n]? " ) - qmake_full.lower( ) -# fi -qmake_build_type = "release" -kitware_build_type = "MinSizeRel" -if build_type[ 0 ] == "d": - qmake_build_type = "debug" - kitware_build_type = "Debug" -# fi - -## ----------------- -## -- Compile Qt4 -- -## ----------------- - -if qmake_src <> None: - qmake_src_dir = extract( qmake_src ) - qmake_bin_dir = qmake_src_dir + "-build" - min_size = 999999 - qmake_configure = "" - for root, dirs, files in os.walk( qmake_src_dir ): - if "configure" in files: - path = os.path.join( root, "configure" ) - if min_size > len( path ): - min_size = len( path ) - qmake_configure = path - # fi - # fi - # rof - create_dir( qmake_bin_dir ) - - # particular_options=-no-framework - particular_options = "" - - command = "cd " + qmake_bin_dir + " && " - command += qmake_configure - command += " -prefix " + install_prefix - command += " -" + qmake_build_type - command += " -opensource -shared -fast -no-webkit -optimized-qmake" - command += " -confirm-license" - if qmake_full == "y": - command += " -no-phonon -no-phonon-backend -no-openvg" - command += " -nomake demos -nomake examples" - # fi - command += particular_options - command += " && make -j" + process_count - command += " && make -j install" - os.system( command ) - qmake_exec = find_paths( [ install_prefix ], [ "qmake" ] )[ 0 ] -# fi - -## ------------------- -## -- Compile CMake -- -## ------------------- - -if cmake_src <> None: - cmake_src_dir = extract( cmake_src ) - cmake_bin_dir = cmake_src_dir + "-build" - min_size = 999999 - cmake_configure = "" - for root, dirs, files in os.walk( cmake_src_dir ): - if "bootstrap" in files: - path = os.path.join( root, "bootstrap" ) - if min_size > len( path ): - min_size = len( path ) - cmake_configure = path - # fi - # fi - # rof - create_dir( cmake_bin_dir ) - - command = "cd " + cmake_bin_dir + " && " - command += cmake_configure - command += " --prefix " + install_prefix - command += " --qt-gui --qt-qmake=" + qmake_exec - command += " && make -j" + process_count - command += " && make -j install" - os.system( command ) - cmake_exec = find_paths( [ install_prefix ], [ "cmake" ] )[ 0 ] -# fi - -## ----------------- -## -- Compile ITK -- -## ----------------- - -itk_src_dir = extract( itk_src ) -itk_bin_dir = itk_src_dir + "-build" -min_size = 999999 -itk_configure = "" -for root, dirs, files in os.walk( itk_src_dir ): - if "CMakeLists.txt" in files: - path = os.path.join( root, "CMakeLists.txt" ) - if min_size > len( path ): - min_size = len( path ) - itk_configure = path - # fi - # fi -# rof -create_dir( itk_bin_dir ) - -command = "cd " + itk_bin_dir + " && " -command += cmake_exec -command += " -DCMAKE_CXX_FLAGS:STRING=-std=c++11" -command += " -DBUILD_DOCUMENTATION:BOOL=OFF" -command += " -DBUILD_EXAMPLES:BOOL=OFF" -command += " -DBUILD_SHARED_LIBS:BOOL=ON" -command += " -DBUILD_TESTING:BOOL=OFF" -command += " -DModule_ITKReview:BOOL=ON" -command += " -DModule_ITKVtkGlue:BOOL=OFF" -command += " -DModule_ParabolicMorphology:BOOL=ON" -command += " -DCMAKE_BUILD_TYPE:STRING=" + kitware_build_type -command += " -DCMAKE_INSTALL_PREFIX:PATH=" + install_prefix -command += " " + itk_src_dir -command += " && make -j" + process_count -command += " && make -j install" -os.system( command ) - -## ----------------- -## -- Compile VTK -- -## ----------------- - -vtk_src_dir = extract( vtk_src ) -vtk_bin_dir = vtk_src_dir + "-build" -min_size = 999999 -vtk_configure = "" -for root, dirs, files in os.walk( vtk_src_dir ): - if "CMakeLists.txt" in files: - path = os.path.join( root, "CMakeLists.txt" ) - if min_size > len( path ): - min_size = len( path ) - vtk_configure = path - # fi - # fi -# rof -create_dir( vtk_bin_dir ) - -command = "cd " + vtk_bin_dir + " && " -command += cmake_exec -command += " -DCMAKE_CXX_FLAGS:STRING=-std=c++11" -command += " -DBUILD_DOCUMENTATION:BOOL=OFF" -command += " -DBUILD_EXAMPLES:BOOL=OFF" -command += " -DBUILD_SHARED_LIBS:BOOL=ON" -command += " -DBUILD_TESTING:BOOL=OFF" -command += " -DModule_vtkGUISupportQt:BOOL=ON" -command += " -DModule_vtkGUISupportQtOpenGL:BOOL=ON" -command += " -DModule_vtkGUISupportQtSQL:BOOL=OFF" -command += " -DModule_vtkGUISupportQtWebkit:BOOL=OFF" -command += " -DQT_QMAKE_EXECUTABLE:PATH=" + qmake_exec -command += " -DCMAKE_BUILD_TYPE:STRING=" + kitware_build_type -command += " -DCMAKE_INSTALL_PREFIX:PATH=" + install_prefix -command += " " + vtk_src_dir -command += " && make -j" + process_count -command += " && make -j install" -os.system( command ) - -## eof - $RCSfile$ diff --git a/dependencies/qt-4.8.6_MAC.patch b/dependencies/qt-4.8.6_MAC.patch deleted file mode 100644 index f0d2122..0000000 --- a/dependencies/qt-4.8.6_MAC.patch +++ /dev/null @@ -1,18 +0,0 @@ ---- src/gui/painting/qpaintengine_mac.cpp.orig 2015-05-07 14:14:43.000000000 +0000 -+++ src/gui/painting/qpaintengine_mac.cpp -@@ -340,13 +340,7 @@ CGColorSpaceRef QCoreGraphicsPaintEngine - } - - // Get the color space from the display profile. -- CGColorSpaceRef colorSpace = 0; -- CMProfileRef displayProfile = 0; -- CMError err = CMGetProfileByAVID((CMDisplayIDType)displayID, &displayProfile); -- if (err == noErr) { -- colorSpace = CGColorSpaceCreateWithPlatformColorSpace(displayProfile); -- CMCloseProfile(displayProfile); -- } -+ CGColorSpaceRef colorSpace = CGDisplayCopyColorSpace(displayID); - - // Fallback: use generic DeviceRGB - if (colorSpace == 0) - diff --git a/install/macos/clean_libs.sh b/install/macos/clean_libs.sh deleted file mode 100755 index 14613ce..0000000 --- a/install/macos/clean_libs.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -lib_dir=$1 - -for i in $lib_dir/* - do - lnk_i=`readlink $i` - if ! [[ $lnk_i = *[!\ ]* ]]; then - echo $lnk_i - fi -done - -## eof diff --git a/install/macos/prepare_libs.sh b/install/macos/prepare_libs.sh deleted file mode 100755 index e8cb78d..0000000 --- a/install/macos/prepare_libs.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/bash - -lib_dir=$1 - -for i in $lib_dir/* - do - lnk_i=`readlink $i` - if ! [[ $lnk_i = *[!\ ]* ]]; then - equal_lib="" - for j in $lib_dir/* - do - lnk_j=`readlink $j` - if ! [[ $lnk_j = *[!\ ]* ]]; then - difference=`diff -q $i $j` - if ! [[ $difference = *[!\ ]* ]]; then - equal_lib+=$j - equal_lib+=" " - fi - fi - done - if [[ $equal_lib = *[!\ ]* ]]; then - max_len=0 - max_str="" - for k in $equal_lib - do - if [ ${#k} -ge $max_len ]; then - max_len=${#k} - max_str=$k - fi - done - echo $max_str - for k in $equal_lib - do - if ! [ $k == $max_str ]; then - rm -rf $k - ln -fs $max_str $k - fi - done - unset max_len - unset max_str - fi - unset equal_lib - fi -done - -## eof diff --git a/install/macos/relink_lib.sh b/install/macos/relink_lib.sh deleted file mode 100755 index f2172c2..0000000 --- a/install/macos/relink_lib.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -file=$1 -lib_dir=$2 -exec_dir=$3 - -strindex( ) -{ - x="${1%%$2*}" - [[ $x = $1 ]] && echo -1 || echo ${#x} - } - -file_link=`readlink $file` -if ! [[ $file_link = *[!\ ]* ]]; then - for lib in $lib_dir/* - do - lib_name=`basename $lib` - linked_lib=`otool -L $file | grep $lib_name | tail -1` - if [[ $linked_lib = *[!\ ]* ]]; then - index=`strindex "$linked_lib" " ("` - real_lib=`echo $linked_lib | cut -c 1-$index` - lib_link=`readlink $lib` - if [[ $lib_link = *[!\ ]* ]]; then - lib_link=`basename $lib_link` - else - lib_link=$lib_name - fi - if [[ $lib_link = *[!\ ]* ]]; then - echo $real_lib $lib_link - install_name_tool -change $real_lib $exec_dir/$lib_link $file - fi - fi - done -fi - -## eof \ No newline at end of file diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt deleted file mode 100644 index 30d104a..0000000 --- a/lib/CMakeLists.txt +++ /dev/null @@ -1,75 +0,0 @@ - -## ====================== -## == Helper libraries == -## ====================== - -SET( - _cpExtensions_components - cpExtensions/Config.h.in - cpExtensions/DataStructures - cpExtensions/Algorithms - cpExtensions/Interaction - cpExtensions/Visualization - ) - -IF(BUILD_QT4_COMPONENTS) - LIST(APPEND _cpExtensions_components "cpExtensions/QT") -ENDIF(BUILD_QT4_COMPONENTS) -cpPlugins_BuildLibrary(cpExtensions SHARED ${_cpExtensions_components}) -TARGET_LINK_LIBRARIES( - cpExtensions - ${QT_LIBRARIES} ${ITK_LIBRARIES} ${VTK_LIBRARIES} - ) - -## ============================================ -## == Explicit instances from templated code == -## ============================================ - -SUBDIRS( - cpInstances - ) - -## ================== -## == Base library == -## ================== - -SET(_real_config ${CMAKE_CURRENT_BINARY_DIR}/cpPlugins/RealConfig.h) -ADD_CUSTOM_COMMAND( - OUTPUT ${_real_config} - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/cpPlugins - COMMAND ${cpPlugins_bash_CreateRealConfig_APP} ${_real_config} - DEPENDS ${cpPlugins_bash_CreateRealConfig_APP} - ) -SET( - _cpPlugins_components - ${_real_config} - cpPlugins/Config.h.in - cpPlugins/tinyxml2 - cpPlugins/OS - cpPlugins/Pipeline - cpPlugins/Interface - ) -IF(BUILD_QT4_COMPONENTS) - LIST(APPEND _cpPlugins_components "cpPlugins/QT") -ENDIF(BUILD_QT4_COMPONENTS) -cpPlugins_BuildLibrary(cpPlugins SHARED ${_cpPlugins_components}) -TARGET_LINK_LIBRARIES(cpPlugins ${ITK_LIBRARIES} ${VTK_LIBRARIES}) -IF(BUILD_QT4_COMPONENTS) - TARGET_LINK_LIBRARIES(cpPlugins ${QT_LIBRARIES}) -ENDIF(BUILD_QT4_COMPONENTS) - -## =================================== -## == Base library for applications == -## =================================== - -IF(BUILD_QT4_COMPONENTS) - cpPlugins_BuildLibrary(cpBaseQtApplication SHARED cpBaseQtApplication) - cpPlugins_BuildLibrary(cp_QCustomPlot SHARED QCustomPlot) - TARGET_LINK_LIBRARIES( - cpBaseQtApplication - cpExtensions cpPlugins - ) - TARGET_LINK_LIBRARIES(cp_QCustomPlot ${QT_LIBRARIES}) -ENDIF(BUILD_QT4_COMPONENTS) - -## eof - $RCSfile$ diff --git a/lib/QCustomPlot/GPL.txt b/lib/QCustomPlot/GPL.txt deleted file mode 100644 index 94a9ed0..0000000 --- a/lib/QCustomPlot/GPL.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/lib/QCustomPlot/QCustomPlot.cxx b/lib/QCustomPlot/QCustomPlot.cxx deleted file mode 100644 index abc692b..0000000 --- a/lib/QCustomPlot/QCustomPlot.cxx +++ /dev/null @@ -1,23553 +0,0 @@ -/*************************************************************************** -** ** -** QCustomPlot, an easy to use, modern plotting widget for Qt ** -** Copyright (C) 2011-2015 Emanuel Eichhammer ** -** ** -** This program is free software: you can redistribute it and/or modify ** -** it under the terms of the GNU General Public License as published by ** -** the Free Software Foundation, either version 3 of the License, or ** -** (at your option) any later version. ** -** ** -** This program is distributed in the hope that it will be useful, ** -** but WITHOUT ANY WARRANTY; without even the implied warranty of ** -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** -** GNU General Public License for more details. ** -** ** -** You should have received a copy of the GNU General Public License ** -** along with this program. If not, see http://www.gnu.org/licenses/. ** -** ** -**************************************************************************** -** Author: Emanuel Eichhammer ** -** Website/Contact: http://www.qcustomplot.com/ ** -** Date: 22.12.15 ** -** Version: 1.3.2 ** -****************************************************************************/ - -#include - - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPPainter -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPPainter - \brief QPainter subclass used internally - - This QPainter subclass is used to provide some extended functionality e.g. for tweaking position - consistency between antialiased and non-antialiased painting. Further it provides workarounds - for QPainter quirks. - - \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and - restore. So while it is possible to pass a QCPPainter instance to a function that expects a - QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because - it will call the base class implementations of the functions actually hidden by QCPPainter). -*/ - -/*! - Creates a new QCPPainter instance and sets default values -*/ -QCPPainter::QCPPainter() : - QPainter(), - mModes(pmDefault), - mIsAntialiasing(false) -{ - // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and - // a call to begin() will follow -} - -/*! - Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just - like the analogous QPainter constructor, begins painting on \a device immediately. - - Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. -*/ -QCPPainter::QCPPainter(QPaintDevice *device) : - QPainter(device), - mModes(pmDefault), - mIsAntialiasing(false) -{ -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (isActive()) - setRenderHint(QPainter::NonCosmeticDefaultPen); -#endif -} - -QCPPainter::~QCPPainter() -{ -} - -/*! - Sets the pen of the painter and applies certain fixes to it, depending on the mode of this - QCPPainter. - - \note this function hides the non-virtual base class implementation. -*/ -void QCPPainter::setPen(const QPen &pen) -{ - QPainter::setPen(pen); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); -} - -/*! \overload - - Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of - this QCPPainter. - - \note this function hides the non-virtual base class implementation. -*/ -void QCPPainter::setPen(const QColor &color) -{ - QPainter::setPen(color); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); -} - -/*! \overload - - Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of - this QCPPainter. - - \note this function hides the non-virtual base class implementation. -*/ -void QCPPainter::setPen(Qt::PenStyle penStyle) -{ - QPainter::setPen(penStyle); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); -} - -/*! \overload - - Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when - antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to - integer coordinates and then passes it to the original drawLine. - - \note this function hides the non-virtual base class implementation. -*/ -void QCPPainter::drawLine(const QLineF &line) -{ - if (mIsAntialiasing || mModes.testFlag(pmVectorized)) - QPainter::drawLine(line); - else - QPainter::drawLine(line.toLine()); -} - -/*! - Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint - with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between - antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for - AA/Non-AA painting). -*/ -void QCPPainter::setAntialiasing(bool enabled) -{ - setRenderHint(QPainter::Antialiasing, enabled); - if (mIsAntialiasing != enabled) - { - mIsAntialiasing = enabled; - if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs - { - if (mIsAntialiasing) - translate(0.5, 0.5); - else - translate(-0.5, -0.5); - } - } -} - -/*! - Sets the mode of the painter. This controls whether the painter shall adjust its - fixes/workarounds optimized for certain output devices. -*/ -void QCPPainter::setModes(QCPPainter::PainterModes modes) -{ - mModes = modes; -} - -/*! - Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a - device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, - all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that - behaviour. - - The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets - the render hint as appropriate. - - \note this function hides the non-virtual base class implementation. -*/ -bool QCPPainter::begin(QPaintDevice *device) -{ - bool result = QPainter::begin(device); -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (result) - setRenderHint(QPainter::NonCosmeticDefaultPen); -#endif - return result; -} - -/*! \overload - - Sets the mode of the painter. This controls whether the painter shall adjust its - fixes/workarounds optimized for certain output devices. -*/ -void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) -{ - if (!enabled && mModes.testFlag(mode)) - mModes &= ~mode; - else if (enabled && !mModes.testFlag(mode)) - mModes |= mode; -} - -/*! - Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to - QPainter, the save/restore functions are reimplemented to also save/restore those members. - - \note this function hides the non-virtual base class implementation. - - \see restore -*/ -void QCPPainter::save() -{ - mAntialiasingStack.push(mIsAntialiasing); - QPainter::save(); -} - -/*! - Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to - QPainter, the save/restore functions are reimplemented to also save/restore those members. - - \note this function hides the non-virtual base class implementation. - - \see save -*/ -void QCPPainter::restore() -{ - if (!mAntialiasingStack.isEmpty()) - mIsAntialiasing = mAntialiasingStack.pop(); - else - qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; - QPainter::restore(); -} - -/*! - Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen - overrides when the \ref pmNonCosmetic mode is set. -*/ -void QCPPainter::makeNonCosmetic() -{ - if (qFuzzyIsNull(pen().widthF())) - { - QPen p = pen(); - p.setWidth(1); - QPainter::setPen(p); - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPScatterStyle -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPScatterStyle - \brief Represents the visual appearance of scatter points - - This class holds information about shape, color and size of scatter points. In plottables like - QCPGraph it is used to store how scatter points shall be drawn. For example, \ref - QCPGraph::setScatterStyle takes a QCPScatterStyle instance. - - A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a - fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can - be controlled with \ref setSize. - - \section QCPScatterStyle-defining Specifying a scatter style - - You can set all these configurations either by calling the respective functions on an instance: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1 - - Or you can use one of the various constructors that take different parameter combinations, making - it easy to specify a scatter style in a single call, like so: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2 - - \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable - - There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref - QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref - isPenDefined will return false. It leads to scatter points that inherit the pen from the - plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line - color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes - it very convenient to set up typical scatter settings: - - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation - - Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works - because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly - into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) - constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref - ScatterShape, where actually a QCPScatterStyle is expected. - - \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps - - QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. - - For custom shapes, you can provide a QPainterPath with the desired shape to the \ref - setCustomPath function or call the constructor that takes a painter path. The scatter shape will - automatically be set to \ref ssCustom. - - For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the - constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. - Note that \ref setSize does not influence the appearance of the pixmap. -*/ - -/* start documentation of inline functions */ - -/*! \fn bool QCPScatterStyle::isNone() const - - Returns whether the scatter shape is \ref ssNone. - - \see setShape -*/ - -/*! \fn bool QCPScatterStyle::isPenDefined() const - - Returns whether a pen has been defined for this scatter style. - - The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are - \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is - left undefined, the scatter color will be inherited from the plottable that uses this scatter - style. - - \see setPen -*/ - -/* end documentation of inline functions */ - -/*! - Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. - - Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited - from the plottable that uses this scatter style. -*/ -QCPScatterStyle::QCPScatterStyle() : - mSize(6), - mShape(ssNone), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPenDefined(false) -{ -} - -/*! - Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or - brush is defined. - - Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited - from the plottable that uses this scatter style. -*/ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : - mSize(size), - mShape(shape), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPenDefined(false) -{ -} - -/*! - Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, - and size to \a size. No brush is defined, i.e. the scatter point will not be filled. -*/ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : - mSize(size), - mShape(shape), - mPen(QPen(color)), - mBrush(Qt::NoBrush), - mPenDefined(true) -{ -} - -/*! - Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, - the brush color to \a fill (with a solid pattern), and size to \a size. -*/ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : - mSize(size), - mShape(shape), - mPen(QPen(color)), - mBrush(QBrush(fill)), - mPenDefined(true) -{ -} - -/*! - Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the - brush to \a brush, and size to \a size. - - \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen - and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n - QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n - doesn't necessarily lead C++ to use this constructor in some cases, but might mistake - Qt::NoPen for a QColor and use the - \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) - constructor instead (which will lead to an unexpected look of the scatter points). To prevent - this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) - instead of just Qt::blue, to clearly point out to the compiler that this constructor is - wanted. -*/ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : - mSize(size), - mShape(shape), - mPen(pen), - mBrush(brush), - mPenDefined(pen.style() != Qt::NoPen) -{ -} - -/*! - Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape - is set to \ref ssPixmap. -*/ -QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : - mSize(5), - mShape(ssPixmap), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPixmap(pixmap), - mPenDefined(false) -{ -} - -/*! - Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The - scatter shape is set to \ref ssCustom. - - The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly - different meaning than for built-in scatter points: The custom path will be drawn scaled by a - factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its - natural size by default. To double the size of the path for example, set \a size to 12. -*/ -QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : - mSize(size), - mShape(ssCustom), - mPen(pen), - mBrush(brush), - mCustomPath(customPath), - mPenDefined(pen.style() != Qt::NoPen) -{ -} - -/*! - Sets the size (pixel diameter) of the drawn scatter points to \a size. - - \see setShape -*/ -void QCPScatterStyle::setSize(double size) -{ - mSize = size; -} - -/*! - Sets the shape to \a shape. - - Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref - ssPixmap and \ref ssCustom, respectively. - - \see setSize -*/ -void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) -{ - mShape = shape; -} - -/*! - Sets the pen that will be used to draw scatter points to \a pen. - - If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after - a call to this function, even if \a pen is Qt::NoPen. - - \see setBrush -*/ -void QCPScatterStyle::setPen(const QPen &pen) -{ - mPenDefined = true; - mPen = pen; -} - -/*! - Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter - shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. - - \see setPen -*/ -void QCPScatterStyle::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the pixmap that will be drawn as scatter point to \a pixmap. - - Note that \ref setSize does not influence the appearance of the pixmap. - - The scatter shape is automatically set to \ref ssPixmap. -*/ -void QCPScatterStyle::setPixmap(const QPixmap &pixmap) -{ - setShape(ssPixmap); - mPixmap = pixmap; -} - -/*! - Sets the custom shape that will be drawn as scatter point to \a customPath. - - The scatter shape is automatically set to \ref ssCustom. -*/ -void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) -{ - setShape(ssCustom); - mCustomPath = customPath; -} - -/*! - Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an - undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. - - This function is used by plottables (or any class that wants to draw scatters) just before a - number of scatters with this style shall be drawn with the \a painter. - - \see drawShape -*/ -void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const -{ - painter->setPen(mPenDefined ? mPen : defaultPen); - painter->setBrush(mBrush); -} - -/*! - Draws the scatter shape with \a painter at position \a pos. - - This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be - called before scatter points are drawn with \ref drawShape. - - \see applyTo -*/ -void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const -{ - drawShape(painter, pos.x(), pos.y()); -} - -/*! \overload - Draws the scatter shape with \a painter at position \a x and \a y. -*/ -void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const -{ - double w = mSize/2.0; - switch (mShape) - { - case ssNone: break; - case ssDot: - { - painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); - break; - } - case ssCross: - { - painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); - painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); - break; - } - case ssPlus: - { - painter->drawLine(QLineF(x-w, y, x+w, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - break; - } - case ssCircle: - { - painter->drawEllipse(QPointF(x , y), w, w); - break; - } - case ssDisc: - { - QBrush b = painter->brush(); - painter->setBrush(painter->pen().color()); - painter->drawEllipse(QPointF(x , y), w, w); - painter->setBrush(b); - break; - } - case ssSquare: - { - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - break; - } - case ssDiamond: - { - painter->drawLine(QLineF(x-w, y, x, y-w)); - painter->drawLine(QLineF( x, y-w, x+w, y)); - painter->drawLine(QLineF(x+w, y, x, y+w)); - painter->drawLine(QLineF( x, y+w, x-w, y)); - break; - } - case ssStar: - { - painter->drawLine(QLineF(x-w, y, x+w, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); - painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); - break; - } - case ssTriangle: - { - painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); - painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); - painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); - break; - } - case ssTriangleInverted: - { - painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); - painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); - painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); - break; - } - case ssCrossSquare: - { - painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); - painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - break; - } - case ssPlusSquare: - { - painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - break; - } - case ssCrossCircle: - { - painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); - painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); - painter->drawEllipse(QPointF(x, y), w, w); - break; - } - case ssPlusCircle: - { - painter->drawLine(QLineF(x-w, y, x+w, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - painter->drawEllipse(QPointF(x, y), w, w); - break; - } - case ssPeace: - { - painter->drawLine(QLineF(x, y-w, x, y+w)); - painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); - painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); - painter->drawEllipse(QPointF(x, y), w, w); - break; - } - case ssPixmap: - { - painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); - break; - } - case ssCustom: - { - QTransform oldTransform = painter->transform(); - painter->translate(x, y); - painter->scale(mSize/6.0, mSize/6.0); - painter->drawPath(mCustomPath); - painter->setTransform(oldTransform); - break; - } - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLayer -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLayer - \brief A layer that may contain objects, to control the rendering order - - The Layering system of QCustomPlot is the mechanism to control the rendering order of the - elements inside the plot. - - It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of - one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, - QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers - bottom to top and successively draws the layerables of the layers. - - A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base - class from which almost all visible objects derive, like axes, grids, graphs, items, etc. - - Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in - that order). The top two layers "axes" and "legend" contain the default axes and legend, so they - will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as - the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. - are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid - instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background - shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the - "background" layer. Of course, the layer affiliation of the individual objects can be changed as - required (\ref QCPLayerable::setLayer). - - Controlling the ordering of objects is easy: Create a new layer in the position you want it to - be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with - QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will - be placed on the new layer automatically, due to the current layer setting. Alternatively you - could have also ignored the current layer setting and just moved the objects with - QCPLayerable::setLayer to the desired layer after creating them. - - It is also possible to move whole layers. For example, If you want the grid to be shown in front - of all plottables/items on the "main" layer, just move it above "main" with - QCustomPlot::moveLayer. - - The rendering order within one layer is simply by order of creation or insertion. The item - created last (or added last to the layer), is drawn on top of all other objects on that layer. - - When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below - the deleted layer, see QCustomPlot::removeLayer. -*/ - -/* start documentation of inline functions */ - -/*! \fn QList QCPLayer::children() const - - Returns a list of all layerables on this layer. The order corresponds to the rendering order: - layerables with higher indices are drawn above layerables with lower indices. -*/ - -/*! \fn int QCPLayer::index() const - - Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be - accessed via \ref QCustomPlot::layer. - - Layers with higher indices will be drawn above layers with lower indices. -*/ - -/* end documentation of inline functions */ - -/*! - Creates a new QCPLayer instance. - - Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. - - \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. - This check is only performed by \ref QCustomPlot::addLayer. -*/ -QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : - QObject(parentPlot), - mParentPlot(parentPlot), - mName(layerName), - mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function - mVisible(true) -{ - // Note: no need to make sure layerName is unique, because layer - // management is done with QCustomPlot functions. -} - -QCPLayer::~QCPLayer() -{ - // If child layerables are still on this layer, detach them, so they don't try to reach back to this - // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted - // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to - // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) - - while (!mChildren.isEmpty()) - mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() - - if (mParentPlot->currentLayer() == this) - qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; -} - -/*! - Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this - layer will be invisible. - - This function doesn't change the visibility property of the layerables (\ref - QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the - visibility of the parent layer into account. -*/ -void QCPLayer::setVisible(bool visible) -{ - mVisible = visible; -} - -/*! \internal - - Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will - be prepended to the list, i.e. be drawn beneath the other layerables already in the list. - - This function does not change the \a mLayer member of \a layerable to this layer. (Use - QCPLayerable::setLayer to change the layer of an object, not this function.) - - \see removeChild -*/ -void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) -{ - if (!mChildren.contains(layerable)) - { - if (prepend) - mChildren.prepend(layerable); - else - mChildren.append(layerable); - } else - qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); -} - -/*! \internal - - Removes the \a layerable from the list of this layer. - - This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer - to change the layer of an object, not this function.) - - \see addChild -*/ -void QCPLayer::removeChild(QCPLayerable *layerable) -{ - if (!mChildren.removeOne(layerable)) - qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLayerable -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLayerable - \brief Base class for all drawable objects - - This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid - etc. - - Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking - the layers accordingly. - - For details about the layering mechanism, see the QCPLayer documentation. -*/ - -/* start documentation of inline functions */ - -/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const - - Returns the parent layerable of this layerable. The parent layerable is used to provide - visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables - only get drawn if their parent layerables are visible, too. - - Note that a parent layerable is not necessarily also the QObject parent for memory management. - Further, a layerable doesn't always have a parent layerable, so this function may return 0. - - A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be - set manually by the user. -*/ - -/* end documentation of inline functions */ -/* start documentation of pure virtual functions */ - -/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 - \internal - - This function applies the default antialiasing setting to the specified \a painter, using the - function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when - \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing - setting may be specified individually, this function should set the antialiasing state of the - most prominent entity. In this case however, the \ref draw function usually calls the specialized - versions of this function before drawing each entity, effectively overriding the setting of the - default antialiasing hint. - - First example: QCPGraph has multiple entities that have an antialiasing setting: The graph - line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, - QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't - only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's - antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and - QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw - calls the respective specialized applyAntialiasingHint function. - - Second example: QCPItemLine consists only of a line so there is only one antialiasing - setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by - all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the - respective layerable subclass.) Consequently it only has the normal - QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to - care about setting any antialiasing states, because the default antialiasing hint is already set - on the painter when the \ref draw function is called, and that's the state it wants to draw the - line with. -*/ - -/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 - \internal - - This function draws the layerable with the specified \a painter. It is only called by - QCustomPlot, if the layerable is visible (\ref setVisible). - - Before this function is called, the painter's antialiasing state is set via \ref - applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was - set to \ref clipRect. -*/ - -/* end documentation of pure virtual functions */ -/* start documentation of signals */ - -/*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); - - This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to - a different layer. - - \see setLayer -*/ - -/* end documentation of signals */ - -/*! - Creates a new QCPLayerable instance. - - Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the - derived classes. - - If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a - targetLayer is an empty string, it places itself on the current layer of the plot (see \ref - QCustomPlot::setCurrentLayer). - - It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later - time with \ref initializeParentPlot. - - The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable - parents are mainly used to control visibility in a hierarchy of layerables. This means a - layerable is only drawn, if all its ancestor layerables are also visible. Note that \a - parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a - plot does. It is not uncommon to set the QObject-parent to something else in the constructors of - QCPLayerable subclasses, to guarantee a working destruction hierarchy. -*/ -QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : - QObject(plot), - mVisible(true), - mParentPlot(plot), - mParentLayerable(parentLayerable), - mLayer(0), - mAntialiased(true) -{ - if (mParentPlot) - { - if (targetLayer.isEmpty()) - setLayer(mParentPlot->currentLayer()); - else if (!setLayer(targetLayer)) - qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; - } -} - -QCPLayerable::~QCPLayerable() -{ - if (mLayer) - { - mLayer->removeChild(this); - mLayer = 0; - } -} - -/*! - Sets the visibility of this layerable object. If an object is not visible, it will not be drawn - on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not - possible. -*/ -void QCPLayerable::setVisible(bool on) -{ - mVisible = on; -} - -/*! - Sets the \a layer of this layerable object. The object will be placed on top of the other objects - already on \a layer. - - If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or - interact/receive events). - - Returns true if the layer of this layerable was successfully changed to \a layer. -*/ -bool QCPLayerable::setLayer(QCPLayer *layer) -{ - return moveToLayer(layer, false); -} - -/*! \overload - Sets the layer of this layerable object by name - - Returns true on success, i.e. if \a layerName is a valid layer name. -*/ -bool QCPLayerable::setLayer(const QString &layerName) -{ - if (!mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (QCPLayer *layer = mParentPlot->layer(layerName)) - { - return setLayer(layer); - } else - { - qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; - return false; - } -} - -/*! - Sets whether this object will be drawn antialiased or not. - - Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and - QCustomPlot::setNotAntialiasedElements. -*/ -void QCPLayerable::setAntialiased(bool enabled) -{ - mAntialiased = enabled; -} - -/*! - Returns whether this layerable is visible, taking the visibility of the layerable parent and the - visibility of the layer this layerable is on into account. This is the method that is consulted - to decide whether a layerable shall be drawn or not. - - If this layerable has a direct layerable parent (usually set via hierarchies implemented in - subclasses, like in the case of QCPLayoutElement), this function returns true only if this - layerable has its visibility set to true and the parent layerable's \ref realVisibility returns - true. - - If this layerable doesn't have a direct layerable parent, returns the state of this layerable's - visibility. -*/ -bool QCPLayerable::realVisibility() const -{ - return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); -} - -/*! - This function is used to decide whether a click hits a layerable object or not. - - \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the - shortest pixel distance of this point to the object. If the object is either invisible or the - distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the - object is not selectable, -1.0 is returned, too. - - If the object is represented not by single lines but by an area like a \ref QCPItemText or the - bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In - these cases this function thus returns a constant value greater zero but still below the parent - plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). - - Providing a constant value for area objects allows selecting line objects even when they are - obscured by such area objects, by clicking close to the lines (i.e. closer than - 0.99*selectionTolerance). - - The actual setting of the selection state is not done by this function. This is handled by the - parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified - via the selectEvent/deselectEvent methods. - - \a details is an optional output parameter. Every layerable subclass may place any information - in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot - decides on the basis of this selectTest call, that the object was successfully selected. The - subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part - objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked - is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be - placed in \a details. So in the subsequent \ref selectEvent, the decision which part was - selected doesn't have to be done a second time for a single selection operation. - - You may pass 0 as \a details to indicate that you are not interested in those selection details. - - \see selectEvent, deselectEvent, QCustomPlot::setInteractions -*/ -double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(pos) - Q_UNUSED(onlySelectable) - Q_UNUSED(details) - return -1.0; -} - -/*! \internal - - Sets the parent plot of this layerable. Use this function once to set the parent plot if you have - passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to - another one. - - Note that, unlike when passing a non-null parent plot in the constructor, this function does not - make \a parentPlot the QObject-parent of this layerable. If you want this, call - QObject::setParent(\a parentPlot) in addition to this function. - - Further, you will probably want to set a layer (\ref setLayer) after calling this function, to - make the layerable appear on the QCustomPlot. - - The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized - so they can react accordingly (e.g. also initialize the parent plot of child layerables, like - QCPLayout does). -*/ -void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) -{ - if (mParentPlot) - { - qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; - return; - } - - if (!parentPlot) - qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; - - mParentPlot = parentPlot; - parentPlotInitialized(mParentPlot); -} - -/*! \internal - - Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not - become the QObject-parent (for memory management) of this layerable. - - The parent layerable has influence on the return value of the \ref realVisibility method. Only - layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be - drawn. - - \see realVisibility -*/ -void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) -{ - mParentLayerable = parentLayerable; -} - -/*! \internal - - Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to - the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is - false, the object will be appended. - - Returns true on success, i.e. if \a layer is a valid layer. -*/ -bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) -{ - if (layer && !mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (layer && layer->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; - return false; - } - - QCPLayer *oldLayer = mLayer; - if (mLayer) - mLayer->removeChild(this); - mLayer = layer; - if (mLayer) - mLayer->addChild(this, prepend); - if (mLayer != oldLayer) - emit layerChanged(mLayer); - return true; -} - -/*! \internal - - Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a - localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is - controlled via \a overrideElement. -*/ -void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const -{ - if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(false); - else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(true); - else - painter->setAntialiasing(localAntialiased); -} - -/*! \internal - - This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting - of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the - parent plot is set at a later time. - - For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any - QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level - element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To - propagate the parent plot to all the children of the hierarchy, the top level element then uses - this function to pass the parent plot on to its child elements. - - The default implementation does nothing. - - \see initializeParentPlot -*/ -void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) -{ - Q_UNUSED(parentPlot) -} - -/*! \internal - - Returns the selection category this layerable shall belong to. The selection category is used in - conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and - which aren't. - - Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref - QCP::iSelectOther. This is what the default implementation returns. - - \see QCustomPlot::setInteractions -*/ -QCP::Interaction QCPLayerable::selectionCategory() const -{ - return QCP::iSelectOther; -} - -/*! \internal - - Returns the clipping rectangle of this layerable object. By default, this is the viewport of the - parent QCustomPlot. Specific subclasses may reimplement this function to provide different - clipping rects. - - The returned clipping rect is set on the painter before the draw function of the respective - object is called. -*/ -QRect QCPLayerable::clipRect() const -{ - if (mParentPlot) - return mParentPlot->viewport(); - else - return QRect(); -} - -/*! \internal - - This event is called when the layerable shall be selected, as a consequence of a click by the - user. Subclasses should react to it by setting their selection state appropriately. The default - implementation does nothing. - - \a event is the mouse event that caused the selection. \a additive indicates, whether the user - was holding the multi-select-modifier while performing the selection (see \ref - QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled - (i.e. become selected when unselected and unselected when selected). - - Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. - returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). - The \a details data you output from \ref selectTest is fed back via \a details here. You may - use it to transport any kind of information from the selectTest to the possibly subsequent - selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable - that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need - to do the calculation again to find out which part was actually clicked. - - \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must - set the value either to true or false, depending on whether the selection state of this layerable - was actually changed. For layerables that only are selectable as a whole and not in parts, this - is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the - selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the - layerable was previously unselected and now is switched to the selected state. - - \see selectTest, deselectEvent -*/ -void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - Q_UNUSED(additive) - Q_UNUSED(details) - Q_UNUSED(selectionStateChanged) -} - -/*! \internal - - This event is called when the layerable shall be deselected, either as consequence of a user - interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by - unsetting their selection appropriately. - - just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must - return true or false when the selection state of this layerable has changed or not changed, - respectively. - - \see selectTest, selectEvent -*/ -void QCPLayerable::deselectEvent(bool *selectionStateChanged) -{ - Q_UNUSED(selectionStateChanged) -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPRange -//////////////////////////////////////////////////////////////////////////////////////////////////// -/*! \class QCPRange - \brief Represents the range an axis is encompassing. - - contains a \a lower and \a upper double value and provides convenience input, output and - modification functions. - - \see QCPAxis::setRange -*/ - -/*! - Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller - intervals would cause errors due to the 11-bit exponent of double precision numbers, - corresponding to a minimum magnitude of roughly 1e-308. - \see validRange, maxRange -*/ -const double QCPRange::minRange = 1e-280; - -/*! - Maximum values (negative and positive) the range will accept in range-changing functions. - Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, - corresponding to a maximum magnitude of roughly 1e308. - Since the number of planck-volumes in the entire visible universe is only ~1e183, this should - be enough. - \see validRange, minRange -*/ -const double QCPRange::maxRange = 1e250; - -/*! - Constructs a range with \a lower and \a upper set to zero. -*/ -QCPRange::QCPRange() : - lower(0), - upper(0) -{ -} - -/*! \overload - Constructs a range with the specified \a lower and \a upper values. -*/ -QCPRange::QCPRange(double lower, double upper) : - lower(lower), - upper(upper) -{ - normalize(); -} - -/*! - Returns the size of the range, i.e. \a upper-\a lower -*/ -double QCPRange::size() const -{ - return upper-lower; -} - -/*! - Returns the center of the range, i.e. (\a upper+\a lower)*0.5 -*/ -double QCPRange::center() const -{ - return (upper+lower)*0.5; -} - -/*! - Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values - are swapped. -*/ -void QCPRange::normalize() -{ - if (lower > upper) - qSwap(lower, upper); -} - -/*! - Expands this range such that \a otherRange is contained in the new range. It is assumed that both - this range and \a otherRange are normalized (see \ref normalize). - - If \a otherRange is already inside the current range, this function does nothing. - - \see expanded -*/ -void QCPRange::expand(const QCPRange &otherRange) -{ - if (lower > otherRange.lower) - lower = otherRange.lower; - if (upper < otherRange.upper) - upper = otherRange.upper; -} - - -/*! - Returns an expanded range that contains this and \a otherRange. It is assumed that both this - range and \a otherRange are normalized (see \ref normalize). - - \see expand -*/ -QCPRange QCPRange::expanded(const QCPRange &otherRange) const -{ - QCPRange result = *this; - result.expand(otherRange); - return result; -} - -/*! - Returns a sanitized version of the range. Sanitized means for logarithmic scales, that - the range won't span the positive and negative sign domain, i.e. contain zero. Further - \a lower will always be numerically smaller (or equal) to \a upper. - - If the original range does span positive and negative sign domains or contains zero, - the returned range will try to approximate the original range as good as possible. - If the positive interval of the original range is wider than the negative interval, the - returned range will only contain the positive interval, with lower bound set to \a rangeFac or - \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval - is wider than the positive interval, this time by changing the \a upper bound. -*/ -QCPRange QCPRange::sanitizedForLogScale() const -{ - double rangeFac = 1e-3; - QCPRange sanitizedRange(lower, upper); - sanitizedRange.normalize(); - // can't have range spanning negative and positive values in log plot, so change range to fix it - //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) - if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) - { - // case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; - } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) - else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) - { - // case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) - { - // find out whether negative or positive interval is wider to decide which sign domain will be chosen - if (-sanitizedRange.lower > sanitizedRange.upper) - { - // negative is wider, do same as in case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else - { - // positive is wider, do same as in case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; - } - } - // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; -} - -/*! - Checks, whether the specified range is within valid bounds, which are defined - as QCPRange::maxRange and QCPRange::minRange. - A valid range means: - \li range bounds within -maxRange and maxRange - \li range size above minRange - \li range size below maxRange -*/ -bool QCPRange::validRange(double lower, double upper) -{ - return (lower > -maxRange && - upper < maxRange && - qAbs(lower-upper) > minRange && - qAbs(lower-upper) < maxRange && - !(lower > 0 && qIsInf(upper/lower)) && - !(upper < 0 && qIsInf(lower/upper))); -} - -/*! - \overload - Checks, whether the specified range is within valid bounds, which are defined - as QCPRange::maxRange and QCPRange::minRange. - A valid range means: - \li range bounds within -maxRange and maxRange - \li range size above minRange - \li range size below maxRange -*/ -bool QCPRange::validRange(const QCPRange &range) -{ - return (range.lower > -maxRange && - range.upper < maxRange && - qAbs(range.lower-range.upper) > minRange && - qAbs(range.lower-range.upper) < maxRange && - !(range.lower > 0 && qIsInf(range.upper/range.lower)) && - !(range.upper < 0 && qIsInf(range.lower/range.upper))); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPMarginGroup -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPMarginGroup - \brief A margin group allows synchronization of margin sides if working with multiple layout elements. - - QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that - they will all have the same size, based on the largest required margin in the group. - - \n - \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" - \n - - In certain situations it is desirable that margins at specific sides are synchronized across - layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will - provide a cleaner look to the user if the left and right margins of the two axis rects are of the - same size. The left axis of the top axis rect will then be at the same horizontal position as the - left axis of the lower axis rect, making them appear aligned. The same applies for the right - axes. This is what QCPMarginGroup makes possible. - - To add/remove a specific side of a layout element to/from a margin group, use the \ref - QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call - \ref clear, or just delete the margin group. - - \section QCPMarginGroup-example Example - - First create a margin group: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 - Then set this group on the layout element sides: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2 - Here, we've used the first two axis rects of the plot and synchronized their left margins with - each other and their right margins with each other. -*/ - -/* start documentation of inline functions */ - -/*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const - - Returns a list of all layout elements that have their margin \a side associated with this margin - group. -*/ - -/* end documentation of inline functions */ - -/*! - Creates a new QCPMarginGroup instance in \a parentPlot. -*/ -QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot) -{ - mChildren.insert(QCP::msLeft, QList()); - mChildren.insert(QCP::msRight, QList()); - mChildren.insert(QCP::msTop, QList()); - mChildren.insert(QCP::msBottom, QList()); -} - -QCPMarginGroup::~QCPMarginGroup() -{ - clear(); -} - -/*! - Returns whether this margin group is empty. If this function returns true, no layout elements use - this margin group to synchronize margin sides. -*/ -bool QCPMarginGroup::isEmpty() const -{ - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - if (!it.value().isEmpty()) - return false; - } - return true; -} - -/*! - Clears this margin group. The synchronization of the margin sides that use this margin group is - lifted and they will use their individual margin sizes again. -*/ -void QCPMarginGroup::clear() -{ - // make all children remove themselves from this margin group: - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - const QList elements = it.value(); - for (int i=elements.size()-1; i>=0; --i) - elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild - } -} - -/*! \internal - - Returns the synchronized common margin for \a side. This is the margin value that will be used by - the layout element on the respective side, if it is part of this margin group. - - The common margin is calculated by requesting the automatic margin (\ref - QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin - group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into - account, too.) -*/ -int QCPMarginGroup::commonMargin(QCP::MarginSide side) const -{ - // query all automatic margins of the layout elements in this margin group side and find maximum: - int result = 0; - const QList elements = mChildren.value(side); - for (int i=0; iautoMargins().testFlag(side)) - continue; - int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); - if (m > result) - result = m; - } - return result; -} - -/*! \internal - - Adds \a element to the internal list of child elements, for the margin \a side. - - This function does not modify the margin group property of \a element. -*/ -void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) -{ - if (!mChildren[side].contains(element)) - mChildren[side].append(element); - else - qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); -} - -/*! \internal - - Removes \a element from the internal list of child elements, for the margin \a side. - - This function does not modify the margin group property of \a element. -*/ -void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) -{ - if (!mChildren[side].removeOne(element)) - qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLayoutElement -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLayoutElement - \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". - - This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. - - A Layout element is a rectangular object which can be placed in layouts. It has an outer rect - (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference - between outer and inner rect is called its margin. The margin can either be set to automatic or - manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be - set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, - the layout element subclass will control the value itself (via \ref calculateAutoMargin). - - Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level - layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref - QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. - - Thus in QCustomPlot one can divide layout elements into two categories: The ones that are - invisible by themselves, because they don't draw anything. Their only purpose is to manage the - position and size of other layout elements. This category of layout elements usually use - QCPLayout as base class. Then there is the category of layout elements which actually draw - something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does - not necessarily mean that the latter category can't have child layout elements. QCPLegend for - instance, actually derives from QCPLayoutGrid and the individual legend items are child layout - elements in the grid layout. -*/ - -/* start documentation of inline functions */ - -/*! \fn QCPLayout *QCPLayoutElement::layout() const - - Returns the parent layout of this layout element. -*/ - -/*! \fn QRect QCPLayoutElement::rect() const - - Returns the inner rect of this layout element. The inner rect is the outer rect (\ref - setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). - - In some cases, the area between outer and inner rect is left blank. In other cases the margin - area is used to display peripheral graphics while the main content is in the inner rect. This is - where automatic margin calculation becomes interesting because it allows the layout element to - adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect - draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if - \ref setAutoMargins is enabled) according to the space required by the labels of the axes. -*/ - -/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) - - This event is called, if the mouse was pressed while being inside the outer rect of this layout - element. -*/ - -/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) - - This event is called, if the mouse is moved inside the outer rect of this layout element. -*/ - -/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) - - This event is called, if the mouse was previously pressed inside the outer rect of this layout - element and is now released. -*/ - -/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) - - This event is called, if the mouse is double-clicked inside the outer rect of this layout - element. -*/ - -/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) - - This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this - layout element. -*/ - -/* end documentation of inline functions */ - -/*! - Creates an instance of QCPLayoutElement and sets default values. -*/ -QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) - mParentLayout(0), - mMinimumSize(), - mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), - mRect(0, 0, 0, 0), - mOuterRect(0, 0, 0, 0), - mMargins(0, 0, 0, 0), - mMinimumMargins(0, 0, 0, 0), - mAutoMargins(QCP::msAll) -{ -} - -QCPLayoutElement::~QCPLayoutElement() -{ - setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any - // unregister at layout: - if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor - mParentLayout->take(this); -} - -/*! - Sets the outer rect of this layout element. If the layout element is inside a layout, the layout - sets the position and size of this layout element using this function. - - Calling this function externally has no effect, since the layout will overwrite any changes to - the outer rect upon the next replot. - - The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. - - \see rect -*/ -void QCPLayoutElement::setOuterRect(const QRect &rect) -{ - if (mOuterRect != rect) - { - mOuterRect = rect; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } -} - -/*! - Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all - sides, this function is used to manually set the margin on those sides. Sides that are still set - to be handled automatically are ignored and may have any value in \a margins. - - The margin is the distance between the outer rect (controlled by the parent layout via \ref - setOuterRect) and the inner \ref rect (which usually contains the main content of this layout - element). - - \see setAutoMargins -*/ -void QCPLayoutElement::setMargins(const QMargins &margins) -{ - if (mMargins != margins) - { - mMargins = margins; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } -} - -/*! - If \ref setAutoMargins is enabled on some or all margins, this function is used to provide - minimum values for those margins. - - The minimum values are not enforced on margin sides that were set to be under manual control via - \ref setAutoMargins. - - \see setAutoMargins -*/ -void QCPLayoutElement::setMinimumMargins(const QMargins &margins) -{ - if (mMinimumMargins != margins) - { - mMinimumMargins = margins; - } -} - -/*! - Sets on which sides the margin shall be calculated automatically. If a side is calculated - automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is - set to be controlled manually, the value may be specified with \ref setMargins. - - Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref - setMarginGroup), to synchronize (align) it with other layout elements in the plot. - - \see setMinimumMargins, setMargins -*/ -void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) -{ - mAutoMargins = sides; -} - -/*! - Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to - respect the \a size here by changing row/column sizes in the layout accordingly. - - If the parent layout size is not sufficient to satisfy all minimum size constraints of its child - layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot - propagates the layout's size constraints to the outside by setting its own minimum QWidget size - accordingly, so violations of \a size should be exceptions. -*/ -void QCPLayoutElement::setMinimumSize(const QSize &size) -{ - if (mMinimumSize != size) - { - mMinimumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } -} - -/*! \overload - - Sets the minimum size for the inner \ref rect of this layout element. -*/ -void QCPLayoutElement::setMinimumSize(int width, int height) -{ - setMinimumSize(QSize(width, height)); -} - -/*! - Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to - respect the \a size here by changing row/column sizes in the layout accordingly. -*/ -void QCPLayoutElement::setMaximumSize(const QSize &size) -{ - if (mMaximumSize != size) - { - mMaximumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } -} - -/*! \overload - - Sets the maximum size for the inner \ref rect of this layout element. -*/ -void QCPLayoutElement::setMaximumSize(int width, int height) -{ - setMaximumSize(QSize(width, height)); -} - -/*! - Sets the margin \a group of the specified margin \a sides. - - Margin groups allow synchronizing specified margins across layout elements, see the documentation - of \ref QCPMarginGroup. - - To unset the margin group of \a sides, set \a group to 0. - - Note that margin groups only work for margin sides that are set to automatic (\ref - setAutoMargins). -*/ -void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) -{ - QVector sideVector; - if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); - if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); - if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); - if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); - - for (int i=0; iremoveChild(side, this); - - if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there - { - mMarginGroups.remove(side); - } else // setting to a new group - { - mMarginGroups[side] = group; - group->addChild(side, this); - } - } - } -} - -/*! - Updates the layout element and sub-elements. This function is automatically called before every - replot by the parent layout element. It is called multiple times, once for every \ref - UpdatePhase. The phases are run through in the order of the enum values. For details about what - happens at the different phases, see the documentation of \ref UpdatePhase. - - Layout elements that have child elements should call the \ref update method of their child - elements, and pass the current \a phase unchanged. - - The default implementation executes the automatic margin mechanism in the \ref upMargins phase. - Subclasses should make sure to call the base class implementation. -*/ -void QCPLayoutElement::update(UpdatePhase phase) -{ - if (phase == upMargins) - { - if (mAutoMargins != QCP::msNone) - { - // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: - QMargins newMargins = mMargins; - QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; - foreach (QCP::MarginSide side, allMarginSides) - { - if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically - { - if (mMarginGroups.contains(side)) - QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group - else - QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly - // apply minimum margin restrictions: - if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) - QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); - } - } - setMargins(newMargins); - } - } -} - -/*! - Returns the minimum size this layout element (the inner \ref rect) may be compressed to. - - if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this - function to determine the minimum allowed size of this layout element. (A manual minimum size is - considered set if it is non-zero.) -*/ -QSize QCPLayoutElement::minimumSizeHint() const -{ - return mMinimumSize; -} - -/*! - Returns the maximum size this layout element (the inner \ref rect) may be expanded to. - - if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this - function to determine the maximum allowed size of this layout element. (A manual maximum size is - considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) -*/ -QSize QCPLayoutElement::maximumSizeHint() const -{ - return mMaximumSize; -} - -/*! - Returns a list of all child elements in this layout element. If \a recursive is true, all - sub-child elements are included in the list, too. - - \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have - empty cells which yield 0 at the respective index.) -*/ -QList QCPLayoutElement::elements(bool recursive) const -{ - Q_UNUSED(recursive) - return QList(); -} - -/*! - Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer - rect, this method returns a value corresponding to 0.99 times the parent plot's selection - tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is - true, -1.0 is returned. - - See \ref QCPLayerable::selectTest for a general explanation of this virtual method. - - QCPLayoutElement subclasses may reimplement this method to provide more specific selection test - behaviour. -*/ -double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - - if (onlySelectable) - return -1; - - if (QRectF(mOuterRect).contains(pos)) - { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; - else - { - qDebug() << Q_FUNC_INFO << "parent plot not defined"; - return -1; - } - } else - return -1; -} - -/*! \internal - - propagates the parent plot initialization to all child elements, by calling \ref - QCPLayerable::initializeParentPlot on them. -*/ -void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) -{ - foreach (QCPLayoutElement* el, elements(false)) - { - if (!el->parentPlot()) - el->initializeParentPlot(parentPlot); - } -} - -/*! \internal - - Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a - side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the - returned value will not be smaller than the specified minimum margin. - - The default implementation just returns the respective manual margin (\ref setMargins) or the - minimum margin, whichever is larger. -*/ -int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) -{ - return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLayout -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLayout - \brief The abstract base class for layouts - - This is an abstract base class for layout elements whose main purpose is to define the position - and size of other child layout elements. In most cases, layouts don't draw anything themselves - (but there are exceptions to this, e.g. QCPLegend). - - QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. - - QCPLayout introduces a common interface for accessing and manipulating the child elements. Those - functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref - simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions - to this interface which are more specialized to the form of the layout. For example, \ref - QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid - more conveniently. - - Since this is an abstract base class, you can't instantiate it directly. Rather use one of its - subclasses like QCPLayoutGrid or QCPLayoutInset. - - For a general introduction to the layout system, see the dedicated documentation page \ref - thelayoutsystem "The Layout System". -*/ - -/* start documentation of pure virtual functions */ - -/*! \fn virtual int QCPLayout::elementCount() const = 0 - - Returns the number of elements/cells in the layout. - - \see elements, elementAt -*/ - -/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 - - Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. - - Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. - QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check - whether a cell is empty or not. - - \see elements, elementCount, takeAt -*/ - -/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 - - Removes the element with the given \a index from the layout and returns it. - - If the \a index is invalid or the cell with that index is empty, returns 0. - - Note that some layouts don't remove the respective cell right away but leave an empty cell after - successful removal of the layout element. To collapse empty cells, use \ref simplify. - - \see elementAt, take -*/ - -/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 - - Removes the specified \a element from the layout and returns true on success. - - If the \a element isn't in this layout, returns false. - - Note that some layouts don't remove the respective cell right away but leave an empty cell after - successful removal of the layout element. To collapse empty cells, use \ref simplify. - - \see takeAt -*/ - -/* end documentation of pure virtual functions */ - -/*! - Creates an instance of QCPLayout and sets default values. Note that since QCPLayout - is an abstract base class, it can't be instantiated directly. -*/ -QCPLayout::QCPLayout() -{ -} - -/*! - First calls the QCPLayoutElement::update base class implementation to update the margins on this - layout. - - Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. - - Finally, \ref update is called on all child elements. -*/ -void QCPLayout::update(UpdatePhase phase) -{ - QCPLayoutElement::update(phase); - - // set child element rects according to layout: - if (phase == upLayout) - updateLayout(); - - // propagate update call to child elements: - const int elCount = elementCount(); - for (int i=0; iupdate(phase); - } -} - -/* inherits documentation from base class */ -QList QCPLayout::elements(bool recursive) const -{ - const int c = elementCount(); - QList result; -#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(c); -#endif - for (int i=0; ielements(recursive); - } - } - return result; -} - -/*! - Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the - default implementation does nothing. - - Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit - simplification while QCPLayoutGrid does. -*/ -void QCPLayout::simplify() -{ -} - -/*! - Removes and deletes the element at the provided \a index. Returns true on success. If \a index is - invalid or points to an empty cell, returns false. - - This function internally uses \ref takeAt to remove the element from the layout and then deletes - the returned element. Note that some layouts don't remove the respective cell right away but leave an - empty cell after successful removal of the layout element. To collapse empty cells, use \ref - simplify. - - \see remove, takeAt -*/ -bool QCPLayout::removeAt(int index) -{ - if (QCPLayoutElement *el = takeAt(index)) - { - delete el; - return true; - } else - return false; -} - -/*! - Removes and deletes the provided \a element. Returns true on success. If \a element is not in the - layout, returns false. - - This function internally uses \ref takeAt to remove the element from the layout and then deletes - the element. Note that some layouts don't remove the respective cell right away but leave an - empty cell after successful removal of the layout element. To collapse empty cells, use \ref - simplify. - - \see removeAt, take -*/ -bool QCPLayout::remove(QCPLayoutElement *element) -{ - if (take(element)) - { - delete element; - return true; - } else - return false; -} - -/*! - Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure - all empty cells are collapsed. - - \see remove, removeAt -*/ -void QCPLayout::clear() -{ - for (int i=elementCount()-1; i>=0; --i) - { - if (elementAt(i)) - removeAt(i); - } - simplify(); -} - -/*! - Subclasses call this method to report changed (minimum/maximum) size constraints. - - If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref - sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of - QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, - it may update itself and resize cells accordingly. -*/ -void QCPLayout::sizeConstraintsChanged() const -{ - if (QWidget *w = qobject_cast(parent())) - w->updateGeometry(); - else if (QCPLayout *l = qobject_cast(parent())) - l->sizeConstraintsChanged(); -} - -/*! \internal - - Subclasses reimplement this method to update the position and sizes of the child elements/cells - via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. - - The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay - within that rect. - - \ref getSectionSizes may help with the reimplementation of this function. - - \see update -*/ -void QCPLayout::updateLayout() -{ -} - - -/*! \internal - - Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the - \ref QCPLayerable::parentLayerable and the QObject parent to this layout. - - Further, if \a el didn't previously have a parent plot, calls \ref - QCPLayerable::initializeParentPlot on \a el to set the paret plot. - - This method is used by subclass specific methods that add elements to the layout. Note that this - method only changes properties in \a el. The removal from the old layout and the insertion into - the new layout must be done additionally. -*/ -void QCPLayout::adoptElement(QCPLayoutElement *el) -{ - if (el) - { - el->mParentLayout = this; - el->setParentLayerable(this); - el->setParent(this); - if (!el->parentPlot()) - el->initializeParentPlot(mParentPlot); - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; -} - -/*! \internal - - Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout - and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent - QCustomPlot. - - This method is used by subclass specific methods that remove elements from the layout (e.g. \ref - take or \ref takeAt). Note that this method only changes properties in \a el. The removal from - the old layout must be done additionally. -*/ -void QCPLayout::releaseElement(QCPLayoutElement *el) -{ - if (el) - { - el->mParentLayout = 0; - el->setParentLayerable(0); - el->setParent(mParentPlot); - // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; -} - -/*! \internal - - This is a helper function for the implementation of \ref updateLayout in subclasses. - - It calculates the sizes of one-dimensional sections with provided constraints on maximum section - sizes, minimum section sizes, relative stretch factors and the final total size of all sections. - - The QVector entries refer to the sections. Thus all QVectors must have the same size. - - \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size - imposed, set all vector values to Qt's QWIDGETSIZE_MAX. - - \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size - imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than - \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, - not exceeding the allowed total size is taken to be more important than not going below minimum - section sizes.) - - \a stretchFactors give the relative proportions of the sections to each other. If all sections - shall be scaled equally, set all values equal. If the first section shall be double the size of - each individual other section, set the first number of \a stretchFactors to double the value of - the other individual values (e.g. {2, 1, 1, 1}). - - \a totalSize is the value that the final section sizes will add up to. Due to rounding, the - actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, - you could distribute the remaining difference on the sections. - - The return value is a QVector containing the section sizes. -*/ -QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const -{ - if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) - { - qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; - return QVector(); - } - if (stretchFactors.isEmpty()) - return QVector(); - int sectionCount = stretchFactors.size(); - QVector sectionSizes(sectionCount); - // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): - int minSizeSum = 0; - for (int i=0; i minimumLockedSections; - QList unfinishedSections; - for (int i=0; i result(sectionCount); - for (int i=0; i= 0 && row < mElements.size()) - { - if (column >= 0 && column < mElements.first().size()) - { - if (QCPLayoutElement *result = mElements.at(row).at(column)) - return result; - else - qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; - return 0; -} - -/*! - Returns the number of rows in the layout. - - \see columnCount -*/ -int QCPLayoutGrid::rowCount() const -{ - return mElements.size(); -} - -/*! - Returns the number of columns in the layout. - - \see rowCount -*/ -int QCPLayoutGrid::columnCount() const -{ - if (mElements.size() > 0) - return mElements.first().size(); - else - return 0; -} - -/*! - Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it - is first removed from there. If \a row or \a column don't exist yet, the layout is expanded - accordingly. - - Returns true if the element was added successfully, i.e. if the cell at \a row and \a column - didn't already have an element. - - \see element, hasElement, take, remove -*/ -bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) -{ - if (element) - { - if (!hasElement(row, column)) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - expandTo(row+1, column+1); - mElements[row][column] = element; - adoptElement(element); - return true; - } else - qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; - } else - qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; - return false; -} - -/*! - Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't - empty. - - \see element -*/ -bool QCPLayoutGrid::hasElement(int row, int column) -{ - if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) - return mElements.at(row).at(column); - else - return false; -} - -/*! - Sets the stretch \a factor of \a column. - - Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond - their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref - QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - - The default stretch factor of newly created rows/columns is 1. - - \see setColumnStretchFactors, setRowStretchFactor -*/ -void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) -{ - if (column >= 0 && column < columnCount()) - { - if (factor > 0) - mColumnStretchFactors[column] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid column:" << column; -} - -/*! - Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. - - Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond - their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref - QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - - The default stretch factor of newly created rows/columns is 1. - - \see setColumnStretchFactor, setRowStretchFactors -*/ -void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) -{ - if (factors.size() == mColumnStretchFactors.size()) - { - mColumnStretchFactors = factors; - for (int i=0; i= 0 && row < rowCount()) - { - if (factor > 0) - mRowStretchFactors[row] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid row:" << row; -} - -/*! - Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. - - Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond - their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref - QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - - The default stretch factor of newly created rows/columns is 1. - - \see setRowStretchFactor, setColumnStretchFactors -*/ -void QCPLayoutGrid::setRowStretchFactors(const QList &factors) -{ - if (factors.size() == mRowStretchFactors.size()) - { - mRowStretchFactors = factors; - for (int i=0; i()); - mRowStretchFactors.append(1); - } - // go through rows and expand columns as necessary: - int newColCount = qMax(columnCount(), newColumnCount); - for (int i=0; i rowCount()) - newIndex = rowCount(); - - mRowStretchFactors.insert(newIndex, 1); - QList newRow; - for (int col=0; col columnCount()) - newIndex = columnCount(); - - mColumnStretchFactors.insert(newIndex, 1); - for (int row=0; row minColWidths, minRowHeights, maxColWidths, maxRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - int totalRowSpacing = (rowCount()-1) * mRowSpacing; - int totalColSpacing = (columnCount()-1) * mColumnSpacing; - QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); - QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); - - // go through cells and set rects accordingly: - int yOffset = mRect.top(); - for (int row=0; row 0) - yOffset += rowHeights.at(row-1)+mRowSpacing; - int xOffset = mRect.left(); - for (int col=0; col 0) - xOffset += colWidths.at(col-1)+mColumnSpacing; - if (mElements.at(row).at(col)) - mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); - } - } -} - -/* inherits documentation from base class */ -int QCPLayoutGrid::elementCount() const -{ - return rowCount()*columnCount(); -} - -/* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const -{ - if (index >= 0 && index < elementCount()) - return mElements.at(index / columnCount()).at(index % columnCount()); - else - return 0; -} - -/* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutGrid::takeAt(int index) -{ - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements[index / columnCount()][index % columnCount()] = 0; - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } -} - -/* inherits documentation from base class */ -bool QCPLayoutGrid::take(QCPLayoutElement *element) -{ - if (element) - { - for (int i=0; i QCPLayoutGrid::elements(bool recursive) const -{ - QList result; - int colC = columnCount(); - int rowC = rowCount(); -#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(colC*rowC); -#endif - for (int row=0; rowelements(recursive); - } - } - return result; -} - -/*! - Simplifies the layout by collapsing rows and columns which only contain empty cells. -*/ -void QCPLayoutGrid::simplify() -{ - // remove rows with only empty cells: - for (int row=rowCount()-1; row>=0; --row) - { - bool hasElements = false; - for (int col=0; col=0; --col) - { - bool hasElements = false; - for (int row=0; row minColWidths, minRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - QSize result(0, 0); - for (int i=0; i maxColWidths, maxRowHeights; - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - QSize result(0, 0); - for (int i=0; i *minColWidths, QVector *minRowHeights) const -{ - *minColWidths = QVector(columnCount(), 0); - *minRowHeights = QVector(rowCount(), 0); - for (int row=0; rowminimumSizeHint(); - QSize min = mElements.at(row).at(col)->minimumSize(); - QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); - if (minColWidths->at(col) < final.width()) - (*minColWidths)[col] = final.width(); - if (minRowHeights->at(row) < final.height()) - (*minRowHeights)[row] = final.height(); - } - } - } -} - -/*! \internal - - Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights - respectively. - - The maximum height of a row is the smallest maximum height of any element in that row. The - maximum width of a column is the smallest maximum width of any element in that column. - - This is a helper function for \ref updateLayout. - - \see getMinimumRowColSizes -*/ -void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const -{ - *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); - *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); - for (int row=0; rowmaximumSizeHint(); - QSize max = mElements.at(row).at(col)->maximumSize(); - QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); - if (maxColWidths->at(col) > final.width()) - (*maxColWidths)[col] = final.width(); - if (maxRowHeights->at(row) > final.height()) - (*maxRowHeights)[row] = final.height(); - } - } - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLayoutInset -//////////////////////////////////////////////////////////////////////////////////////////////////// -/*! \class QCPLayoutInset - \brief A layout that places child elements aligned to the border or arbitrarily positioned - - Elements are placed either aligned to the border or at arbitrary position in the area of the - layout. Which placement applies is controlled with the \ref InsetPlacement (\ref - setInsetPlacement). - - Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or - addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset - placement will default to \ref ipBorderAligned and the element will be aligned according to the - \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at - arbitrary position and size, defined by \a rect. - - The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. - - This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. -*/ - -/* start documentation of inline functions */ - -/*! \fn virtual void QCPLayoutInset::simplify() - - The QCPInsetLayout does not need simplification since it can never have empty cells due to its - linear index structure. This method does nothing. -*/ - -/* end documentation of inline functions */ - -/*! - Creates an instance of QCPLayoutInset and sets default values. -*/ -QCPLayoutInset::QCPLayoutInset() -{ -} - -QCPLayoutInset::~QCPLayoutInset() -{ - // clear all child layout elements. This is important because only the specific layouts know how - // to handle removing elements (clear calls virtual removeAt method to do that). - clear(); -} - -/*! - Returns the placement type of the element with the specified \a index. -*/ -QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const -{ - if (elementAt(index)) - return mInsetPlacement.at(index); - else - { - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; - return ipFree; - } -} - -/*! - Returns the alignment of the element with the specified \a index. The alignment only has a - meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. -*/ -Qt::Alignment QCPLayoutInset::insetAlignment(int index) const -{ - if (elementAt(index)) - return mInsetAlignment.at(index); - else - { - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; - return 0; - } -} - -/*! - Returns the rect of the element with the specified \a index. The rect only has a - meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. -*/ -QRectF QCPLayoutInset::insetRect(int index) const -{ - if (elementAt(index)) - return mInsetRect.at(index); - else - { - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; - return QRectF(); - } -} - -/*! - Sets the inset placement type of the element with the specified \a index to \a placement. - - \see InsetPlacement -*/ -void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) -{ - if (elementAt(index)) - mInsetPlacement[index] = placement; - else - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; -} - -/*! - If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function - is used to set the alignment of the element with the specified \a index to \a alignment. - - \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, - Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other - alignment flags will be ignored. -*/ -void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) -{ - if (elementAt(index)) - mInsetAlignment[index] = alignment; - else - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; -} - -/*! - If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the - position and size of the element with the specified \a index to \a rect. - - \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) - will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right - corner of the layout, with 35% width and height of the parent layout. - - Note that the minimum and maximum sizes of the embedded element (\ref - QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. -*/ -void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) -{ - if (elementAt(index)) - mInsetRect[index] = rect; - else - qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; -} - -/* inherits documentation from base class */ -void QCPLayoutInset::updateLayout() -{ - for (int i=0; iminimumSizeHint(); - QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); - finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); - finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); - finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); - finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); - if (mInsetPlacement.at(i) == ipFree) - { - insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), - rect().y()+rect().height()*mInsetRect.at(i).y(), - rect().width()*mInsetRect.at(i).width(), - rect().height()*mInsetRect.at(i).height()); - if (insetRect.size().width() < finalMinSize.width()) - insetRect.setWidth(finalMinSize.width()); - if (insetRect.size().height() < finalMinSize.height()) - insetRect.setHeight(finalMinSize.height()); - if (insetRect.size().width() > finalMaxSize.width()) - insetRect.setWidth(finalMaxSize.width()); - if (insetRect.size().height() > finalMaxSize.height()) - insetRect.setHeight(finalMaxSize.height()); - } else if (mInsetPlacement.at(i) == ipBorderAligned) - { - insetRect.setSize(finalMinSize); - Qt::Alignment al = mInsetAlignment.at(i); - if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); - else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); - else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter - if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); - else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); - else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter - } - mElements.at(i)->setOuterRect(insetRect); - } -} - -/* inherits documentation from base class */ -int QCPLayoutInset::elementCount() const -{ - return mElements.size(); -} - -/* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutInset::elementAt(int index) const -{ - if (index >= 0 && index < mElements.size()) - return mElements.at(index); - else - return 0; -} - -/* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutInset::takeAt(int index) -{ - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements.removeAt(index); - mInsetPlacement.removeAt(index); - mInsetAlignment.removeAt(index); - mInsetRect.removeAt(index); - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } -} - -/* inherits documentation from base class */ -bool QCPLayoutInset::take(QCPLayoutElement *element) -{ - if (element) - { - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; -} - -/*! - Adds the specified \a element to the layout as an inset aligned at the border (\ref - setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a - alignment. - - \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, - Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other - alignment flags will be ignored. - - \see addElement(QCPLayoutElement *element, const QRectF &rect) -*/ -void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) -{ - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipBorderAligned); - mInsetAlignment.append(alignment); - mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; -} - -/*! - Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref - setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a - rect. - - \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) - will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right - corner of the layout, with 35% width and height of the parent layout. - - \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) -*/ -void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) -{ - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipFree); - mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); - mInsetRect.append(rect); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLineEnding -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLineEnding - \brief Handles the different ending decorations for line-like items - - \image html QCPLineEnding.png "The various ending styles currently supported" - - For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine - has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. - - The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can - be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of - the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. - For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite - directions, e.g. "outward". This can be changed by \ref setInverted, which would make the - respective arrow point inward. - - Note that due to the overloaded QCPLineEnding constructor, you may directly specify a - QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. - \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead -*/ - -/*! - Creates a QCPLineEnding instance with default values (style \ref esNone). -*/ -QCPLineEnding::QCPLineEnding() : - mStyle(esNone), - mWidth(8), - mLength(10), - mInverted(false) -{ -} - -/*! - Creates a QCPLineEnding instance with the specified values. -*/ -QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : - mStyle(style), - mWidth(width), - mLength(length), - mInverted(inverted) -{ -} - -/*! - Sets the style of the ending decoration. -*/ -void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) -{ - mStyle = style; -} - -/*! - Sets the width of the ending decoration, if the style supports it. On arrows, for example, the - width defines the size perpendicular to the arrow's pointing direction. - - \see setLength -*/ -void QCPLineEnding::setWidth(double width) -{ - mWidth = width; -} - -/*! - Sets the length of the ending decoration, if the style supports it. On arrows, for example, the - length defines the size in pointing direction. - - \see setWidth -*/ -void QCPLineEnding::setLength(double length) -{ - mLength = length; -} - -/*! - Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point - inward when \a inverted is set to true. - - Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or - discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are - affected by it, which can be used to control to which side the half bar points to. -*/ -void QCPLineEnding::setInverted(bool inverted) -{ - mInverted = inverted; -} - -/*! \internal - - Returns the maximum pixel radius the ending decoration might cover, starting from the position - the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). - - This is relevant for clipping. Only omit painting of the decoration when the position where the - decoration is supposed to be drawn is farther away from the clipping rect than the returned - distance. -*/ -double QCPLineEnding::boundingDistance() const -{ - switch (mStyle) - { - case esNone: - return 0; - - case esFlatArrow: - case esSpikeArrow: - case esLineArrow: - case esSkewedBar: - return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length - - case esDisc: - case esSquare: - case esDiamond: - case esBar: - case esHalfBar: - return mWidth*1.42; // items that only have a width -> width*sqrt(2) - - } - return 0; -} - -/*! - Starting from the origin of this line ending (which is style specific), returns the length - covered by the line ending symbol, in backward direction. - - For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if - both have the same \ref setLength value, because the spike arrow has an inward curved back, which - reduces the length along its center axis (the drawing origin for arrows is at the tip). - - This function is used for precise, style specific placement of line endings, for example in - QCPAxes. -*/ -double QCPLineEnding::realLength() const -{ - switch (mStyle) - { - case esNone: - case esLineArrow: - case esSkewedBar: - case esBar: - case esHalfBar: - return 0; - - case esFlatArrow: - return mLength; - - case esDisc: - case esSquare: - case esDiamond: - return mWidth*0.5; - - case esSpikeArrow: - return mLength*0.8; - } - return 0; -} - -/*! \internal - - Draws the line ending with the specified \a painter at the position \a pos. The direction of the - line ending is controlled with \a dir. -*/ -void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const -{ - if (mStyle == esNone) - return; - - QVector2D lengthVec(dir.normalized()); - if (lengthVec.isNull()) - lengthVec = QVector2D(1, 0); - QVector2D widthVec(-lengthVec.y(), lengthVec.x()); - lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); - widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); - - QPen penBackup = painter->pen(); - QBrush brushBackup = painter->brush(); - QPen miterPen = penBackup; - miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey - QBrush brush(painter->pen().color(), Qt::SolidPattern); - switch (mStyle) - { - case esNone: break; - case esFlatArrow: - { - QPointF points[3] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 3); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esSpikeArrow: - { - QPointF points[4] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec*0.8f).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esLineArrow: - { - QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), - pos.toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->drawPolyline(points, 3); - painter->setPen(penBackup); - break; - } - case esDisc: - { - painter->setBrush(brush); - painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); - painter->setBrush(brushBackup); - break; - } - case esSquare: - { - QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); - QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), - (pos-widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esDiamond: - { - QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); - QPointF points[4] = {(pos-widthVecPerp).toPointF(), - (pos-widthVec).toPointF(), - (pos+widthVecPerp).toPointF(), - (pos+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esBar: - { - painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); - break; - } - case esHalfBar: - { - painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); - break; - } - case esSkewedBar: - { - if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) - { - // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line - painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), - (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); - } else - { - // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly - painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), - (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); - } - break; - } - } -} - -/*! \internal - \overload - - Draws the line ending. The direction is controlled with the \a angle parameter in radians. -*/ -void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const -{ - draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPGrid -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPGrid - \brief Responsible for drawing the grid of a QCPAxis. - - This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the - grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref - QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. - - The axis and grid drawing was split into two classes to allow them to be placed on different - layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid - in the background and the axes in the foreground, and any plottables/items in between. This - described situation is the default setup, see the QCPLayer documentation. -*/ - -/*! - Creates a QCPGrid instance and sets default values. - - You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. -*/ -QCPGrid::QCPGrid(QCPAxis *parentAxis) : - QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), - mParentAxis(parentAxis) -{ - // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called - setParent(parentAxis); - setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); - setSubGridVisible(false); - setAntialiased(false); - setAntialiasedSubGrid(false); - setAntialiasedZeroLine(false); -} - -/*! - Sets whether grid lines at sub tick marks are drawn. - - \see setSubGridPen -*/ -void QCPGrid::setSubGridVisible(bool visible) -{ - mSubGridVisible = visible; -} - -/*! - Sets whether sub grid lines are drawn antialiased. -*/ -void QCPGrid::setAntialiasedSubGrid(bool enabled) -{ - mAntialiasedSubGrid = enabled; -} - -/*! - Sets whether zero lines are drawn antialiased. -*/ -void QCPGrid::setAntialiasedZeroLine(bool enabled) -{ - mAntialiasedZeroLine = enabled; -} - -/*! - Sets the pen with which (major) grid lines are drawn. -*/ -void QCPGrid::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen with which sub grid lines are drawn. -*/ -void QCPGrid::setSubGridPen(const QPen &pen) -{ - mSubGridPen = pen; -} - -/*! - Sets the pen with which zero lines are drawn. - - Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid - lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. -*/ -void QCPGrid::setZeroLinePen(const QPen &pen) -{ - mZeroLinePen = pen; -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing the major grid lines. - - This is the antialiasing state the painter passed to the \ref draw method is in by default. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased -*/ -void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); -} - -/*! \internal - - Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning - over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). -*/ -void QCPGrid::draw(QCPPainter *painter) -{ - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - if (mSubGridVisible) - drawSubGridLines(painter); - drawGridLines(painter); -} - -/*! \internal - - Draws the main grid lines and possibly a zero line with the specified painter. - - This is a helper function called by \ref draw. -*/ -void QCPGrid::drawGridLines(QCPPainter *painter) const -{ - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - int lowTick = mParentAxis->mLowestVisibleTick; - int highTick = mParentAxis->mHighestVisibleTick; - double t; // helper variable, result of coordinate-to-pixel transforms - if (mParentAxis->orientation() == Qt::Horizontal) - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero - for (int i=lowTick; i <= highTick; ++i) - { - if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - break; - } - } - } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=lowTick; i <= highTick; ++i) - { - if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - } - } else - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero - for (int i=lowTick; i <= highTick; ++i) - { - if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - break; - } - } - } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=lowTick; i <= highTick; ++i) - { - if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - } - } -} - -/*! \internal - - Draws the sub grid lines with the specified painter. - - This is a helper function called by \ref draw. -*/ -void QCPGrid::drawSubGridLines(QCPPainter *painter) const -{ - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); - double t; // helper variable, result of coordinate-to-pixel transforms - painter->setPen(mSubGridPen); - if (mParentAxis->orientation() == Qt::Horizontal) - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - } - } else - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - } - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAxis -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAxis - \brief Manages a single axis inside a QCustomPlot. - - Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via - QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and - QCustomPlot::yAxis2 (right). - - Axes are always part of an axis rect, see QCPAxisRect. - \image html AxisNamesOverview.png -
Naming convention of axis parts
- \n - - \image html AxisRectSpacingOverview.png -
Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line - on the left represents the QCustomPlot widget border.
- -*/ - -/* start of documentation of inline functions */ - -/*! \fn Qt::Orientation QCPAxis::orientation() const - - Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced - from the axis type (left, top, right or bottom). - - \see orientation(AxisType type) -*/ - -/*! \fn QCPGrid *QCPAxis::grid() const - - Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the - grid is displayed. -*/ - -/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) - - Returns the orientation of the specified axis type - - \see orientation() -*/ - -/* end of documentation of inline functions */ -/* start of documentation of signals */ - -/*! \fn void QCPAxis::ticksRequest() - - This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick - labels for a replot. - - Modifying the tick positions can be done with \ref setTickVector. If you also want to control the - tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref - setTickVectorLabels. - - If you only want static ticks you probably don't need this signal, since you can just set the - tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and - maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this - signal and set the vector/vectors there. -*/ - -/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) - - This signal is emitted when the range of this axis has changed. You can connect it to the \ref - setRange slot of another axis to communicate the new range to the other axis, in order for it to - be synchronized. - - You may also manipulate/correct the range with \ref setRange in a slot connected to this signal. - This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper - range shouldn't go beyond certain values. For example, the following slot would limit the x axis - to only positive ranges: - \code - if (newRange.lower < 0) - plot->xAxis->setRange(0, newRange.size()); - \endcode -*/ - -/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) - \overload - - Additionally to the new range, this signal also provides the previous range held by the axis as - \a oldRange. -*/ - -/*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); - - This signal is emitted when the scale type changes, by calls to \ref setScaleType -*/ - -/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) - - This signal is emitted when the selection state of this axis has changed, either by user interaction - or by a direct call to \ref setSelectedParts. -*/ - -/*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); - - This signal is emitted when the selectability changes, by calls to \ref setSelectableParts -*/ - -/* end of documentation of signals */ - -/*! - Constructs an Axis instance of Type \a type for the axis rect \a parent. - - Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create - them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, - create them manually and then inject them also via \ref QCPAxisRect::addAxis. -*/ -QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : - QCPLayerable(parent->parentPlot(), QString(), parent), - // axis base: - mAxisType(type), - mAxisRect(parent), - mPadding(5), - mOrientation(orientation(type)), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - mSelectedLabelColor(Qt::blue), - // tick labels: - mTickLabels(true), - mAutoTickLabels(true), - mTickLabelType(ltNumber), - mTickLabelFont(mParentPlot->font()), - mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), - mTickLabelColor(Qt::black), - mSelectedTickLabelColor(Qt::blue), - mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), - mDateTimeSpec(Qt::LocalTime), - mNumberPrecision(6), - mNumberFormatChar('g'), - mNumberBeautifulPowers(true), - // ticks and subticks: - mTicks(true), - mTickStep(1), - mSubTickCount(4), - mAutoTickCount(6), - mAutoTicks(true), - mAutoTickStep(true), - mAutoSubTicks(true), - mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedTickPen(QPen(Qt::blue, 2)), - mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - mRange(0, 5), - mRangeReversed(false), - mScaleType(stLinear), - mScaleLogBase(10), - mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), - // internal members: - mGrid(new QCPGrid(this)), - mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), - mLowestVisibleTick(0), - mHighestVisibleTick(-1), - mCachedMarginValid(false), - mCachedMargin(0) -{ - setParent(parent); - mGrid->setVisible(false); - setAntialiased(false); - setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again - - if (type == atTop) - { - setTickLabelPadding(3); - setLabelPadding(6); - } else if (type == atRight) - { - setTickLabelPadding(7); - setLabelPadding(12); - } else if (type == atBottom) - { - setTickLabelPadding(3); - setLabelPadding(3); - } else if (type == atLeft) - { - setTickLabelPadding(5); - setLabelPadding(10); - } -} - -QCPAxis::~QCPAxis() -{ - delete mAxisPainter; - delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order -} - -/* No documentation as it is a property getter */ -int QCPAxis::tickLabelPadding() const -{ - return mAxisPainter->tickLabelPadding; -} - -/* No documentation as it is a property getter */ -double QCPAxis::tickLabelRotation() const -{ - return mAxisPainter->tickLabelRotation; -} - -/* No documentation as it is a property getter */ -QCPAxis::LabelSide QCPAxis::tickLabelSide() const -{ - return mAxisPainter->tickLabelSide; -} - -/* No documentation as it is a property getter */ -QString QCPAxis::numberFormat() const -{ - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mAxisPainter->numberMultiplyCross) - result.append(QLatin1Char('c')); - } - return result; -} - -/* No documentation as it is a property getter */ -int QCPAxis::tickLengthIn() const -{ - return mAxisPainter->tickLengthIn; -} - -/* No documentation as it is a property getter */ -int QCPAxis::tickLengthOut() const -{ - return mAxisPainter->tickLengthOut; -} - -/* No documentation as it is a property getter */ -int QCPAxis::subTickLengthIn() const -{ - return mAxisPainter->subTickLengthIn; -} - -/* No documentation as it is a property getter */ -int QCPAxis::subTickLengthOut() const -{ - return mAxisPainter->subTickLengthOut; -} - -/* No documentation as it is a property getter */ -int QCPAxis::labelPadding() const -{ - return mAxisPainter->labelPadding; -} - -/* No documentation as it is a property getter */ -int QCPAxis::offset() const -{ - return mAxisPainter->offset; -} - -/* No documentation as it is a property getter */ -QCPLineEnding QCPAxis::lowerEnding() const -{ - return mAxisPainter->lowerEnding; -} - -/* No documentation as it is a property getter */ -QCPLineEnding QCPAxis::upperEnding() const -{ - return mAxisPainter->upperEnding; -} - -/*! - Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref - stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis - scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step - (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major - ticks, consider choosing a logarithm base of 100, 1000 or even higher. - - If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option - (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 - [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" - part). To only display the decimal power, set the number precision to zero with - \ref setNumberPrecision. -*/ -void QCPAxis::setScaleType(QCPAxis::ScaleType type) -{ - if (mScaleType != type) - { - mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); - mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); - } -} - -/*! - If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the - scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. - - Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but - less major ticks, consider choosing \a base 100, 1000 or even higher. -*/ -void QCPAxis::setScaleLogBase(double base) -{ - if (base > 1) - { - mScaleLogBase = base; - mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation - mCachedMarginValid = false; - } else - qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; -} - -/*! - Sets the range of the axis. - - This slot may be connected with the \ref rangeChanged signal of another axis so this axis - is always synchronized with the other axis range, when it changes. - - To invert the direction of an axis, use \ref setRangeReversed. -*/ -void QCPAxis::setRange(const QCPRange &range) -{ - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) - { - mRange = range.sanitizedForLogScale(); - } else - { - mRange = range.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. - (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - - However, even when \a selectable is set to a value not allowing the selection of a specific part, - it is still possible to set the selection of this part manually, by calling \ref setSelectedParts - directly. - - \see SelectablePart, setSelectedParts -*/ -void QCPAxis::setSelectableParts(const SelectableParts &selectable) -{ - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } -} - -/*! - Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part - is selected, it uses a different pen/font. - - The entire selection mechanism for axes is handled automatically when \ref - QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you - wish to change the selection state manually. - - This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - - emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - - \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, - setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor -*/ -void QCPAxis::setSelectedParts(const SelectableParts &selected) -{ - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } -} - -/*! - \overload - - Sets the lower and upper bound of the axis range. - - To invert the direction of an axis, use \ref setRangeReversed. - - There is also a slot to set a range, see \ref setRange(const QCPRange &range). -*/ -void QCPAxis::setRange(double lower, double upper) -{ - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - \overload - - Sets the range of the axis. - - The \a position coordinate indicates together with the \a alignment parameter, where the new - range will be positioned. \a size defines the size of the new axis range. \a alignment may be - Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, - or center of the range to be aligned with \a position. Any other values of \a alignment will - default to Qt::AlignCenter. -*/ -void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) -{ - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); -} - -/*! - Sets the lower bound of the axis range. The upper bound is not changed. - \see setRange -*/ -void QCPAxis::setRangeLower(double lower) -{ - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - Sets the upper bound of the axis range. The lower bound is not changed. - \see setRange -*/ -void QCPAxis::setRangeUpper(double upper) -{ - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal - axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the - direction of increasing values is inverted. - - Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part - of the \ref setRange interface will still reference the mathematically smaller number than the \a - upper part. -*/ -void QCPAxis::setRangeReversed(bool reversed) -{ - if (mRangeReversed != reversed) - { - mRangeReversed = reversed; - mCachedMarginValid = false; - } -} - -/*! - Sets whether the tick positions should be calculated automatically (either from an automatically - generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). - - If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. - For these manual ticks you may let QCPAxis generate the appropriate labels automatically by - leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels - manually, set \ref setAutoTickLabels to false and provide the label strings with \ref - setTickVectorLabels. - - If you need dynamically calculated tick vectors (and possibly tick label vectors), set the - vectors in a slot connected to the \ref ticksRequest signal. - - \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep -*/ -void QCPAxis::setAutoTicks(bool on) -{ - if (mAutoTicks != on) - { - mAutoTicks = on; - mCachedMarginValid = false; - } -} - -/*! - When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be - generated in the visible range, approximately. - - It's not guaranteed that this number of ticks is met exactly, but approximately within a - tolerance of about two. - - Only values greater than zero are accepted as \a approximateCount. - - \see setAutoTickStep, setAutoTicks, setAutoSubTicks -*/ -void QCPAxis::setAutoTickCount(int approximateCount) -{ - if (mAutoTickCount != approximateCount) - { - if (approximateCount > 0) - { - mAutoTickCount = approximateCount; - mCachedMarginValid = false; - } else - qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; - } -} - -/*! - Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref - ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point - number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. - - If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This - is usually used in a combination with \ref setAutoTicks set to false for complete control over - tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" - etc. as tick labels. - - If you need dynamically calculated tick vectors (and possibly tick label vectors), set the - vectors in a slot connected to the \ref ticksRequest signal. - - \see setAutoTicks -*/ -void QCPAxis::setAutoTickLabels(bool on) -{ - if (mAutoTickLabels != on) - { - mAutoTickLabels = on; - mCachedMarginValid = false; - } -} - -/*! - Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated - automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human - readable plots. - - The number of ticks the algorithm aims for within the visible range can be specified with \ref - setAutoTickCount. - - If \a on is set to false, you may set the tick step manually with \ref setTickStep. - - \see setAutoTicks, setAutoSubTicks, setAutoTickCount -*/ -void QCPAxis::setAutoTickStep(bool on) -{ - if (mAutoTickStep != on) - { - mAutoTickStep = on; - mCachedMarginValid = false; - } -} - -/*! - Sets whether the number of sub ticks in one tick interval is determined automatically. This - works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is - enabled, this is always the case. - - When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. - - \see setAutoTickCount, setAutoTicks, setAutoTickStep -*/ -void QCPAxis::setAutoSubTicks(bool on) -{ - if (mAutoSubTicks != on) - { - mAutoSubTicks = on; - mCachedMarginValid = false; - } -} - -/*! - Sets whether tick marks are displayed. - - Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve - that, see \ref setTickLabels. -*/ -void QCPAxis::setTicks(bool show) -{ - if (mTicks != show) - { - mTicks = show; - mCachedMarginValid = false; - } -} - -/*! - Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. -*/ -void QCPAxis::setTickLabels(bool show) -{ - if (mTickLabels != show) - { - mTickLabels = show; - mCachedMarginValid = false; - } -} - -/*! - Sets the distance between the axis base line (including any outward ticks) and the tick labels. - \see setLabelPadding, setPadding -*/ -void QCPAxis::setTickLabelPadding(int padding) -{ - if (mAxisPainter->tickLabelPadding != padding) - { - mAxisPainter->tickLabelPadding = padding; - mCachedMarginValid = false; - } -} - -/*! - Sets whether the tick labels display numbers or dates/times. - - If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. - - If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. - - In QCustomPlot, date/time coordinates are double numbers representing the seconds since - 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the - QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also - the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in - milliseconds. Divide its return value by 1000.0 to get a value with the format needed for - date/time plotting, with a resolution of one millisecond. - - Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. - (represented by a negative number), unlike the toTime_t function, which works with unsigned - integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of - toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. - - \see setTickLabels -*/ -void QCPAxis::setTickLabelType(LabelType type) -{ - if (mTickLabelType != type) - { - mTickLabelType = type; - mCachedMarginValid = false; - } -} - -/*! - Sets the font of the tick labels. - - \see setTickLabels, setTickLabelColor -*/ -void QCPAxis::setTickLabelFont(const QFont &font) -{ - if (font != mTickLabelFont) - { - mTickLabelFont = font; - mCachedMarginValid = false; - } -} - -/*! - Sets the color of the tick labels. - - \see setTickLabels, setTickLabelFont -*/ -void QCPAxis::setTickLabelColor(const QColor &color) -{ - if (color != mTickLabelColor) - { - mTickLabelColor = color; - mCachedMarginValid = false; - } -} - -/*! - Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, - the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values - from -90 to 90 degrees. - - If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For - other angles, the label is drawn with an offset such that it seems to point toward or away from - the tick mark. -*/ -void QCPAxis::setTickLabelRotation(double degrees) -{ - if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) - { - mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); - mCachedMarginValid = false; - } -} - -/*! - Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. - - The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels - to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels - appear on the inside are additionally clipped to the axis rect. -*/ -void QCPAxis::setTickLabelSide(LabelSide side) -{ - mAxisPainter->tickLabelSide = side; - mCachedMarginValid = false; -} - -/*! - Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. - for details about the \a format string, see the documentation of QDateTime::toString(). - - Newlines can be inserted with "\n". - - \see setDateTimeSpec -*/ -void QCPAxis::setDateTimeFormat(const QString &format) -{ - if (mDateTimeFormat != format) - { - mDateTimeFormat = format; - mCachedMarginValid = false; - } -} - -/*! - Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref - ltDateTime. - - The default value of QDateTime objects (and also QCustomPlot) is Qt::LocalTime. However, - if the date time values passed to QCustomPlot are given in the UTC spec, set \a - timeSpec to Qt::UTC to get the correct axis labels. - - \see setDateTimeFormat -*/ -void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) -{ - mDateTimeSpec = timeSpec; -} - -/*! - Sets the number format for the numbers drawn as tick labels (if tick label type is \ref - ltNumber). This \a formatCode is an extended version of the format code used e.g. by - QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" - section in the detailed description of the QString class. \a formatCode is a string of one, two - or three characters. The first character is identical to the normal format code used by Qt. In - short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, - whichever is shorter. - - The second and third characters are optional and specific to QCustomPlot:\n - If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. - "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for - "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 - [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. - If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can - be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the - cross and 183 (0xB7) for the dot. - - If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' - option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 - [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" - part). To only display the decimal power, set the number precision to zero with \ref - setNumberPrecision. - - Examples for \a formatCode: - \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, - normal scientific format is used - \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with - beautifully typeset decimal powers and a dot as multiplication sign - \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as - multiplication sign - \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal - powers. Format code will be reduced to 'f'. - \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format - code will not be changed. -*/ -void QCPAxis::setNumberFormat(const QString &formatCode) -{ - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - { - mNumberBeautifulPowers = true; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - return; - } - if (formatCode.length() < 3) - { - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - { - mAxisPainter->numberMultiplyCross = true; - } else if (formatCode.at(2) == QLatin1Char('d')) - { - mAxisPainter->numberMultiplyCross = false; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; - return; - } -} - -/*! - Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) - for details. The effect of precisions are most notably for number Formats starting with 'e', see - \ref setNumberFormat - - If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref - setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display - usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic - scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 - [superscript] n", set \a precision to zero. -*/ -void QCPAxis::setNumberPrecision(int precision) -{ - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - mCachedMarginValid = false; - } -} - -/*! - If \ref setAutoTickStep is set to false, use this function to set the tick step manually. - The tick step is the interval between (major) ticks, in plot coordinates. - \see setSubTickCount -*/ -void QCPAxis::setTickStep(double step) -{ - if (mTickStep != step) - { - mTickStep = step; - mCachedMarginValid = false; - } -} - -/*! - If you want full control over what ticks (and possibly labels) the axes show, this function is - used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else - the provided tick vector will be overwritten with automatically generated tick coordinates upon - replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is - left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. - - \a vec is a vector containing the positions of the ticks, in plot coordinates. - - \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. - - \see setTickVectorLabels -*/ -void QCPAxis::setTickVector(const QVector &vec) -{ - // don't check whether mTickVector != vec here, because it takes longer than we would save - mTickVector = vec; - mCachedMarginValid = false; -} - -/*! - If you want full control over what ticks and labels the axes show, this function is used to set a - number of QStrings that will be displayed at the tick positions which you need to provide with - \ref setTickVector. These two vectors should have the same size. (Note that you need to disable - \ref setAutoTicks and \ref setAutoTickLabels first.) - - \a vec is a vector containing the labels of the ticks. The entries correspond to the respective - indices in the tick vector, passed via \ref setTickVector. - - \see setTickVector -*/ -void QCPAxis::setTickVectorLabels(const QVector &vec) -{ - // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save - mTickVectorLabels = vec; - mCachedMarginValid = false; -} - -/*! - Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the - plot and \a outside is the length they will reach outside the plot. If \a outside is greater than - zero, the tick labels and axis label will increase their distance to the axis accordingly, so - they won't collide with the ticks. - - \see setSubTickLength, setTickLengthIn, setTickLengthOut -*/ -void QCPAxis::setTickLength(int inside, int outside) -{ - setTickLengthIn(inside); - setTickLengthOut(outside); -} - -/*! - Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach - inside the plot. - - \see setTickLengthOut, setTickLength, setSubTickLength -*/ -void QCPAxis::setTickLengthIn(int inside) -{ - if (mAxisPainter->tickLengthIn != inside) - { - mAxisPainter->tickLengthIn = inside; - } -} - -/*! - Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach - outside the plot. If \a outside is greater than zero, the tick labels and axis label will - increase their distance to the axis accordingly, so they won't collide with the ticks. - - \see setTickLengthIn, setTickLength, setSubTickLength -*/ -void QCPAxis::setTickLengthOut(int outside) -{ - if (mAxisPainter->tickLengthOut != outside) - { - mAxisPainter->tickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } -} - -/*! - Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, - divides the tick intervals in four sub intervals. - - By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the - mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is - always the case. - - If you want to disable automatic sub tick count and use this function to set the count manually, - see \ref setAutoSubTicks. -*/ -void QCPAxis::setSubTickCount(int count) -{ - mSubTickCount = count; -} - -/*! - Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside - the plot and \a outside is the length they will reach outside the plot. If \a outside is greater - than zero, the tick labels and axis label will increase their distance to the axis accordingly, - so they won't collide with the ticks. - - \see setTickLength, setSubTickLengthIn, setSubTickLengthOut -*/ -void QCPAxis::setSubTickLength(int inside, int outside) -{ - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); -} - -/*! - Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside - the plot. - - \see setSubTickLengthOut, setSubTickLength, setTickLength -*/ -void QCPAxis::setSubTickLengthIn(int inside) -{ - if (mAxisPainter->subTickLengthIn != inside) - { - mAxisPainter->subTickLengthIn = inside; - } -} - -/*! - Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach - outside the plot. If \a outside is greater than zero, the tick labels will increase their - distance to the axis accordingly, so they won't collide with the ticks. - - \see setSubTickLengthIn, setSubTickLength, setTickLength -*/ -void QCPAxis::setSubTickLengthOut(int outside) -{ - if (mAxisPainter->subTickLengthOut != outside) - { - mAxisPainter->subTickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } -} - -/*! - Sets the pen, the axis base line is drawn with. - - \see setTickPen, setSubTickPen -*/ -void QCPAxis::setBasePen(const QPen &pen) -{ - mBasePen = pen; -} - -/*! - Sets the pen, tick marks will be drawn with. - - \see setTickLength, setBasePen -*/ -void QCPAxis::setTickPen(const QPen &pen) -{ - mTickPen = pen; -} - -/*! - Sets the pen, subtick marks will be drawn with. - - \see setSubTickCount, setSubTickLength, setBasePen -*/ -void QCPAxis::setSubTickPen(const QPen &pen) -{ - mSubTickPen = pen; -} - -/*! - Sets the font of the axis label. - - \see setLabelColor -*/ -void QCPAxis::setLabelFont(const QFont &font) -{ - if (mLabelFont != font) - { - mLabelFont = font; - mCachedMarginValid = false; - } -} - -/*! - Sets the color of the axis label. - - \see setLabelFont -*/ -void QCPAxis::setLabelColor(const QColor &color) -{ - mLabelColor = color; -} - -/*! - Sets the text of the axis label that will be shown below/above or next to the axis, depending on - its orientation. To disable axis labels, pass an empty string as \a str. -*/ -void QCPAxis::setLabel(const QString &str) -{ - if (mLabel != str) - { - mLabel = str; - mCachedMarginValid = false; - } -} - -/*! - Sets the distance between the tick labels and the axis label. - - \see setTickLabelPadding, setPadding -*/ -void QCPAxis::setLabelPadding(int padding) -{ - if (mAxisPainter->labelPadding != padding) - { - mAxisPainter->labelPadding = padding; - mCachedMarginValid = false; - } -} - -/*! - Sets the padding of the axis. - - When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, - that is left blank. - - The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. - - \see setLabelPadding, setTickLabelPadding -*/ -void QCPAxis::setPadding(int padding) -{ - if (mPadding != padding) - { - mPadding = padding; - mCachedMarginValid = false; - } -} - -/*! - Sets the offset the axis has to its axis rect side. - - If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, - only the offset of the inner most axis has meaning (even if it is set to be invisible). The - offset of the other, outer axes is controlled automatically, to place them at appropriate - positions. -*/ -void QCPAxis::setOffset(int offset) -{ - mAxisPainter->offset = offset; -} - -/*! - Sets the font that is used for tick labels when they are selected. - - \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedTickLabelFont(const QFont &font) -{ - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } -} - -/*! - Sets the font that is used for the axis label when it is selected. - - \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedLabelFont(const QFont &font) -{ - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts -} - -/*! - Sets the color that is used for tick labels when they are selected. - - \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedTickLabelColor(const QColor &color) -{ - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } -} - -/*! - Sets the color that is used for the axis label when it is selected. - - \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedLabelColor(const QColor &color) -{ - mSelectedLabelColor = color; -} - -/*! - Sets the pen that is used to draw the axis base line when selected. - - \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedBasePen(const QPen &pen) -{ - mSelectedBasePen = pen; -} - -/*! - Sets the pen that is used to draw the (major) ticks when selected. - - \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedTickPen(const QPen &pen) -{ - mSelectedTickPen = pen; -} - -/*! - Sets the pen that is used to draw the subticks when selected. - - \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAxis::setSelectedSubTickPen(const QPen &pen) -{ - mSelectedSubTickPen = pen; -} - -/*! - Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available - styles. - - For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. - Note that this meaning does not change when the axis range is reversed with \ref - setRangeReversed. - - \see setUpperEnding -*/ -void QCPAxis::setLowerEnding(const QCPLineEnding &ending) -{ - mAxisPainter->lowerEnding = ending; -} - -/*! - Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available - styles. - - For horizontal axes, this method refers to the right ending, for vertical axes the top ending. - Note that this meaning does not change when the axis range is reversed with \ref - setRangeReversed. - - \see setLowerEnding -*/ -void QCPAxis::setUpperEnding(const QCPLineEnding &ending) -{ - mAxisPainter->upperEnding = ending; -} - -/*! - If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper - bounds of the range. The range is simply moved by \a diff. - - If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This - corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). -*/ -void QCPAxis::moveRange(double diff) -{ - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - mRange.lower += diff; - mRange.upper += diff; - } else // mScaleType == stLogarithmic - { - mRange.lower *= diff; - mRange.upper *= diff; - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a - factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at - coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates - around 1.0 will have moved symmetrically closer to 1.0). -*/ -void QCPAxis::scaleRange(double factor, double center) -{ - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - } else // mScaleType == stLogarithmic - { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range - { - QCPRange newRange; - newRange.lower = qPow(mRange.lower/center, factor)*center; - newRange.upper = qPow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLogScale(); - } else - qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); -} - -/*! - Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will - be done around the center of the current axis range. - - For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs - plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the - axis rect has. - - This is an operation that changes the range of this axis once, it doesn't fix the scale ratio - indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent - won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent - will follow. -*/ -void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) -{ - int otherPixelSize, ownPixelSize; - - if (otherAxis->orientation() == Qt::Horizontal) - otherPixelSize = otherAxis->axisRect()->width(); - else - otherPixelSize = otherAxis->axisRect()->height(); - - if (orientation() == Qt::Horizontal) - ownPixelSize = axisRect()->width(); - else - ownPixelSize = axisRect()->height(); - - double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; - setRange(range().center(), newRangeSize, Qt::AlignCenter); -} - -/*! - Changes the axis range such that all plottables associated with this axis are fully visible in - that dimension. - - \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes -*/ -void QCPAxis::rescale(bool onlyVisiblePlottables) -{ - QList p = plottables(); - QCPRange newRange; - bool haveRange = false; - for (int i=0; irealVisibility() && onlyVisiblePlottables) - continue; - QCPRange plottableRange; - bool currentFoundRange; - QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; - if (mScaleType == stLogarithmic) - signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); - if (p.at(i)->keyAxis() == this) - plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); - else - plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); - if (currentFoundRange) - { - if (!haveRange) - newRange = plottableRange; - else - newRange.expand(plottableRange); - haveRange = true; - } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mScaleType == stLinear) - { - newRange.lower = center-mRange.size()/2.0; - newRange.upper = center+mRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mRange.upper/mRange.lower); - newRange.upper = center*qSqrt(mRange.upper/mRange.lower); - } - } - setRange(newRange); - } -} - -/*! - Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. -*/ -double QCPAxis::pixelToCoord(double value) const -{ - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; - else - return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; - } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; - else - return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; - } - } -} - -/*! - Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. -*/ -double QCPAxis::coordToPixel(double value) const -{ - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - else - return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - } else // mScaleType == stLogarithmic - { - if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; - else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; - else - { - if (!mRangeReversed) - return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - else - return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - } - } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); - else - return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); - } else // mScaleType == stLogarithmic - { - if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; - else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; - else - { - if (!mRangeReversed) - return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); - else - return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); - } - } - } -} - -/*! - Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function - is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this - function does not change the current selection state of the axis. - - If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - - \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions -*/ -QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const -{ - if (!mVisible) - return spNone; - - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) - return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) - return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) - return spAxisLabel; - else - return spNone; -} - -/* inherits documentation from base class */ -double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) - return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; -} - -/*! - Returns a list of all the plottables that have this axis as key or value axis. - - If you are only interested in plottables of type QCPGraph, see \ref graphs. - - \see graphs, items -*/ -QList QCPAxis::plottables() const -{ - QList result; - if (!mParentPlot) return result; - - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; -} - -/*! - Returns a list of all the graphs that have this axis as key or value axis. - - \see plottables, items -*/ -QList QCPAxis::graphs() const -{ - QList result; - if (!mParentPlot) return result; - - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; -} - -/*! - Returns a list of all the items that are associated with this axis. An item is considered - associated with an axis if at least one of its positions uses the axis as key or value axis. - - \see plottables, graphs -*/ -QList QCPAxis::items() const -{ - QList result; - if (!mParentPlot) return result; - - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } - } - } - return result; -} - -/*! - Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to - QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) -*/ -QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) -{ - switch (side) - { - case QCP::msLeft: return atLeft; - case QCP::msRight: return atRight; - case QCP::msTop: return atTop; - case QCP::msBottom: return atBottom; - default: break; - } - qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; - return atLeft; -} - -/*! - Returns the axis type that describes the opposite axis of an axis with the specified \a type. -*/ -QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) -{ - switch (type) - { - case atLeft: return atRight; break; - case atRight: return atLeft; break; - case atBottom: return atTop; break; - case atTop: return atBottom; break; - default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; - } -} - -/*! \internal - - This function is called to prepare the tick vector, sub tick vector and tick label vector. If - \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref - generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to - provide external tick positions. Then the sub tick vectors and tick label vectors are created. -*/ -void QCPAxis::setupTickVectors() -{ - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - - // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself - if (mAutoTicks) - { - generateAutoTicks(); - } else - { - emit ticksRequest(); - } - - visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); - if (mTickVector.isEmpty()) - { - mSubTickVector.clear(); - return; - } - - // generate subticks between ticks: - mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); - if (mSubTickCount > 0) - { - double subTickStep = 0; - double subTickPosition = 0; - int subTickIndex = 0; - bool done = false; - int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; - int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; - for (int i=lowTick+1; i<=highTick; ++i) - { - subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); - for (int k=1; k<=mSubTickCount; ++k) - { - subTickPosition = mTickVector.at(i-1) + k*subTickStep; - if (subTickPosition < mRange.lower) - continue; - if (subTickPosition > mRange.upper) - { - done = true; - break; - } - mSubTickVector[subTickIndex] = subTickPosition; - subTickIndex++; - } - if (done) break; - } - mSubTickVector.resize(subTickIndex); - } - - // generate tick labels according to tick positions: - if (mAutoTickLabels) - { - int vecsize = mTickVector.size(); - mTickVectorLabels.resize(vecsize); - if (mTickLabelType == ltNumber) - { - for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) - mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision); - } else if (mTickLabelType == ltDateTime) - { - for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) - { -#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") - mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); -#else - mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); -#endif - } - } - } else // mAutoTickLabels == false - { - if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels - { - emit ticksRequest(); - } - // make sure provided tick label vector has correct (minimal) length: - if (mTickVectorLabels.size() < mTickVector.size()) - mTickVectorLabels.resize(mTickVector.size()); - } -} - -/*! \internal - - If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to - generate reasonable tick positions (and subtick count). The algorithm tries to create - approximately mAutoTickCount ticks (set via \ref setAutoTickCount). - - If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every - power of the current logarithm base, set via \ref setScaleLogBase. -*/ -void QCPAxis::generateAutoTicks() -{ - if (mScaleType == stLinear) - { - if (mAutoTickStep) - { - // Generate tick positions according to linear scaling: - mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers - double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. - double tickStepMantissa = mTickStep/magnitudeFactor; - if (tickStepMantissa < 5) - { - // round digit after decimal point to 0.5 - mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; - } else - { - // round to first digit in multiples of 2 - mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; - } - } - if (mAutoSubTicks) - mSubTickCount = calculateAutoSubTickCount(mTickStep); - // Generate tick positions according to mTickStep: - qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision - qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision - int tickcount = lastStep-firstStep+1; - if (tickcount < 0) tickcount = 0; - mTickVector.resize(tickcount); - for (int i=0; i 0 && mRange.upper > 0) // positive range - { - double lowerMag = basePow(qFloor(baseLog(mRange.lower))); - double currentMag = lowerMag; - mTickVector.clear(); - mTickVector.append(currentMag); - while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case - { - currentMag *= mScaleLogBase; - mTickVector.append(currentMag); - } - } else if (mRange.lower < 0 && mRange.upper < 0) // negative range - { - double lowerMag = -basePow(qCeil(baseLog(-mRange.lower))); - double currentMag = lowerMag; - mTickVector.clear(); - mTickVector.append(currentMag); - while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case - { - currentMag /= mScaleLogBase; - mTickVector.append(currentMag); - } - } else // invalid range for logarithmic scale, because lower and upper have different sign - { - mTickVector.clear(); - qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; - } - } -} - -/*! \internal - - Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a - tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For - Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, - because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note - that a subtick count of 4 means dividing the major tick step into 5 sections. - - This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps - with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no - fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is - returned. -*/ -int QCPAxis::calculateAutoSubTickCount(double tickStep) const -{ - int result = mSubTickCount; // default to current setting, if no proper value can be found - - // get mantissa of tickstep: - double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. - double tickStepMantissa = tickStep/magnitudeFactor; - - // separate integer and fractional part of mantissa: - double epsilon = 0.01; - double intPartf; - int intPart; - double fracPart = modf(tickStepMantissa, &intPartf); - intPart = intPartf; - - // handle cases with (almost) integer mantissa: - if (fracPart < epsilon || 1.0-fracPart < epsilon) - { - if (1.0-fracPart < epsilon) - ++intPart; - switch (intPart) - { - case 1: result = 4; break; // 1.0 -> 0.2 substep - case 2: result = 3; break; // 2.0 -> 0.5 substep - case 3: result = 2; break; // 3.0 -> 1.0 substep - case 4: result = 3; break; // 4.0 -> 1.0 substep - case 5: result = 4; break; // 5.0 -> 1.0 substep - case 6: result = 2; break; // 6.0 -> 2.0 substep - case 7: result = 6; break; // 7.0 -> 1.0 substep - case 8: result = 3; break; // 8.0 -> 2.0 substep - case 9: result = 2; break; // 9.0 -> 3.0 substep - } - } else - { - // handle cases with significantly fractional mantissa: - if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa - { - switch (intPart) - { - case 1: result = 2; break; // 1.5 -> 0.5 substep - case 2: result = 4; break; // 2.5 -> 0.5 substep - case 3: result = 4; break; // 3.5 -> 0.7 substep - case 4: result = 2; break; // 4.5 -> 1.5 substep - case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) - case 6: result = 4; break; // 6.5 -> 1.3 substep - case 7: result = 2; break; // 7.5 -> 2.5 substep - case 8: result = 4; break; // 8.5 -> 1.7 substep - case 9: result = 4; break; // 9.5 -> 1.9 substep - } - } - // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default - } - - return result; -} - -/* inherits documentation from base class */ -void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPAxis::deselectEvent(bool *selectionStateChanged) -{ - SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing axis lines. - - This is the antialiasing state the painter passed to the \ref draw method is in by default. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased -*/ -void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); -} - -/*! \internal - - Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. - -*/ -void QCPAxis::draw(QCPPainter *painter) -{ - const int lowTick = mLowestVisibleTick; - const int highTick = mHighestVisibleTick; - QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter - QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter - QVector tickLabels; // the final vector passed to QCPAxisPainter - tickPositions.reserve(highTick-lowTick+1); - tickLabels.reserve(highTick-lowTick+1); - subTickPositions.reserve(mSubTickVector.size()); - - if (mTicks) - { - for (int i=lowTick; i<=highTick; ++i) - { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(i)); - } - - if (mSubTickCount > 0) - { - const int subTickCount = mSubTickVector.size(); - for (int i=0; itype = mAxisType; - mAxisPainter->basePen = getBasePen(); - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->labelColor = getLabelColor(); - mAxisPainter->label = mLabel; - mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; - mAxisPainter->tickPen = getTickPen(); - mAxisPainter->subTickPen = getSubTickPen(); - mAxisPainter->tickLabelFont = getTickLabelFont(); - mAxisPainter->tickLabelColor = getTickLabelColor(); - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; - mAxisPainter->reversedEndings = mRangeReversed; - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - mAxisPainter->subTickPositions = subTickPositions; - mAxisPainter->draw(painter); -} - -/*! \internal - - Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in - the current range. The return values are indices of the tick vector, not the positions of the - ticks themselves. - - The actual use of this function is when an external tick vector is provided, since it might - exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of - subticks. - - If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be - smaller than lowIndex. There is one case, where this function returns indices that are not really - visible in the current axis range: When the tick spacing is larger than the axis range size and - one tick is below the axis range and the next tick is already above the axis range. Because in - such cases it is usually desirable to know the tick pair, to draw proper subticks. -*/ -void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const -{ - bool lowFound = false; - bool highFound = false; - lowIndex = 0; - highIndex = -1; - - for (int i=0; i < mTickVector.size(); ++i) - { - if (mTickVector.at(i) >= mRange.lower) - { - lowFound = true; - lowIndex = i; - break; - } - } - for (int i=mTickVector.size()-1; i >= 0; --i) - { - if (mTickVector.at(i) <= mRange.upper) - { - highFound = true; - highIndex = i; - break; - } - } - - if (!lowFound && highFound) - lowIndex = highIndex+1; - else if (lowFound && !highFound) - highIndex = lowIndex-1; -} - -/*! \internal - - A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic - scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. - This is set to 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. - - \see basePow, setScaleLogBase, setScaleType -*/ -double QCPAxis::baseLog(double value) const -{ - return qLn(value)*mScaleLogBaseLogInv; -} - -/*! \internal - - A power function with the base mScaleLogBase, used mostly for coordinate transforms in - logarithmic scales with arbitrary log base. - - \see baseLog, setScaleLogBase, setScaleType -*/ -double QCPAxis::basePow(double value) const -{ - return qPow(mScaleLogBase, value); -} - -/*! \internal - - Returns the pen that is used to draw the axis base line. Depending on the selection state, this - is either mSelectedBasePen or mBasePen. -*/ -QPen QCPAxis::getBasePen() const -{ - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; -} - -/*! \internal - - Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this - is either mSelectedTickPen or mTickPen. -*/ -QPen QCPAxis::getTickPen() const -{ - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; -} - -/*! \internal - - Returns the pen that is used to draw the subticks. Depending on the selection state, this - is either mSelectedSubTickPen or mSubTickPen. -*/ -QPen QCPAxis::getSubTickPen() const -{ - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; -} - -/*! \internal - - Returns the font that is used to draw the tick labels. Depending on the selection state, this - is either mSelectedTickLabelFont or mTickLabelFont. -*/ -QFont QCPAxis::getTickLabelFont() const -{ - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; -} - -/*! \internal - - Returns the font that is used to draw the axis label. Depending on the selection state, this - is either mSelectedLabelFont or mLabelFont. -*/ -QFont QCPAxis::getLabelFont() const -{ - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; -} - -/*! \internal - - Returns the color that is used to draw the tick labels. Depending on the selection state, this - is either mSelectedTickLabelColor or mTickLabelColor. -*/ -QColor QCPAxis::getTickLabelColor() const -{ - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; -} - -/*! \internal - - Returns the color that is used to draw the axis label. Depending on the selection state, this - is either mSelectedLabelColor or mLabelColor. -*/ -QColor QCPAxis::getLabelColor() const -{ - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; -} - -/*! \internal - - Returns the appropriate outward margin for this axis. It is needed if \ref - QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref - atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom - margin and so forth. For the calculation, this function goes through similar steps as \ref draw, - so changing one function likely requires the modification of the other one as well. - - The margin consists of the outward tick length, tick label padding, tick label size, label - padding, label size, and padding. - - The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. - unchanged are very fast. -*/ -int QCPAxis::calculateMargin() -{ - if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis - return 0; - - if (mCachedMarginValid) - return mCachedMargin; - - // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels - int margin = 0; - - int lowTick, highTick; - visibleTickBounds(lowTick, highTick); - QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter - QVector tickLabels; // the final vector passed to QCPAxisPainter - tickPositions.reserve(highTick-lowTick+1); - tickLabels.reserve(highTick-lowTick+1); - if (mTicks) - { - for (int i=lowTick; i<=highTick; ++i) - { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(i)); - } - } - // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. - // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters - mAxisPainter->type = mAxisType; - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->label = mLabel; - mAxisPainter->tickLabelFont = mTickLabelFont; - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - margin += mAxisPainter->size(); - margin += mPadding; - - mCachedMargin = margin; - mCachedMarginValid = true; - return margin; -} - -/* inherits documentation from base class */ -QCP::Interaction QCPAxis::selectionCategory() const -{ - return QCP::iSelectAxes; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAxisPainterPrivate -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAxisPainterPrivate - - \internal - \brief (Private) - - This is a private class and not part of the public QCustomPlot interface. - - It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and - axis label. It also buffers the labels to reduce replot times. The parameters are configured by - directly accessing the public member variables. -*/ - -/*! - Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every - redraw, to utilize the caching mechanisms. -*/ -QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : - type(QCPAxis::atLeft), - basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - lowerEnding(QCPLineEnding::esNone), - upperEnding(QCPLineEnding::esNone), - labelPadding(0), - tickLabelPadding(0), - tickLabelRotation(0), - tickLabelSide(QCPAxis::lsOutside), - substituteExponent(true), - numberMultiplyCross(false), - tickLengthIn(5), - tickLengthOut(0), - subTickLengthIn(2), - subTickLengthOut(0), - tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - offset(0), - abbreviateDecimalPowers(false), - reversedEndings(false), - mParentPlot(parentPlot), - mLabelCache(16) // cache at most 16 (tick) labels -{ -} - -QCPAxisPainterPrivate::~QCPAxisPainterPrivate() -{ -} - -/*! \internal - - Draws the axis with the specified \a painter. - - The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set - here, too. -*/ -void QCPAxisPainterPrivate::draw(QCPPainter *painter) -{ - QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) - { - mLabelCache.clear(); - mLabelParameterHash = newHash; - } - - QPoint origin; - switch (type) - { - case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; - case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; - case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; - case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; - } - - double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) - switch (type) - { - case QCPAxis::atTop: yCor = -1; break; - case QCPAxis::atRight: xCor = 1; break; - default: break; - } - int margin = 0; - // draw baseline: - QLineF baseLine; - painter->setPen(basePen); - if (QCPAxis::orientation(type) == Qt::Horizontal) - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); - else - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); - if (reversedEndings) - baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later - painter->drawLine(baseLine); - - // draw ticks: - if (!tickPositions.isEmpty()) - { - painter->setPen(tickPen); - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); - } - } - - // draw subticks: - if (!subTickPositions.isEmpty()) - { - painter->setPen(subTickPen); - // direction of ticks ("inward" is right for left axis and left for right axis) - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); - } - } - margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // draw axis base endings: - bool antialiasingBackup = painter->antialiasing(); - painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't - painter->setBrush(QBrush(basePen.color())); - QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); - if (lowerEnding.style() != QCPLineEnding::esNone) - lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); - if (upperEnding.style() != QCPLineEnding::esNone) - upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); - painter->setAntialiasing(antialiasingBackup); - - // tick labels: - QRect oldClipRect; - if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect - { - oldClipRect = painter->clipRegion().boundingRect(); - painter->setClipRect(axisRect); - } - QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label - if (!tickLabels.isEmpty()) - { - if (tickLabelSide == QCPAxis::lsOutside) - margin += tickLabelPadding; - painter->setFont(tickLabelFont); - painter->setPen(QPen(tickLabelColor)); - const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); - int distanceToAxis = margin; - if (tickLabelSide == QCPAxis::lsInside) - distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - for (int i=0; isetClipRect(oldClipRect); - - // axis label: - QRect labelBounds; - if (!label.isEmpty()) - { - margin += labelPadding; - painter->setFont(labelFont); - painter->setPen(QPen(labelColor)); - labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); - if (type == QCPAxis::atLeft) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); - painter->rotate(-90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); - } - else if (type == QCPAxis::atRight) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); - painter->rotate(90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); - } - else if (type == QCPAxis::atTop) - painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - else if (type == QCPAxis::atBottom) - painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - } - - // set selection boxes: - int selectionTolerance = 0; - if (mParentPlot) - selectionTolerance = mParentPlot->selectionTolerance(); - else - qDebug() << Q_FUNC_INFO << "mParentPlot is null"; - int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); - int selAxisInSize = selectionTolerance; - int selTickLabelSize; - int selTickLabelOffset; - if (tickLabelSide == QCPAxis::lsOutside) - { - selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; - } else - { - selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - } - int selLabelSize = labelBounds.height(); - int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; - if (type == QCPAxis::atLeft) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atRight) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atTop) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); - } else if (type == QCPAxis::atBottom) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); - } - mAxisSelectionBox = mAxisSelectionBox.normalized(); - mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); - mLabelSelectionBox = mLabelSelectionBox.normalized(); - // draw hitboxes for debug purposes: - //painter->setBrush(Qt::NoBrush); - //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); -} - -/*! \internal - - Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone - direction) needed to fit the axis. -*/ -int QCPAxisPainterPrivate::size() const -{ - int result = 0; - - // get length of tick marks pointing outwards: - if (!tickPositions.isEmpty()) - result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // calculate size of tick labels: - if (tickLabelSide == QCPAxis::lsOutside) - { - QSize tickLabelsSize(0, 0); - if (!tickLabels.isEmpty()) - { - for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled - { - CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache - if (!cachedLabel) // no cached label existed, create it - { - cachedLabel = new CachedLabel; - TickLabelData labelData = getTickLabelData(painter->font(), text); - cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); - cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - cachedLabel->pixmap.fill(Qt::transparent); - QCPPainter cachePainter(&cachedLabel->pixmap); - cachePainter.setPen(painter->pen()); - drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); - } - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); - else - labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); - } - if (!labelClippedByBorder) - { - painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); - finalSize = cachedLabel->pixmap.size(); - } - mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created - } else // label caching disabled, draw text directly on surface: - { - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); - else - labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); - } - if (!labelClippedByBorder) - { - drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); - finalSize = labelData.rotatedTotalBounds.size(); - } - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); -} - -/*! \internal - - This is a \ref placeTickLabel helper function. - - Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a - y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to - directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when - QCP::phCacheLabels plotting hint is not set. -*/ -void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const -{ - // backup painter settings that we're about to change: - QTransform oldTransform = painter->transform(); - QFont oldFont = painter->font(); - - // transform painter to position/rotation: - painter->translate(x, y); - if (!qFuzzyIsNull(tickLabelRotation)) - painter->rotate(tickLabelRotation); - - // draw text: - if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); - painter->setFont(labelData.expFont); - painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); - } else - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); - } - - // reset painter settings to what it was before: - painter->setTransform(oldTransform); - painter->setFont(oldFont); -} - -/*! \internal - - This is a \ref placeTickLabel helper function. - - Transforms the passed \a text and \a font to a tickLabelData structure that can then be further - processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and - exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. -*/ -QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const -{ - TickLabelData result; - - // determine whether beautiful decimal powers should be used - bool useBeautifulPowers = false; - int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart - int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart - if (substituteExponent) - { - ePos = text.indexOf(QLatin1Char('e')); - if (ePos > 0 && text.at(ePos-1).isDigit()) - { - eLast = ePos; - while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit())) - ++eLast; - if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power - useBeautifulPowers = true; - } - } - - // calculate text bounding rects and do string preparation for beautiful decimal powers: - result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line - result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding - if (useBeautifulPowers) - { - // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: - result.basePart = text.left(ePos); - // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: - if (abbreviateDecimalPowers && result.basePart == QLatin1String("1")) - result.basePart = QLatin1String("10"); - else - result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10"); - result.expPart = text.mid(ePos+1); - // clip "+" and leading zeros off expPart: - while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e' - result.expPart.remove(1, 1); - if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) - result.expPart.remove(0, 1); - // prepare smaller font for exponent: - result.expFont = font; - if (result.expFont.pointSize() > 0) - result.expFont.setPointSize(result.expFont.pointSize()*0.75); - else - result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); - // calculate bounding rects of base part, exponent part and total one: - result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); - result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); - result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA - } else // useBeautifulPowers == false - { - result.basePart = text; - result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); - } - result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler - - // calculate possibly different bounding rect after rotation: - result.rotatedTotalBounds = result.totalBounds; - if (!qFuzzyIsNull(tickLabelRotation)) - { - QTransform transform; - transform.rotate(tickLabelRotation); - result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); - } - - return result; -} - -/*! \internal - - This is a \ref placeTickLabel helper function. - - Calculates the offset at which the top left corner of the specified tick label shall be drawn. - The offset is relative to a point right next to the tick the label belongs to. - - This function is thus responsible for e.g. centering tick labels under ticks and positioning them - appropriately when they are rotated. -*/ -QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const -{ - /* - calculate label offset from base point at tick (non-trivial, for best visual appearance): short - explanation for bottom axis: The anchor, i.e. the point in the label that is placed - horizontally under the corresponding tick is always on the label side that is closer to the - axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height - is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text - will be centered under the tick (i.e. displaced horizontally by half its height). At the same - time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick - labels. - */ - bool doRotation = !qFuzzyIsNull(tickLabelRotation); - bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. - double radians = tickLabelRotation/180.0*M_PI; - int x=0, y=0; - if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); - y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = -labelData.totalBounds.width(); - y = -labelData.totalBounds.height()/2.0; - } - } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = 0; - y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = 0; - y = -labelData.totalBounds.height()/2.0; - } - } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; - y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); - } else - { - x = -qSin(-radians)*labelData.totalBounds.height()/2.0; - y = -qCos(-radians)*labelData.totalBounds.height(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = -labelData.totalBounds.height(); - } - } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height()/2.0; - y = 0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; - y = +qSin(-radians)*labelData.totalBounds.width(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = 0; - } - } - - return QPointF(x, y); -} - -/*! \internal - - Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label - to be drawn, depending on number format etc. Since only the largest tick label is wanted for the - margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a - smaller width/height. -*/ -void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const -{ - // note: this function must return the same tick label sizes as the placeTickLabel function. - QSize finalSize; - if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label - { - const CachedLabel *cachedLabel = mLabelCache.object(text); - finalSize = cachedLabel->pixmap.size(); - } else // label caching disabled or no label with this text cached: - { - TickLabelData labelData = getTickLabelData(font, text); - finalSize = labelData.rotatedTotalBounds.size(); - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAbstractPlottable -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAbstractPlottable - \brief The abstract base class for all data representing objects in a plot. - - It defines a very basic interface like name, pen, brush, visibility etc. Since this class is - abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to - create new ways of displaying data (see "Creating own plottables" below). - - All further specifics are in the subclasses, for example: - \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph - (typically created with \ref QCustomPlot::addGraph) - \li A parametric curve: \ref QCPCurve - \li A bar chart: \ref QCPBars - \li A statistical box plot: \ref QCPStatisticalBox - \li A color encoded two-dimensional map: \ref QCPColorMap - \li An OHLC/Candlestick chart: \ref QCPFinancial - - \section plottables-subclassing Creating own plottables - - To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure - virtual functions, you must implement: - \li \ref clearData - \li \ref selectTest - \li \ref draw - \li \ref drawLegendIcon - \li \ref getKeyRange - \li \ref getValueRange - - See the documentation of those functions for what they need to do. - - For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot - coordinates to pixel coordinates. This function is quite convenient, because it takes the - orientation of the key and value axes into account for you (x and y are swapped when the key axis - is vertical and the value axis horizontal). If you are worried about performance (i.e. you need - to translate many points in a loop like QCPGraph), you can directly use \ref - QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis - yourself. - - Here are some important members you inherit from QCPAbstractPlottable: - - - - - - - - - - - - - - - - - - - - - - - - - - -
QCustomPlot *\b mParentPlotA pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
QString \b mNameThe name of the plottable.
QPen \b mPenThe generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
QPen \b mSelectedPenThe generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).
QBrush \b mBrushThe generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
QBrush \b mSelectedBrushThe generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).
QPointer\b mKeyAxis, \b mValueAxisThe key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. - Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.
bool \b mSelectedindicates whether the plottable is selected or not.
-*/ - -/* start of documentation of pure virtual functions */ - -/*! \fn void QCPAbstractPlottable::clearData() = 0 - Clears all data in the plottable. -*/ - -/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 - \internal - - called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation - of this plottable inside \a rect, next to the plottable name. - - The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't - appear outside the legend icon border. -*/ - -/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 - \internal - - called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can - set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the - returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain - to \ref sdNegative and all positive points will be ignored for range calculation. For no - restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output - parameter that indicates whether a range could be found or not. If this is false, you shouldn't - use the returned range (e.g. no points in data). - - Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by - this function may have size zero, which wouldn't count as a valid range. - - \see rescaleAxes, getValueRange -*/ - -/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 - \internal - - called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can - set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the - returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain - to \ref sdNegative and all positive points will be ignored for range calculation. For no - restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output - parameter that indicates whether a range could be found or not. If this is false, you shouldn't - use the returned range (e.g. no points in data). - - Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by - this function may have size zero, which wouldn't count as a valid range. - - \see rescaleAxes, getKeyRange -*/ - -/* end of documentation of pure virtual functions */ -/* start of documentation of signals */ - -/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) - - This signal is emitted when the selection state of this plottable has changed, either by user - interaction or by a direct call to \ref setSelected. -*/ - -/*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); - - This signal is emitted when the selectability of this plottable has changed. - - \see setSelectable -*/ - -/* end of documentation of signals */ - -/*! - Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as - its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance - and have perpendicular orientations. If either of these restrictions is violated, a corresponding - message is printed to the debug output (qDebug), the construction is not aborted, though. - - Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, - it can't be directly instantiated. - - You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. -*/ -QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), - mName(), - mAntialiasedFill(true), - mAntialiasedScatters(true), - mAntialiasedErrorBars(false), - mPen(Qt::black), - mSelectedPen(Qt::black), - mBrush(Qt::NoBrush), - mSelectedBrush(Qt::NoBrush), - mKeyAxis(keyAxis), - mValueAxis(valueAxis), - mSelectable(true), - mSelected(false) -{ - if (keyAxis->parentPlot() != valueAxis->parentPlot()) - qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; - if (keyAxis->orientation() == valueAxis->orientation()) - qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; -} - -/*! - The name is the textual representation of this plottable as it is displayed in the legend - (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. -*/ -void QCPAbstractPlottable::setName(const QString &name) -{ - mName = name; -} - -/*! - Sets whether fills of this plottable are drawn antialiased or not. - - Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. -*/ -void QCPAbstractPlottable::setAntialiasedFill(bool enabled) -{ - mAntialiasedFill = enabled; -} - -/*! - Sets whether the scatter symbols of this plottable are drawn antialiased or not. - - Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. -*/ -void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) -{ - mAntialiasedScatters = enabled; -} - -/*! - Sets whether the error bars of this plottable are drawn antialiased or not. - - Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. -*/ -void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) -{ - mAntialiasedErrorBars = enabled; -} - - -/*! - The pen is used to draw basic lines that make up the plottable representation in the - plot. - - For example, the \ref QCPGraph subclass draws its graph lines with this pen. - - \see setBrush -*/ -void QCPAbstractPlottable::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - When the plottable is selected, this pen is used to draw basic lines instead of the normal - pen set via \ref setPen. - - \see setSelected, setSelectable, setSelectedBrush, selectTest -*/ -void QCPAbstractPlottable::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - The brush is used to draw basic fills of the plottable representation in the - plot. The Fill can be a color, gradient or texture, see the usage of QBrush. - - For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when - it's not set to Qt::NoBrush. - - \see setPen -*/ -void QCPAbstractPlottable::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - When the plottable is selected, this brush is used to draw fills instead of the normal - brush set via \ref setBrush. - - \see setSelected, setSelectable, setSelectedPen, selectTest -*/ -void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/*! - The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal - to the plottable's value axis. This function performs no checks to make sure this is the case. - The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the - y-axis (QCustomPlot::yAxis) as value axis. - - Normally, the key and value axes are set in the constructor of the plottable (or \ref - QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - - \see setValueAxis -*/ -void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) -{ - mKeyAxis = axis; -} - -/*! - The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is - orthogonal to the plottable's key axis. This function performs no checks to make sure this is the - case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and - the y-axis (QCustomPlot::yAxis) as value axis. - - Normally, the key and value axes are set in the constructor of the plottable (or \ref - QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - - \see setKeyAxis -*/ -void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) -{ - mValueAxis = axis; -} - -/*! - Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. - (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) - - However, even when \a selectable was set to false, it is possible to set the selection manually, - by calling \ref setSelected directly. - - \see setSelected -*/ -void QCPAbstractPlottable::setSelectable(bool selectable) -{ - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } -} - -/*! - Sets whether this plottable is selected or not. When selected, it uses a different pen and brush - to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. - - The entire selection mechanism for plottables is handled automatically when \ref - QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when - you wish to change the selection state manually. - - This function can change the selection state even when \ref setSelectable was set to false. - - emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - - \see setSelectable, selectTest -*/ -void QCPAbstractPlottable::setSelected(bool selected) -{ - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } -} - -/*! - Rescales the key and value axes associated with this plottable to contain all displayed data, so - the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make - sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. - Instead it will stay in the current sign domain and ignore all parts of the plottable that lie - outside of that domain. - - \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show - multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has - \a onlyEnlarge set to false (the default), and all subsequent set to true. - - \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale -*/ -void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const -{ - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); -} - -/*! - Rescales the key axis of the plottable so the whole plottable is visible. - - See \ref rescaleAxes for detailed behaviour. -*/ -void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - SignDomain signDomain = sdBoth; - if (keyAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(keyAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (keyAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-keyAxis->range().size()/2.0; - newRange.upper = center+keyAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); - newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); - } - } - keyAxis->setRange(newRange); - } -} - -/*! - Rescales the value axis of the plottable so the whole plottable is visible. - - Returns true if the axis was actually scaled. This might not be the case if this plottable has an - invalid range, e.g. because it has no data points. - - See \ref rescaleAxes for detailed behaviour. -*/ -void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const -{ - QCPAxis *valueAxis = mValueAxis.data(); - if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } - - SignDomain signDomain = sdBoth; - if (valueAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); - - bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(valueAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-valueAxis->range().size()/2.0; - newRange.upper = center+valueAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); - newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); - } - } - valueAxis->setRange(newRange); - } -} - -/*! - Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). - - Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable - needs a more specialized representation in the legend, this function will take this into account - and instead create the specialized subclass of QCPAbstractLegendItem. - - Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in - the legend. - - \see removeFromLegend, QCPLegend::addItem -*/ -bool QCPAbstractPlottable::addToLegend() -{ - if (!mParentPlot || !mParentPlot->legend) - return false; - - if (!mParentPlot->legend->hasItemWithPlottable(this)) - { - mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); - return true; - } else - return false; -} - -/*! - Removes the plottable from the legend of the parent QCustomPlot. This means the - QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable - is removed. - - Returns true on success, i.e. if the legend exists and a legend item associated with this - plottable was found and removed. - - \see addToLegend, QCPLegend::removeItem -*/ -bool QCPAbstractPlottable::removeFromLegend() const -{ - if (!mParentPlot->legend) - return false; - - if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) - return mParentPlot->legend->removeItem(lip); - else - return false; -} - -/* inherits documentation from base class */ -QRect QCPAbstractPlottable::clipRect() const -{ - if (mKeyAxis && mValueAxis) - return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); - else - return QRect(); -} - -/* inherits documentation from base class */ -QCP::Interaction QCPAbstractPlottable::selectionCategory() const -{ - return QCP::iSelectPlottables; -} - -/*! \internal - - Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, - taking the orientations of the axes associated with this plottable into account (e.g. whether key - represents x or y). - - \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. - - \see pixelsToCoords, QCPAxis::coordToPixel -*/ -void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - x = keyAxis->coordToPixel(key); - y = valueAxis->coordToPixel(value); - } else - { - y = keyAxis->coordToPixel(key); - x = valueAxis->coordToPixel(value); - } -} - -/*! \internal - \overload - - Returns the input as pixel coordinates in a QPointF. -*/ -const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - if (keyAxis->orientation() == Qt::Horizontal) - return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); - else - return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); -} - -/*! \internal - - Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, - taking the orientations of the axes associated with this plottable into account (e.g. whether key - represents x or y). - - \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. - - \see coordsToPixels, QCPAxis::coordToPixel -*/ -void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - key = keyAxis->pixelToCoord(x); - value = valueAxis->pixelToCoord(y); - } else - { - key = keyAxis->pixelToCoord(y); - value = valueAxis->pixelToCoord(x); - } -} - -/*! \internal - \overload - - Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. -*/ -void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const -{ - pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); -} - -/*! \internal - - Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the - graph is not selected and mSelectedPen when it is. -*/ -QPen QCPAbstractPlottable::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \internal - - Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the - graph is not selected and mSelectedBrush when it is. -*/ -QBrush QCPAbstractPlottable::mainBrush() const -{ - return mSelected ? mSelectedBrush : mBrush; -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing plottable lines. - - This is the antialiasing state the painter passed to the \ref draw method is in by default. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint -*/ -void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing plottable fills. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint -*/ -void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing plottable scatter points. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint -*/ -void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing plottable error bars. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint -*/ -void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); -} - -/*! \internal - - Finds the shortest squared distance of \a point to the line segment defined by \a start and \a - end. - - This function may be used to help with the implementation of the \ref selectTest function for - specific plottables. - - \note This function is identical to QCPAbstractItem::distSqrToLine -*/ -double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const -{ - QVector2D a(start); - QVector2D b(end); - QVector2D p(point); - QVector2D v(b-a); - - double vLengthSqr = v.lengthSquared(); - if (!qFuzzyIsNull(vLengthSqr)) - { - double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; - if (mu < 0) - return (a-p).lengthSquared(); - else if (mu > 1) - return (b-p).lengthSquared(); - else - return ((a + mu*v)-p).lengthSquared(); - } else - return (a-p).lengthSquared(); -} - -/* inherits documentation from base class */ -void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) -{ - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemAnchor -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemAnchor - \brief An anchor of an item to which positions can be attached to. - - An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't - control anything on its item, but provides a way to tie other items via their positions to the - anchor. - - For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. - Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can - attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by - calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the - QCPItemRect. This way the start of the line will now always follow the respective anchor location - on the rect item. - - Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an - anchor to other positions. - - To learn how to provide anchors in your own item subclasses, see the subclassing section of the - QCPAbstractItem documentation. -*/ - -/* start documentation of inline functions */ - -/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() - - Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if - it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). - - This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids - dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with - gcc compiler). -*/ - -/* end documentation of inline functions */ - -/*! - Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if - you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as - explained in the subclassing section of the QCPAbstractItem documentation. -*/ -QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : - mName(name), - mParentPlot(parentPlot), - mParentItem(parentItem), - mAnchorId(anchorId) -{ -} - -QCPItemAnchor::~QCPItemAnchor() -{ - // unregister as parent at children: - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } -} - -/*! - Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. - - The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the - parent item, QCPItemAnchor is just an intermediary. -*/ -QPointF QCPItemAnchor::pixelPoint() const -{ - if (mParentItem) - { - if (mAnchorId > -1) - { - return mParentItem->anchorPixelPoint(mAnchorId); - } else - { - qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; - return QPointF(); - } - } else - { - qDebug() << Q_FUNC_INFO << "no parent item set"; - return QPointF(); - } -} - -/*! \internal - - Adds \a pos to the childX list of this anchor, which keeps track of which children use this - anchor as parent anchor for the respective coordinate. This is necessary to notify the children - prior to destruction of the anchor. - - Note that this function does not change the parent setting in \a pos. -*/ -void QCPItemAnchor::addChildX(QCPItemPosition *pos) -{ - if (!mChildrenX.contains(pos)) - mChildrenX.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); -} - -/*! \internal - - Removes \a pos from the childX list of this anchor. - - Note that this function does not change the parent setting in \a pos. -*/ -void QCPItemAnchor::removeChildX(QCPItemPosition *pos) -{ - if (!mChildrenX.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); -} - -/*! \internal - - Adds \a pos to the childY list of this anchor, which keeps track of which children use this - anchor as parent anchor for the respective coordinate. This is necessary to notify the children - prior to destruction of the anchor. - - Note that this function does not change the parent setting in \a pos. -*/ -void QCPItemAnchor::addChildY(QCPItemPosition *pos) -{ - if (!mChildrenY.contains(pos)) - mChildrenY.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); -} - -/*! \internal - - Removes \a pos from the childY list of this anchor. - - Note that this function does not change the parent setting in \a pos. -*/ -void QCPItemAnchor::removeChildY(QCPItemPosition *pos) -{ - if (!mChildrenY.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemPosition -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemPosition - \brief Manages the position of an item. - - Every item has at least one public QCPItemPosition member pointer which provides ways to position the - item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: - \a topLeft and \a bottomRight. - - QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type - defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel - coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also - possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref - setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y - direction, while following a plot coordinate in the X direction. - - A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie - multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords) - are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0) - means directly ontop of the parent anchor. For example, You could attach the \a start position of - a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line - always be centered under the text label, no matter where the text is moved to. For more advanced - plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see - \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X - direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B - in Y. - - Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent - anchor for other positions. - - To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This - works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref - setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified - pixel values. -*/ - -/* start documentation of inline functions */ - -/*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const - - Returns the current position type. - - If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the - type of the X coordinate. In that case rather use \a typeX() and \a typeY(). - - \see setType -*/ - -/*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const - - Returns the current parent anchor. - - If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), - this method returns the parent anchor of the Y coordinate. In that case rather use \a - parentAnchorX() and \a parentAnchorY(). - - \see setParentAnchor -*/ - -/* end documentation of inline functions */ - -/*! - Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if - you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as - explained in the subclassing section of the QCPAbstractItem documentation. -*/ -QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : - QCPItemAnchor(parentPlot, parentItem, name), - mPositionTypeX(ptAbsolute), - mPositionTypeY(ptAbsolute), - mKey(0), - mValue(0), - mParentAnchorX(0), - mParentAnchorY(0) -{ -} - -QCPItemPosition::~QCPItemPosition() -{ - // unregister as parent at children: - // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then - // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } - // unregister as child in parent: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); -} - -/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ -QCPAxisRect *QCPItemPosition::axisRect() const -{ - return mAxisRect.data(); -} - -/*! - Sets the type of the position. The type defines how the coordinates passed to \ref setCoords - should be handled and how the QCPItemPosition should behave in the plot. - - The possible values for \a type can be separated in two main categories: - - \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords - and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. - By default, the QCustomPlot's x- and yAxis are used. - - \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This - corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref - ptAxisRectRatio. They differ only in the way the absolute position is described, see the - documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify - the axis rect with \ref setAxisRect. By default this is set to the main axis rect. - - Note that the position type \ref ptPlotCoords is only available (and sensible) when the position - has no parent anchor (\ref setParentAnchor). - - If the type is changed, the apparent pixel position on the plot is preserved. This means - the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. - - This method sets the type for both X and Y directions. It is also possible to set different types - for X and Y, see \ref setTypeX, \ref setTypeY. -*/ -void QCPItemPosition::setType(QCPItemPosition::PositionType type) -{ - setTypeX(type); - setTypeY(type); -} - -/*! - This method sets the position type of the X coordinate to \a type. - - For a detailed description of what a position type is, see the documentation of \ref setType. - - \see setType, setTypeY -*/ -void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type) -{ - if (mPositionTypeX != type) - { - // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect - // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPoint(); - - mPositionTypeX = type; - - if (retainPixelPosition) - setPixelPoint(pixel); - } -} - -/*! - This method sets the position type of the Y coordinate to \a type. - - For a detailed description of what a position type is, see the documentation of \ref setType. - - \see setType, setTypeX -*/ -void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) -{ - if (mPositionTypeY != type) - { - // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect - // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPoint(); - - mPositionTypeY = type; - - if (retainPixelPosition) - setPixelPoint(pixel); - } -} - -/*! - Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now - follow any position changes of the anchor. The local coordinate system of positions with a parent - anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence - the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) - - if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved - during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position - will be exactly on top of the parent anchor. - - To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. - - If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is - set to \ref ptAbsolute, to keep the position in a valid state. - - This method sets the parent anchor for both X and Y directions. It is also possible to set - different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. -*/ -bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) -{ - bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); - bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); - return successX && successY; -} - -/*! - This method sets the parent anchor of the X coordinate to \a parentAnchor. - - For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - - \see setParentAnchor, setParentAnchorY -*/ -bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) -{ - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); - return false; - } - currentParent = currentParentPos->parentAnchorX(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; - } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) - setTypeX(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPoint(); - // unregister at current parent anchor: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildX(this); - mParentAnchorX = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPoint(pixelP); - else - setCoords(0, coords().y()); - return true; -} - -/*! - This method sets the parent anchor of the Y coordinate to \a parentAnchor. - - For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - - \see setParentAnchor, setParentAnchorX -*/ -bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) -{ - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); - return false; - } - currentParent = currentParentPos->parentAnchorY(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; - } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) - setTypeY(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPoint(); - // unregister at current parent anchor: - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildY(this); - mParentAnchorY = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPoint(pixelP); - else - setCoords(coords().x(), 0); - return true; -} - -/*! - Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type - (\ref setType, \ref setTypeX, \ref setTypeY). - - For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position - on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the - QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the - plot coordinate system defined by the axes set by \ref setAxes. By default those are the - QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available - coordinate types and their meaning. - - If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a - value must also be provided in the different coordinate systems. Here, the X type refers to \a - key, and the Y type refers to \a value. - - \see setPixelPoint -*/ -void QCPItemPosition::setCoords(double key, double value) -{ - mKey = key; - mValue = value; -} - -/*! \overload - - Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the - meaning of \a value of the \ref setCoords(double key, double value) method. -*/ -void QCPItemPosition::setCoords(const QPointF &pos) -{ - setCoords(pos.x(), pos.y()); -} - -/*! - Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It - includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). - - \see setPixelPoint -*/ -QPointF QCPItemPosition::pixelPoint() const -{ - QPointF result; - - // determine X: - switch (mPositionTypeX) - { - case ptAbsolute: - { - result.rx() = mKey; - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - break; - } - case ptViewportRatio: - { - result.rx() = mKey*mParentPlot->viewport().width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - else - result.rx() += mParentPlot->viewport().left(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.rx() = mKey*mAxisRect.data()->width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - else - result.rx() += mAxisRect.data()->left(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - // determine Y: - switch (mPositionTypeY) - { - case ptAbsolute: - { - result.ry() = mValue; - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - break; - } - case ptViewportRatio: - { - result.ry() = mValue*mParentPlot->viewport().height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - else - result.ry() += mParentPlot->viewport().top(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.ry() = mValue*mAxisRect.data()->height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - else - result.ry() += mAxisRect.data()->top(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - result.ry() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - result.ry() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - return result; -} - -/*! - When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the - coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and - yAxis of the QCustomPlot. -*/ -void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) -{ - mKeyAxis = keyAxis; - mValueAxis = valueAxis; -} - -/*! - When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the - coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of - the QCustomPlot. -*/ -void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) -{ - mAxisRect = axisRect; -} - -/*! - Sets the apparent pixel position. This works no matter what type (\ref setType) this - QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed - appropriately, to make the position finally appear at the specified pixel values. - - Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is - identical to that of \ref setCoords. - - \see pixelPoint, setCoords -*/ -void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) -{ - double x = pixelPoint.x(); - double y = pixelPoint.y(); - - switch (mPositionTypeX) - { - case ptAbsolute: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - break; - } - case ptViewportRatio: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - else - x -= mParentPlot->viewport().left(); - x /= (double)mParentPlot->viewport().width(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - else - x -= mAxisRect.data()->left(); - x /= (double)mAxisRect.data()->width(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - x = mKeyAxis.data()->pixelToCoord(x); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - y = mValueAxis.data()->pixelToCoord(x); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - switch (mPositionTypeY) - { - case ptAbsolute: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - break; - } - case ptViewportRatio: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - else - y -= mParentPlot->viewport().top(); - y /= (double)mParentPlot->viewport().height(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - else - y -= mAxisRect.data()->top(); - y /= (double)mAxisRect.data()->height(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - x = mKeyAxis.data()->pixelToCoord(y); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - y = mValueAxis.data()->pixelToCoord(y); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - setCoords(x, y); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAbstractItem -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAbstractItem - \brief The abstract base class for all items in a plot. - - In QCustomPlot, items are supplemental graphical elements that are neither plottables - (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus - plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each - specific item has at least one QCPItemPosition member which controls the positioning. Some items - are defined by more than one coordinate and thus have two or more QCPItemPosition members (For - example, QCPItemRect has \a topLeft and \a bottomRight). - - This abstract base class defines a very basic interface like visibility and clipping. Since this - class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass - yourself to create new items. - - The built-in items are: - - - - - - - - - - -
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
QCPItemRectA rectangle
QCPItemEllipseAn ellipse
QCPItemPixmapAn arbitrary pixmap
QCPItemTextA text label
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
- - \section items-clipping Clipping - - Items are by default clipped to the main axis rect (they are only visible inside the axis rect). - To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect - "setClipToAxisRect(false)". - - On the other hand if you want the item to be clipped to a different axis rect, specify it via - \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and - in principle is independent of the coordinate axes the item might be tied to via its position - members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping - also contains the axes used for the item positions. - - \section items-using Using items - - First you instantiate the item you want to use and add it to the plot: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 - by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just - set the plot coordinates where the line should start/end: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2 - If we don't want the line to be positioned in plot coordinates but a different coordinate system, - e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3 - Then we can set the coordinates, this time in pixels: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 - and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 - - For more advanced plots, it is even possible to set different types and parent anchors per X/Y - coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref - QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. - - \section items-subclassing Creating own items - - To create an own item, you implement a subclass of QCPAbstractItem. These are the pure - virtual functions, you must implement: - \li \ref selectTest - \li \ref draw - - See the documentation of those functions for what they need to do. - - \subsection items-positioning Allowing the item to be positioned - - As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall - have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add - a public member of type QCPItemPosition like so: - - \code QCPItemPosition * const myPosition;\endcode - - the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition - instance it points to, can be modified, of course). - The initialization of this pointer is made easy with the \ref createPosition function. Just assign - the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition - takes a string which is the name of the position, typically this is identical to the variable name. - For example, the constructor of QCPItemExample could look like this: - - \code - QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - myPosition(createPosition("myPosition")) - { - // other constructor code - } - \endcode - - \subsection items-drawing The draw function - - To give your item a visual representation, reimplement the \ref draw function and use the passed - QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the - position member(s) via \ref QCPItemPosition::pixelPoint. - - To optimize performance you should calculate a bounding rect first (don't forget to take the pen - width into account), check whether it intersects the \ref clipRect, and only draw the item at all - if this is the case. - - \subsection items-selection The selectTest function - - Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and - \ref rectSelectTest. With these, the implementation of the selection test becomes significantly - simpler for most items. See the documentation of \ref selectTest for what the function parameters - mean and what the function should return. - - \subsection anchors Providing anchors - - Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public - member, e.g. - - \code QCPItemAnchor * const bottom;\endcode - - and create it in the constructor with the \ref createAnchor function, assigning it a name and an - anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). - Since anchors can be placed anywhere, relative to the item's position(s), your item needs to - provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int - anchorId) function. - - In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel - position when anything attached to the anchor needs to know the coordinates. -*/ - -/* start of documentation of inline functions */ - -/*! \fn QList QCPAbstractItem::positions() const - - Returns all positions of the item in a list. - - \see anchors, position -*/ - -/*! \fn QList QCPAbstractItem::anchors() const - - Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always - also an anchor, the list will also contain the positions of this item. - - \see positions, anchor -*/ - -/* end of documentation of inline functions */ -/* start documentation of pure virtual functions */ - -/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 - \internal - - Draws this item with the provided \a painter. - - The cliprect of the provided painter is set to the rect returned by \ref clipRect before this - function is called. The clipRect depends on the clipping settings defined by \ref - setClipToAxisRect and \ref setClipAxisRect. -*/ - -/* end documentation of pure virtual functions */ -/* start documentation of signals */ - -/*! \fn void QCPAbstractItem::selectionChanged(bool selected) - This signal is emitted when the selection state of this item has changed, either by user interaction - or by a direct call to \ref setSelected. -*/ - -/* end documentation of signals */ - -/*! - Base class constructor which initializes base class members. -*/ -QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), - mClipToAxisRect(false), - mSelectable(true), - mSelected(false) -{ - QList rects = parentPlot->axisRects(); - if (rects.size() > 0) - { - setClipToAxisRect(true); - setClipAxisRect(rects.first()); - } -} - -QCPAbstractItem::~QCPAbstractItem() -{ - // don't delete mPositions because every position is also an anchor and thus in mAnchors - qDeleteAll(mAnchors); -} - -/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ -QCPAxisRect *QCPAbstractItem::clipAxisRect() const -{ - return mClipAxisRect.data(); -} - -/*! - Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the - entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. - - \see setClipAxisRect -*/ -void QCPAbstractItem::setClipToAxisRect(bool clip) -{ - mClipToAxisRect = clip; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); -} - -/*! - Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref - setClipToAxisRect is set to true. - - \see setClipToAxisRect -*/ -void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) -{ - mClipAxisRect = rect; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); -} - -/*! - Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. - (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) - - However, even when \a selectable was set to false, it is possible to set the selection manually, - by calling \ref setSelected. - - \see QCustomPlot::setInteractions, setSelected -*/ -void QCPAbstractItem::setSelectable(bool selectable) -{ - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } -} - -/*! - Sets whether this item is selected or not. When selected, it might use a different visual - appearance (e.g. pen and brush), this depends on the specific item though. - - The entire selection mechanism for items is handled automatically when \ref - QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this - function when you wish to change the selection state manually. - - This function can change the selection state even when \ref setSelectable was set to false. - - emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - - \see setSelectable, selectTest -*/ -void QCPAbstractItem::setSelected(bool selected) -{ - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } -} - -/*! - Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by - that name, returns 0. - - This function provides an alternative way to access item positions. Normally, you access - positions direcly by their member pointers (which typically have the same variable name as \a - name). - - \see positions, anchor -*/ -QCPItemPosition *QCPAbstractItem::position(const QString &name) const -{ - for (int i=0; iname() == name) - return mPositions.at(i); - } - qDebug() << Q_FUNC_INFO << "position with name not found:" << name; - return 0; -} - -/*! - Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by - that name, returns 0. - - This function provides an alternative way to access item anchors. Normally, you access - anchors direcly by their member pointers (which typically have the same variable name as \a - name). - - \see anchors, position -*/ -QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const -{ - for (int i=0; iname() == name) - return mAnchors.at(i); - } - qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; - return 0; -} - -/*! - Returns whether this item has an anchor with the specified \a name. - - Note that you can check for positions with this function, too. This is because every position is - also an anchor (QCPItemPosition inherits from QCPItemAnchor). - - \see anchor, position -*/ -bool QCPAbstractItem::hasAnchor(const QString &name) const -{ - for (int i=0; iname() == name) - return true; - } - return false; -} - -/*! \internal - - Returns the rect the visual representation of this item is clipped to. This depends on the - current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. - - If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. - - \see draw -*/ -QRect QCPAbstractItem::clipRect() const -{ - if (mClipToAxisRect && mClipAxisRect) - return mClipAxisRect.data()->rect(); - else - return mParentPlot->viewport(); -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing item lines. - - This is the antialiasing state the painter passed to the \ref draw method is in by default. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased -*/ -void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); -} - -/*! \internal - - Finds the shortest squared distance of \a point to the line segment defined by \a start and \a - end. - - This function may be used to help with the implementation of the \ref selectTest function for - specific items. - - \note This function is identical to QCPAbstractPlottable::distSqrToLine - - \see rectSelectTest -*/ -double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const -{ - QVector2D a(start); - QVector2D b(end); - QVector2D p(point); - QVector2D v(b-a); - - double vLengthSqr = v.lengthSquared(); - if (!qFuzzyIsNull(vLengthSqr)) - { - double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; - if (mu < 0) - return (a-p).lengthSquared(); - else if (mu > 1) - return (b-p).lengthSquared(); - else - return ((a + mu*v)-p).lengthSquared(); - } else - return (a-p).lengthSquared(); -} - -/*! \internal - - A convenience function which returns the selectTest value for a specified \a rect and a specified - click position \a pos. \a filledRect defines whether a click inside the rect should also be - considered a hit or whether only the rect border is sensitive to hits. - - This function may be used to help with the implementation of the \ref selectTest function for - specific items. - - For example, if your item consists of four rects, call this function four times, once for each - rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned - values. - - \see distSqrToLine -*/ -double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const -{ - double result = -1; - - // distance to border: - QList lines; - lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) - << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); - double minDistSqr = std::numeric_limits::max(); - for (int i=0; i mParentPlot->selectionTolerance()*0.99) - { - if (rect.contains(pos)) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; -} - -/*! \internal - - Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in - item subclasses if they want to provide anchors (QCPItemAnchor). - - For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor - ids and returns the respective pixel points of the specified anchor. - - \see createAnchor -*/ -QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const -{ - qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified - \a name must be a unique string that is usually identical to the variable name of the position - member (This is needed to provide the name-based \ref position access to positions). - - Don't delete positions created by this function manually, as the item will take care of it. - - Use this function in the constructor (initialization list) of the specific item subclass to - create each position member. Don't create QCPItemPositions with \b new yourself, because they - won't be registered with the item properly. - - \see createAnchor -*/ -QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) -{ - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); - mPositions.append(newPosition); - mAnchors.append(newPosition); // every position is also an anchor - newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); - newPosition->setType(QCPItemPosition::ptPlotCoords); - if (mParentPlot->axisRect()) - newPosition->setAxisRect(mParentPlot->axisRect()); - newPosition->setCoords(0, 0); - return newPosition; -} - -/*! \internal - - Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified - \a name must be a unique string that is usually identical to the variable name of the anchor - member (This is needed to provide the name based \ref anchor access to anchors). - - The \a anchorId must be a number identifying the created anchor. It is recommended to create an - enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor - to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns - the correct pixel coordinates for the passed anchor id. - - Don't delete anchors created by this function manually, as the item will take care of it. - - Use this function in the constructor (initialization list) of the specific item subclass to - create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they - won't be registered with the item properly. - - \see createPosition -*/ -QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) -{ - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); - mAnchors.append(newAnchor); - return newAnchor; -} - -/* inherits documentation from base class */ -void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) -{ - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -QCP::Interaction QCPAbstractItem::selectionCategory() const -{ - return QCP::iSelectItems; -} - - -/*! \file */ - - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCustomPlot -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCustomPlot - - \brief The central class of the library. This is the QWidget which displays the plot and - interacts with the user. - - For tutorials on how to use QCustomPlot, see the website\n - http://www.qcustomplot.com/ -*/ - -/* start of documentation of inline functions */ - -/*! \fn QRect QCustomPlot::viewport() const - - Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is - drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the - plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left - (0, 0) and size of the QCustomPlot widget. - - Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically - an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger - and contains also the axes themselves, their tick numbers, their labels, the plot title etc. - - Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily - modified to allow saving plots with sizes independent of the current widget size. -*/ - -/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const - - Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just - one cell with the main QCPAxisRect inside. -*/ - -/* end of documentation of inline functions */ -/* start of documentation of signals */ - -/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) - - This signal is emitted when the QCustomPlot receives a mouse double click event. -*/ - -/*! \fn void QCustomPlot::mousePress(QMouseEvent *event) - - This signal is emitted when the QCustomPlot receives a mouse press event. - - It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot - connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref - QCPAxisRect::setRangeDragAxes. -*/ - -/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) - - This signal is emitted when the QCustomPlot receives a mouse move event. - - It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot - connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref - QCPAxisRect::setRangeDragAxes. - - \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, - because the dragging starting point was saved the moment the mouse was pressed. Thus it only has - a meaning for the range drag axes that were set at that moment. If you want to change the drag - axes, consider doing this in the \ref mousePress signal instead. -*/ - -/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) - - This signal is emitted when the QCustomPlot receives a mouse release event. - - It is emitted before QCustomPlot handles any other mechanisms like object selection. So a - slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or - \ref QCPAbstractPlottable::setSelectable. -*/ - -/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) - - This signal is emitted when the QCustomPlot receives a mouse wheel event. - - It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot - connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref - QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. -*/ - -/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) - - This signal is emitted when a plottable is clicked. - - \a event is the mouse event that caused the click and \a plottable is the plottable that received - the click. - - \see plottableDoubleClick -*/ - -/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) - - This signal is emitted when a plottable is double clicked. - - \a event is the mouse event that caused the click and \a plottable is the plottable that received - the click. - - \see plottableClick -*/ - -/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) - - This signal is emitted when an item is clicked. - - \a event is the mouse event that caused the click and \a item is the item that received the - click. - - \see itemDoubleClick -*/ - -/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) - - This signal is emitted when an item is double clicked. - - \a event is the mouse event that caused the click and \a item is the item that received the - click. - - \see itemClick -*/ - -/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) - - This signal is emitted when an axis is clicked. - - \a event is the mouse event that caused the click, \a axis is the axis that received the click and - \a part indicates the part of the axis that was clicked. - - \see axisDoubleClick -*/ - -/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) - - This signal is emitted when an axis is double clicked. - - \a event is the mouse event that caused the click, \a axis is the axis that received the click and - \a part indicates the part of the axis that was clicked. - - \see axisClick -*/ - -/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) - - This signal is emitted when a legend (item) is clicked. - - \a event is the mouse event that caused the click, \a legend is the legend that received the - click and \a item is the legend item that received the click. If only the legend and no item is - clicked, \a item is 0. This happens for a click inside the legend padding or the space between - two items. - - \see legendDoubleClick -*/ - -/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) - - This signal is emitted when a legend (item) is double clicked. - - \a event is the mouse event that caused the click, \a legend is the legend that received the - click and \a item is the legend item that received the click. If only the legend and no item is - clicked, \a item is 0. This happens for a click inside the legend padding or the space between - two items. - - \see legendClick -*/ - -/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) - - This signal is emitted when a plot title is clicked. - - \a event is the mouse event that caused the click and \a title is the plot title that received - the click. - - \see titleDoubleClick -*/ - -/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) - - This signal is emitted when a plot title is double clicked. - - \a event is the mouse event that caused the click and \a title is the plot title that received - the click. - - \see titleClick -*/ - -/*! \fn void QCustomPlot::selectionChangedByUser() - - This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by - clicking. It is not emitted when the selection state of an object has changed programmatically by - a direct call to setSelected() on an object or by calling \ref deselectAll. - - In addition to this signal, selectable objects also provide individual signals, for example - QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are - emitted even if the selection state is changed programmatically. - - See the documentation of \ref setInteractions for details about the selection mechanism. - - \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends -*/ - -/*! \fn void QCustomPlot::beforeReplot() - - This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref - replot). - - It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them - replot synchronously, it won't cause an infinite recursion. - - \see replot, afterReplot -*/ - -/*! \fn void QCustomPlot::afterReplot() - - This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref - replot). - - It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them - replot synchronously, it won't cause an infinite recursion. - - \see replot, beforeReplot -*/ - -/* end of documentation of signals */ -/* start of documentation of public members */ - -/*! \var QCPAxis *QCustomPlot::xAxis - - A pointer to the primary x Axis (bottom) of the main axis rect of the plot. - - QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref - yAxis2) and the \ref legend. They make it very easy working with plots that only have a single - axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the - layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref - QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the - default legend is removed due to manipulation of the layout system (e.g. by removing the main - axis rect), the corresponding pointers become 0. -*/ - -/*! \var QCPAxis *QCustomPlot::yAxis - - A pointer to the primary y Axis (left) of the main axis rect of the plot. - - QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref - yAxis2) and the \ref legend. They make it very easy working with plots that only have a single - axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the - layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref - QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the - default legend is removed due to manipulation of the layout system (e.g. by removing the main - axis rect), the corresponding pointers become 0. -*/ - -/*! \var QCPAxis *QCustomPlot::xAxis2 - - A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are - invisible by default. Use QCPAxis::setVisible to change this (or use \ref - QCPAxisRect::setupFullAxesBox). - - QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref - yAxis2) and the \ref legend. They make it very easy working with plots that only have a single - axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the - layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref - QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the - default legend is removed due to manipulation of the layout system (e.g. by removing the main - axis rect), the corresponding pointers become 0. -*/ - -/*! \var QCPAxis *QCustomPlot::yAxis2 - - A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are - invisible by default. Use QCPAxis::setVisible to change this (or use \ref - QCPAxisRect::setupFullAxesBox). - - QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref - yAxis2) and the \ref legend. They make it very easy working with plots that only have a single - axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the - layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref - QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the - default legend is removed due to manipulation of the layout system (e.g. by removing the main - axis rect), the corresponding pointers become 0. -*/ - -/*! \var QCPLegend *QCustomPlot::legend - - A pointer to the default legend of the main axis rect. The legend is invisible by default. Use - QCPLegend::setVisible to change this. - - QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref - yAxis2) and the \ref legend. They make it very easy working with plots that only have a single - axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the - layout system\endlink to add multiple legends to the plot, use the layout system interface to - access the new legend. For example, legends can be placed inside an axis rect's \ref - QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If - the default legend is removed due to manipulation of the layout system (e.g. by removing the main - axis rect), the corresponding pointer becomes 0. -*/ - -/* end of documentation of public members */ - -/*! - Constructs a QCustomPlot and sets reasonable default values. -*/ -QCustomPlot::QCustomPlot(QWidget *parent) : - QWidget(parent), - xAxis(0), - yAxis(0), - xAxis2(0), - yAxis2(0), - legend(0), - mPlotLayout(0), - mAutoAddPlottableToLegend(true), - mAntialiasedElements(QCP::aeNone), - mNotAntialiasedElements(QCP::aeNone), - mInteractions(0), - mSelectionTolerance(8), - mNoAntialiasingOnDrag(false), - mBackgroundBrush(Qt::white, Qt::SolidPattern), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mCurrentLayer(0), - mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), - mMultiSelectModifier(Qt::ControlModifier), - mPaintBuffer(size()), - mMouseEventElement(0), - mReplotting(false) -{ - setAttribute(Qt::WA_NoMousePropagation); - setAttribute(Qt::WA_OpaquePaintEvent); - setMouseTracking(true); - QLocale currentLocale = locale(); - currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); - setLocale(currentLocale); - - // create initial layers: - mLayers.append(new QCPLayer(this, QLatin1String("background"))); - mLayers.append(new QCPLayer(this, QLatin1String("grid"))); - mLayers.append(new QCPLayer(this, QLatin1String("main"))); - mLayers.append(new QCPLayer(this, QLatin1String("axes"))); - mLayers.append(new QCPLayer(this, QLatin1String("legend"))); - updateLayerIndices(); - setCurrentLayer(QLatin1String("main")); - - // create initial layout, axis rect and legend: - mPlotLayout = new QCPLayoutGrid; - mPlotLayout->initializeParentPlot(this); - mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry - mPlotLayout->setLayer(QLatin1String("main")); - QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); - mPlotLayout->addElement(0, 0, defaultAxisRect); - xAxis = defaultAxisRect->axis(QCPAxis::atBottom); - yAxis = defaultAxisRect->axis(QCPAxis::atLeft); - xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); - yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); - legend = new QCPLegend; - legend->setVisible(false); - defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); - defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); - - defaultAxisRect->setLayer(QLatin1String("background")); - xAxis->setLayer(QLatin1String("axes")); - yAxis->setLayer(QLatin1String("axes")); - xAxis2->setLayer(QLatin1String("axes")); - yAxis2->setLayer(QLatin1String("axes")); - xAxis->grid()->setLayer(QLatin1String("grid")); - yAxis->grid()->setLayer(QLatin1String("grid")); - xAxis2->grid()->setLayer(QLatin1String("grid")); - yAxis2->grid()->setLayer(QLatin1String("grid")); - legend->setLayer(QLatin1String("legend")); - - setViewport(rect()); // needs to be called after mPlotLayout has been created - - replot(); -} - -QCustomPlot::~QCustomPlot() -{ - clearPlottables(); - clearItems(); - - if (mPlotLayout) - { - delete mPlotLayout; - mPlotLayout = 0; - } - - mCurrentLayer = 0; - qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed - mLayers.clear(); -} - -/*! - Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. - - This overrides the antialiasing settings for whole element groups, normally controlled with the - \a setAntialiasing function on the individual elements. If an element is neither specified in - \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on - each individual element instance is used. - - For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be - drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set - to. - - if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is - removed from there. - - \see setNotAntialiasedElements -*/ -void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) -{ - mAntialiasedElements = antialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; -} - -/*! - Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. - - See \ref setAntialiasedElements for details. - - \see setNotAntialiasedElement -*/ -void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) -{ - if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements &= ~antialiasedElement; - else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements |= antialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; -} - -/*! - Sets which elements are forcibly drawn not antialiased as an \a or combination of - QCP::AntialiasedElement. - - This overrides the antialiasing settings for whole element groups, normally controlled with the - \a setAntialiasing function on the individual elements. If an element is neither specified in - \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on - each individual element instance is used. - - For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be - drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set - to. - - if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is - removed from there. - - \see setAntialiasedElements -*/ -void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) -{ - mNotAntialiasedElements = notAntialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; -} - -/*! - Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. - - See \ref setNotAntialiasedElements for details. - - \see setAntialiasedElement -*/ -void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) -{ - if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements &= ~notAntialiasedElement; - else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements |= notAntialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; -} - -/*! - If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the - plottable to the legend (QCustomPlot::legend). - - \see addPlottable, addGraph, QCPLegend::addItem -*/ -void QCustomPlot::setAutoAddPlottableToLegend(bool on) -{ - mAutoAddPlottableToLegend = on; -} - -/*! - Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction - enums. There are the following types of interactions: - - Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the - respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. - For details how to control which axes the user may drag/zoom and in what orientations, see \ref - QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, - \ref QCPAxisRect::setRangeZoomAxes. - - Plottable selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is - set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their - vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can - further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific - plottable. To find out whether a specific plottable is selected, call - QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call - \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience - function \ref selectedGraphs. - - Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user - may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find - out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of - all currently selected items, call \ref selectedItems. - - Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user - may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick - labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for - each axis. To retrieve a list of all axes that currently contain selected parts, call \ref - selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). - - Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may - select the legend itself or individual items by clicking on them. What parts exactly are - selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the - legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To - find out which child items are selected, call \ref QCPLegend::selectedItems. - - All other selectable elements The selection of all other selectable objects (e.g. - QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the - user may select those objects by clicking on them. To find out which are currently selected, you - need to check their selected state explicitly. - - If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is - emitted. Each selectable object additionally emits an individual selectionChanged signal whenever - their selection state has changed, i.e. not only by user interaction. - - To allow multiple objects to be selected by holding the selection modifier (\ref - setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. - - \note In addition to the selection mechanism presented here, QCustomPlot always emits - corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and - \ref plottableDoubleClick for example. - - \see setInteraction, setSelectionTolerance -*/ -void QCustomPlot::setInteractions(const QCP::Interactions &interactions) -{ - mInteractions = interactions; -} - -/*! - Sets the single \a interaction of this QCustomPlot to \a enabled. - - For details about the interaction system, see \ref setInteractions. - - \see setInteractions -*/ -void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) -{ - if (!enabled && mInteractions.testFlag(interaction)) - mInteractions &= ~interaction; - else if (enabled && !mInteractions.testFlag(interaction)) - mInteractions |= interaction; -} - -/*! - Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or - not. - - If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a - potential selection when the minimum distance between the click position and the graph line is - smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks - directly inside the area and ignore this selection tolerance. In other words, it only has meaning - for parts of objects that are too thin to exactly hit with a click and thus need such a - tolerance. - - \see setInteractions, QCPLayerable::selectTest -*/ -void QCustomPlot::setSelectionTolerance(int pixels) -{ - mSelectionTolerance = pixels; -} - -/*! - Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes - ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves - performance during dragging. Thus it creates a more responsive user experience. As soon as the - user stops dragging, the last replot is done with normal antialiasing, to restore high image - quality. - - \see setAntialiasedElements, setNotAntialiasedElements -*/ -void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) -{ - mNoAntialiasingOnDrag = enabled; -} - -/*! - Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. - - \see setPlottingHint -*/ -void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) -{ - mPlottingHints = hints; -} - -/*! - Sets the specified plotting \a hint to \a enabled. - - \see setPlottingHints -*/ -void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) -{ - QCP::PlottingHints newHints = mPlottingHints; - if (!enabled) - newHints &= ~hint; - else - newHints |= hint; - - if (newHints != mPlottingHints) - setPlottingHints(newHints); -} - -/*! - Sets the keyboard modifier that will be recognized as multi-select-modifier. - - If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects - by clicking on them one after the other while holding down \a modifier. - - By default the multi-select-modifier is set to Qt::ControlModifier. - - \see setInteractions -*/ -void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) -{ - mMultiSelectModifier = modifier; -} - -/*! - Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout - (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. - - This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref - savePdf, etc. by temporarily changing the viewport size. -*/ -void QCustomPlot::setViewport(const QRect &rect) -{ - mViewport = rect; - if (mPlotLayout) - mPlotLayout->setOuterRect(mViewport); -} - -/*! - Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn - below all other objects in the plot. - - For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be - enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is - preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, - consider using the overloaded version of this function. - - If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will - first be filled with that brush, before drawing the background pixmap. This can be useful for - background pixmaps with translucent areas. - - \see setBackgroundScaled, setBackgroundScaledMode -*/ -void QCustomPlot::setBackground(const QPixmap &pm) -{ - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); -} - -/*! - Sets the background brush of the viewport (see \ref setViewport). - - Before drawing everything else, the background is filled with \a brush. If a background pixmap - was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport - before the background pixmap is drawn. This can be useful for background pixmaps with translucent - areas. - - Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be - useful for exporting to image formats which support transparency, e.g. \ref savePng. - - \see setBackgroundScaled, setBackgroundScaledMode -*/ -void QCustomPlot::setBackground(const QBrush &brush) -{ - mBackgroundBrush = brush; -} - -/*! \overload - - Allows setting the background pixmap of the viewport, whether it shall be scaled and how it - shall be scaled in one call. - - \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode -*/ -void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) -{ - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; -} - -/*! - Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is - set to true, control whether and how the aspect ratio of the original pixmap is preserved with - \ref setBackgroundScaledMode. - - Note that the scaled version of the original pixmap is buffered, so there is no performance - penalty on replots. (Except when the viewport dimensions are changed continuously.) - - \see setBackground, setBackgroundScaledMode -*/ -void QCustomPlot::setBackgroundScaled(bool scaled) -{ - mBackgroundScaled = scaled; -} - -/*! - If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this - function to define whether and how the aspect ratio of the original pixmap is preserved. - - \see setBackground, setBackgroundScaled -*/ -void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) -{ - mBackgroundScaledMode = mode; -} - -/*! - Returns the plottable with \a index. If the index is invalid, returns 0. - - There is an overloaded version of this function with no parameter which returns the last added - plottable, see QCustomPlot::plottable() - - \see plottableCount, addPlottable -*/ -QCPAbstractPlottable *QCustomPlot::plottable(int index) -{ - if (index >= 0 && index < mPlottables.size()) - { - return mPlottables.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } -} - -/*! \overload - - Returns the last plottable that was added with \ref addPlottable. If there are no plottables in - the plot, returns 0. - - \see plottableCount, addPlottable -*/ -QCPAbstractPlottable *QCustomPlot::plottable() -{ - if (!mPlottables.isEmpty()) - { - return mPlottables.last(); - } else - return 0; -} - -/*! - Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to - the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. - - Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of - \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the - plottable's constructor). - - \see plottable, plottableCount, removePlottable, clearPlottables -*/ -bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) -{ - if (mPlottables.contains(plottable)) - { - qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); - return false; - } - if (plottable->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); - return false; - } - - mPlottables.append(plottable); - // possibly add plottable to legend: - if (mAutoAddPlottableToLegend) - plottable->addToLegend(); - // special handling for QCPGraphs to maintain the simple graph interface: - if (QCPGraph *graph = qobject_cast(plottable)) - mGraphs.append(graph); - if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) - plottable->setLayer(currentLayer()); - return true; -} - -/*! - Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). - - Returns true on success. - - \see addPlottable, clearPlottables -*/ -bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) -{ - if (!mPlottables.contains(plottable)) - { - qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); - return false; - } - - // remove plottable from legend: - plottable->removeFromLegend(); - // special handling for QCPGraphs to maintain the simple graph interface: - if (QCPGraph *graph = qobject_cast(plottable)) - mGraphs.removeOne(graph); - // remove plottable: - delete plottable; - mPlottables.removeOne(plottable); - return true; -} - -/*! \overload - - Removes the plottable by its \a index. -*/ -bool QCustomPlot::removePlottable(int index) -{ - if (index >= 0 && index < mPlottables.size()) - return removePlottable(mPlottables[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } -} - -/*! - Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). - - Returns the number of plottables removed. - - \see removePlottable -*/ -int QCustomPlot::clearPlottables() -{ - int c = mPlottables.size(); - for (int i=c-1; i >= 0; --i) - removePlottable(mPlottables[i]); - return c; -} - -/*! - Returns the number of currently existing plottables in the plot - - \see plottable, addPlottable -*/ -int QCustomPlot::plottableCount() const -{ - return mPlottables.size(); -} - -/*! - Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. - - There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. - - \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected -*/ -QList QCustomPlot::selectedPlottables() const -{ - QList result; - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (plottable->selected()) - result.append(plottable); - } - return result; -} - -/*! - Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines - (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple - plottables come into consideration, the one closest to \a pos is returned. - - If \a onlySelectable is true, only plottables that are selectable - (QCPAbstractPlottable::setSelectable) are considered. - - If there is no plottable at \a pos, the return value is 0. - - \see itemAt, layoutElementAt -*/ -QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const -{ - QCPAbstractPlottable *resultPlottable = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable - continue; - if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes - { - double currentDistance = plottable->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultPlottable = plottable; - resultDistance = currentDistance; - } - } - } - - return resultPlottable; -} - -/*! - Returns whether this QCustomPlot instance contains the \a plottable. - - \see addPlottable -*/ -bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const -{ - return mPlottables.contains(plottable); -} - -/*! - Returns the graph with \a index. If the index is invalid, returns 0. - - There is an overloaded version of this function with no parameter which returns the last created - graph, see QCustomPlot::graph() - - \see graphCount, addGraph -*/ -QCPGraph *QCustomPlot::graph(int index) const -{ - if (index >= 0 && index < mGraphs.size()) - { - return mGraphs.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } -} - -/*! \overload - - Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, - returns 0. - - \see graphCount, addGraph -*/ -QCPGraph *QCustomPlot::graph() const -{ - if (!mGraphs.isEmpty()) - { - return mGraphs.last(); - } else - return 0; -} - -/*! - Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the - bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a - keyAxis and \a valueAxis must reside in this QCustomPlot. - - \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically - "y") for the graph. - - Returns a pointer to the newly created graph, or 0 if adding the graph failed. - - \see graph, graphCount, removeGraph, clearGraphs -*/ -QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) -{ - if (!keyAxis) keyAxis = xAxis; - if (!valueAxis) valueAxis = yAxis; - if (!keyAxis || !valueAxis) - { - qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; - return 0; - } - if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; - return 0; - } - - QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); - if (addPlottable(newGraph)) - { - newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); - return newGraph; - } else - { - delete newGraph; - return 0; - } -} - -/*! - Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If - any other graphs in the plot have a channel fill set towards the removed graph, the channel fill - property of those graphs is reset to zero (no channel fill). - - Returns true on success. - - \see clearGraphs -*/ -bool QCustomPlot::removeGraph(QCPGraph *graph) -{ - return removePlottable(graph); -} - -/*! \overload - - Removes the graph by its \a index. -*/ -bool QCustomPlot::removeGraph(int index) -{ - if (index >= 0 && index < mGraphs.size()) - return removeGraph(mGraphs[index]); - else - return false; -} - -/*! - Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). - - Returns the number of graphs removed. - - \see removeGraph -*/ -int QCustomPlot::clearGraphs() -{ - int c = mGraphs.size(); - for (int i=c-1; i >= 0; --i) - removeGraph(mGraphs[i]); - return c; -} - -/*! - Returns the number of currently existing graphs in the plot - - \see graph, addGraph -*/ -int QCustomPlot::graphCount() const -{ - return mGraphs.size(); -} - -/*! - Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. - - If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, - etc., use \ref selectedPlottables. - - \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected -*/ -QList QCustomPlot::selectedGraphs() const -{ - QList result; - foreach (QCPGraph *graph, mGraphs) - { - if (graph->selected()) - result.append(graph); - } - return result; -} - -/*! - Returns the item with \a index. If the index is invalid, returns 0. - - There is an overloaded version of this function with no parameter which returns the last added - item, see QCustomPlot::item() - - \see itemCount, addItem -*/ -QCPAbstractItem *QCustomPlot::item(int index) const -{ - if (index >= 0 && index < mItems.size()) - { - return mItems.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } -} - -/*! \overload - - Returns the last item, that was added with \ref addItem. If there are no items in the plot, - returns 0. - - \see itemCount, addItem -*/ -QCPAbstractItem *QCustomPlot::item() const -{ - if (!mItems.isEmpty()) - { - return mItems.last(); - } else - return 0; -} - -/*! - Adds the specified item to the plot. QCustomPlot takes ownership of the item. - - Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a - item is this QCustomPlot. - - \see item, itemCount, removeItem, clearItems -*/ -bool QCustomPlot::addItem(QCPAbstractItem *item) -{ - if (!mItems.contains(item) && item->parentPlot() == this) - { - mItems.append(item); - return true; - } else - { - qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); - return false; - } -} - -/*! - Removes the specified item from the plot. - - Returns true on success. - - \see addItem, clearItems -*/ -bool QCustomPlot::removeItem(QCPAbstractItem *item) -{ - if (mItems.contains(item)) - { - delete item; - mItems.removeOne(item); - return true; - } else - { - qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); - return false; - } -} - -/*! \overload - - Removes the item by its \a index. -*/ -bool QCustomPlot::removeItem(int index) -{ - if (index >= 0 && index < mItems.size()) - return removeItem(mItems[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } -} - -/*! - Removes all items from the plot. - - Returns the number of items removed. - - \see removeItem -*/ -int QCustomPlot::clearItems() -{ - int c = mItems.size(); - for (int i=c-1; i >= 0; --i) - removeItem(mItems[i]); - return c; -} - -/*! - Returns the number of currently existing items in the plot - - \see item, addItem -*/ -int QCustomPlot::itemCount() const -{ - return mItems.size(); -} - -/*! - Returns a list of the selected items. If no items are currently selected, the list is empty. - - \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected -*/ -QList QCustomPlot::selectedItems() const -{ - QList result; - foreach (QCPAbstractItem *item, mItems) - { - if (item->selected()) - result.append(item); - } - return result; -} - -/*! - Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref - QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref - setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is - returned. - - If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are - considered. - - If there is no item at \a pos, the return value is 0. - - \see plottableAt, layoutElementAt -*/ -QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const -{ - QCPAbstractItem *resultItem = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractItem *item, mItems) - { - if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable - continue; - if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it - { - double currentDistance = item->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultItem = item; - resultDistance = currentDistance; - } - } - } - - return resultItem; -} - -/*! - Returns whether this QCustomPlot contains the \a item. - - \see addItem -*/ -bool QCustomPlot::hasItem(QCPAbstractItem *item) const -{ - return mItems.contains(item); -} - -/*! - Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is - returned. - - Layer names are case-sensitive. - - \see addLayer, moveLayer, removeLayer -*/ -QCPLayer *QCustomPlot::layer(const QString &name) const -{ - foreach (QCPLayer *layer, mLayers) - { - if (layer->name() == name) - return layer; - } - return 0; -} - -/*! \overload - - Returns the layer by \a index. If the index is invalid, 0 is returned. - - \see addLayer, moveLayer, removeLayer -*/ -QCPLayer *QCustomPlot::layer(int index) const -{ - if (index >= 0 && index < mLayers.size()) - { - return mLayers.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } -} - -/*! - Returns the layer that is set as current layer (see \ref setCurrentLayer). -*/ -QCPLayer *QCustomPlot::currentLayer() const -{ - return mCurrentLayer; -} - -/*! - Sets the layer with the specified \a name to be the current layer. All layerables (\ref - QCPLayerable), e.g. plottables and items, are created on the current layer. - - Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. - - Layer names are case-sensitive. - - \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer -*/ -bool QCustomPlot::setCurrentLayer(const QString &name) -{ - if (QCPLayer *newCurrentLayer = layer(name)) - { - return setCurrentLayer(newCurrentLayer); - } else - { - qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; - return false; - } -} - -/*! \overload - - Sets the provided \a layer to be the current layer. - - Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. - - \see addLayer, moveLayer, removeLayer -*/ -bool QCustomPlot::setCurrentLayer(QCPLayer *layer) -{ - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - - mCurrentLayer = layer; - return true; -} - -/*! - Returns the number of currently existing layers in the plot - - \see layer, addLayer -*/ -int QCustomPlot::layerCount() const -{ - return mLayers.size(); -} - -/*! - Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which - must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. - - Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a - valid layer inside this QCustomPlot. - - If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. - - For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. - - \see layer, moveLayer, removeLayer -*/ -bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) -{ - if (!otherLayer) - otherLayer = mLayers.last(); - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - if (layer(name)) - { - qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; - return false; - } - - QCPLayer *newLayer = new QCPLayer(this, name); - mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); - updateLayerIndices(); - return true; -} - -/*! - Removes the specified \a layer and returns true on success. - - All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below - \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both - cases, the total rendering order of all layerables in the QCustomPlot is preserved. - - If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom - layer) becomes the new current layer. - - It is not possible to remove the last layer of the plot. - - \see layer, addLayer, moveLayer -*/ -bool QCustomPlot::removeLayer(QCPLayer *layer) -{ - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (mLayers.size() < 2) - { - qDebug() << Q_FUNC_INFO << "can't remove last layer"; - return false; - } - - // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) - int removedIndex = layer->index(); - bool isFirstLayer = removedIndex==0; - QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); - QList children = layer->children(); - if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) - { - for (int i=children.size()-1; i>=0; --i) - children.at(i)->moveToLayer(targetLayer, true); - } else // append normally - { - for (int i=0; imoveToLayer(targetLayer, false); - } - // if removed layer is current layer, change current layer to layer below/above: - if (layer == mCurrentLayer) - setCurrentLayer(targetLayer); - // remove layer: - delete layer; - mLayers.removeOne(layer); - updateLayerIndices(); - return true; -} - -/*! - Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or - below is controlled with \a insertMode. - - Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the - QCustomPlot. - - \see layer, addLayer, moveLayer -*/ -bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) -{ - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - - if (layer->index() > otherLayer->index()) - mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); - else if (layer->index() < otherLayer->index()) - mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1)); - - updateLayerIndices(); - return true; -} - -/*! - Returns the number of axis rects in the plot. - - All axis rects can be accessed via QCustomPlot::axisRect(). - - Initially, only one axis rect exists in the plot. - - \see axisRect, axisRects -*/ -int QCustomPlot::axisRectCount() const -{ - return axisRects().size(); -} - -/*! - Returns the axis rect with \a index. - - Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were - added, all of them may be accessed with this function in a linear fashion (even when they are - nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). - - \see axisRectCount, axisRects -*/ -QCPAxisRect *QCustomPlot::axisRect(int index) const -{ - const QList rectList = axisRects(); - if (index >= 0 && index < rectList.size()) - { - return rectList.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; - return 0; - } -} - -/*! - Returns all axis rects in the plot. - - \see axisRectCount, axisRect -*/ -QList QCustomPlot::axisRects() const -{ - QList result; - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) - { - if (element) - { - elementStack.push(element); - if (QCPAxisRect *ar = qobject_cast(element)) - result.append(ar); - } - } - } - - return result; -} - -/*! - Returns the layout element at pixel position \a pos. If there is no element at that position, - returns 0. - - Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on - any of its parent elements is set to false, it will not be considered. - - \see itemAt, plottableAt -*/ -QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const -{ - QCPLayoutElement *currentElement = mPlotLayout; - bool searchSubElements = true; - while (searchSubElements && currentElement) - { - searchSubElements = false; - foreach (QCPLayoutElement *subElement, currentElement->elements(false)) - { - if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) - { - currentElement = subElement; - searchSubElements = true; - break; - } - } - } - return currentElement; -} - -/*! - Returns the axes that currently have selected parts, i.e. whose selection state is not \ref - QCPAxis::spNone. - - \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, - QCPAxis::setSelectableParts -*/ -QList QCustomPlot::selectedAxes() const -{ - QList result, allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - { - if (axis->selectedParts() != QCPAxis::spNone) - result.append(axis); - } - - return result; -} - -/*! - Returns the legends that currently have selected parts, i.e. whose selection state is not \ref - QCPLegend::spNone. - - \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, - QCPLegend::setSelectableParts, QCPLegend::selectedItems -*/ -QList QCustomPlot::selectedLegends() const -{ - QList result; - - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) - { - if (subElement) - { - elementStack.push(subElement); - if (QCPLegend *leg = qobject_cast(subElement)) - { - if (leg->selectedParts() != QCPLegend::spNone) - result.append(leg); - } - } - } - } - - return result; -} - -/*! - Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. - - Since calling this function is not a user interaction, this does not emit the \ref - selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the - objects were previously selected. - - \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends -*/ -void QCustomPlot::deselectAll() -{ - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *layerable, layer->children()) - layerable->deselectEvent(0); - } -} - -/*! - Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the - buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, - for example on the axis ranges or data points of graphs, visible. - - Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the - QCustomPlot widget and user interactions (object selection and range dragging/zooming). - - Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref - afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two - signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite - recursion. -*/ -void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) -{ - if (mReplotting) // incase signals loop back to replot slot - return; - mReplotting = true; - emit beforeReplot(); - - mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); - QCPPainter painter; - painter.begin(&mPaintBuffer); - if (painter.isActive()) - { - painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem - if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - painter.end(); - if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) - repaint(); - else - update(); - } else // might happen if QCustomPlot has width or height zero - qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero."; - - emit afterReplot(); - mReplotting = false; -} - -/*! - Rescales the axes such that all plottables (like graphs) in the plot are fully visible. - - if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true - (QCPLayerable::setVisible), will be used to rescale the axes. - - \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale -*/ -void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) -{ - QList allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - axis->rescale(onlyVisiblePlottables); -} - -/*! - Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale - of texts and lines will be derived from the specified \a width and \a height. This means, the - output will look like the normal on-screen output of a QCustomPlot widget with the corresponding - pixel width and height. If either \a width or \a height is zero, the exported image will have the - same dimensions as the QCustomPlot widget currently has. - - \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens - are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what - zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter - and QPen documentation. - - The objects of the plot will appear in the current selection state. If you don't want any - selected objects to be painted in their selected look, deselect everything with \ref deselectAll - before calling this function. - - Returns true on success. - - \warning - \li If you plan on editing the exported PDF file with a vector graphics editor like - Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines - (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). - \li If calling this function inside the constructor of the parent of the QCustomPlot widget - (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide - explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this - function uses the current width and height of the QCustomPlot widget. However, in Qt, these - aren't defined yet inside the constructor, so you would get an image that has strange - widths/heights. - - \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting - PDF file. - - \note On Android systems, this method does nothing and issues an according qDebug warning - message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. - - \see savePng, saveBmp, saveJpg, saveRastered -*/ -bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) -{ - bool success = false; -#ifdef QT_NO_PRINTER - Q_UNUSED(fileName) - Q_UNUSED(noCosmeticPen) - Q_UNUSED(width) - Q_UNUSED(height) - Q_UNUSED(pdfCreator) - Q_UNUSED(pdfTitle) - qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; -#else - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - - QPrinter printer(QPrinter::ScreenResolution); - printer.setOutputFileName(fileName); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setColorMode(QPrinter::Color); - printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); - printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); -#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) - printer.setFullPage(true); - printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); -#else - QPageLayout pageLayout; - pageLayout.setMode(QPageLayout::FullPageMode); - pageLayout.setOrientation(QPageLayout::Portrait); - pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); - pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); - printer.setPageLayout(pageLayout); -#endif - QCPPainter printpainter; - if (printpainter.begin(&printer)) - { - printpainter.setMode(QCPPainter::pmVectorized); - printpainter.setMode(QCPPainter::pmNoCaching); - printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); - printpainter.setWindow(mViewport); - if (mBackgroundBrush.style() != Qt::NoBrush && - mBackgroundBrush.color() != Qt::white && - mBackgroundBrush.color() != Qt::transparent && - mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent - printpainter.fillRect(viewport(), mBackgroundBrush); - draw(&printpainter); - printpainter.end(); - success = true; - } - setViewport(oldViewport); -#endif // QT_NO_PRINTER - return success; -} - -/*! - Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width - and \a height in pixels. If either \a width or \a height is zero, the exported image will have - the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not - scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. - - For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an - image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, - texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full - 200*200 pixel resolution. - - If you use a high scaling factor, it is recommended to enable antialiasing for all elements via - temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows - QCustomPlot to place objects with sub-pixel accuracy. - - \warning If calling this function inside the constructor of the parent of the QCustomPlot widget - (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide - explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this - function uses the current width and height of the QCustomPlot widget. However, in Qt, these - aren't defined yet inside the constructor, so you would get an image that has strange - widths/heights. - - The objects of the plot will appear in the current selection state. If you don't want any selected - objects to be painted in their selected look, deselect everything with \ref deselectAll before calling - this function. - - If you want the PNG to have a transparent background, call \ref setBackground(const QBrush - &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. - - PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or - -1 to use the default setting. - - Returns true on success. If this function fails, most likely the PNG format isn't supported by - the system, see Qt docs about QImageWriter::supportedImageFormats(). - - \see savePdf, saveBmp, saveJpg, saveRastered -*/ -bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) -{ - return saveRastered(fileName, width, height, scale, "PNG", quality); -} - -/*! - Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width - and \a height in pixels. If either \a width or \a height is zero, the exported image will have - the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not - scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. - - For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an - image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, - texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full - 200*200 pixel resolution. - - If you use a high scaling factor, it is recommended to enable antialiasing for all elements via - temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows - QCustomPlot to place objects with sub-pixel accuracy. - - \warning If calling this function inside the constructor of the parent of the QCustomPlot widget - (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide - explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this - function uses the current width and height of the QCustomPlot widget. However, in Qt, these - aren't defined yet inside the constructor, so you would get an image that has strange - widths/heights. - - The objects of the plot will appear in the current selection state. If you don't want any selected - objects to be painted in their selected look, deselect everything with \ref deselectAll before calling - this function. - - JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or - -1 to use the default setting. - - Returns true on success. If this function fails, most likely the JPG format isn't supported by - the system, see Qt docs about QImageWriter::supportedImageFormats(). - - \see savePdf, savePng, saveBmp, saveRastered -*/ -bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) -{ - return saveRastered(fileName, width, height, scale, "JPG", quality); -} - -/*! - Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width - and \a height in pixels. If either \a width or \a height is zero, the exported image will have - the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not - scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. - - For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an - image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, - texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full - 200*200 pixel resolution. - - If you use a high scaling factor, it is recommended to enable antialiasing for all elements via - temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows - QCustomPlot to place objects with sub-pixel accuracy. - - \warning If calling this function inside the constructor of the parent of the QCustomPlot widget - (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide - explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this - function uses the current width and height of the QCustomPlot widget. However, in Qt, these - aren't defined yet inside the constructor, so you would get an image that has strange - widths/heights. - - The objects of the plot will appear in the current selection state. If you don't want any selected - objects to be painted in their selected look, deselect everything with \ref deselectAll before calling - this function. - - Returns true on success. If this function fails, most likely the BMP format isn't supported by - the system, see Qt docs about QImageWriter::supportedImageFormats(). - - \see savePdf, savePng, saveJpg, saveRastered -*/ -bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) -{ - return saveRastered(fileName, width, height, scale, "BMP"); -} - -/*! \internal - - Returns a minimum size hint that corresponds to the minimum size of the top level layout - (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum - size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. - This is especially important, when placed in a QLayout where other components try to take in as - much space as possible (e.g. QMdiArea). -*/ -QSize QCustomPlot::minimumSizeHint() const -{ - return mPlotLayout->minimumSizeHint(); -} - -/*! \internal - - Returns a size hint that is the same as \ref minimumSizeHint. - -*/ -QSize QCustomPlot::sizeHint() const -{ - return mPlotLayout->minimumSizeHint(); -} - -/*! \internal - - Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but - draws the internal buffer on the widget surface. -*/ -void QCustomPlot::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event); - QPainter painter(this); - painter.drawPixmap(0, 0, mPaintBuffer); -} - -/*! \internal - - Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to - the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized - appropriately. Finally a \ref replot is performed. -*/ -void QCustomPlot::resizeEvent(QResizeEvent *event) -{ - // resize and repaint the buffer: - mPaintBuffer = QPixmap(event->size()); - setViewport(rect()); - replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts -} - -/*! \internal - - Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits - the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref - axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to - it. - - \see mousePressEvent, mouseReleaseEvent -*/ -void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) -{ - emit mouseDoubleClick(event); - - QVariant details; - QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); - - // emit specialized object double click signals: - if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) - emit plottableDoubleClick(ap, event); - else if (QCPAxis *ax = qobject_cast(clickedLayerable)) - emit axisDoubleClick(ax, details.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) - emit itemDoubleClick(ai, event); - else if (QCPLegend *lg = qobject_cast(clickedLayerable)) - emit legendDoubleClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) - emit legendDoubleClick(li->parentLegend(), li, event); - else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) - emit titleDoubleClick(event, pt); - - // call double click event of affected layout element: - if (QCPLayoutElement *el = layoutElementAt(event->pos())) - el->mouseDoubleClickEvent(event); - - // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): - if (mMouseEventElement) - { - mMouseEventElement->mouseReleaseEvent(event); - mMouseEventElement = 0; - } - - //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. -} - -/*! \internal - - Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines - the affected layout element and forwards the event to it. - - \see mouseMoveEvent, mouseReleaseEvent -*/ -void QCustomPlot::mousePressEvent(QMouseEvent *event) -{ - emit mousePress(event); - mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) - - // call event of affected layout element: - mMouseEventElement = layoutElementAt(event->pos()); - if (mMouseEventElement) - mMouseEventElement->mousePressEvent(event); - - QWidget::mousePressEvent(event); -} - -/*! \internal - - Event handler for when the cursor is moved. Emits the \ref mouseMove signal. - - If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout - element before), the mouseMoveEvent is forwarded to that element. - - \see mousePressEvent, mouseReleaseEvent -*/ -void QCustomPlot::mouseMoveEvent(QMouseEvent *event) -{ - emit mouseMove(event); - - // call event of affected layout element: - if (mMouseEventElement) - mMouseEventElement->mouseMoveEvent(event); - - QWidget::mouseMoveEvent(event); -} - -/*! \internal - - Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. - - If the mouse was moved less than a certain threshold in any direction since the \ref - mousePressEvent, it is considered a click which causes the selection mechanism (if activated via - \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse - click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) - - If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout - element before), the \ref mouseReleaseEvent is forwarded to that element. - - \see mousePressEvent, mouseMoveEvent -*/ -void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) -{ - emit mouseRelease(event); - bool doReplot = false; - - if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation - { - if (event->button() == Qt::LeftButton) - { - // handle selection mechanism: - QVariant details; - QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); - bool selectionStateChanged = false; - bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); - // deselect all other layerables if not additive selection: - if (!additive) - { - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *layerable, layer->children()) - { - if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) - { - bool selChanged = false; - layerable->deselectEvent(&selChanged); - selectionStateChanged |= selChanged; - } - } - } - } - if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) - { - // a layerable was actually clicked, call its selectEvent: - bool selChanged = false; - clickedLayerable->selectEvent(event, additive, details, &selChanged); - selectionStateChanged |= selChanged; - } - if (selectionStateChanged) - { - doReplot = true; - emit selectionChangedByUser(); - } - } - - // emit specialized object click signals: - QVariant details; - QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false - if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) - emit plottableClick(ap, event); - else if (QCPAxis *ax = qobject_cast(clickedLayerable)) - emit axisClick(ax, details.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) - emit itemClick(ai, event); - else if (QCPLegend *lg = qobject_cast(clickedLayerable)) - emit legendClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) - emit legendClick(li->parentLegend(), li, event); - else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) - emit titleClick(event, pt); - } - - // call event of affected layout element: - if (mMouseEventElement) - { - mMouseEventElement->mouseReleaseEvent(event); - mMouseEventElement = 0; - } - - if (doReplot || noAntialiasingOnDrag()) - replot(); - - QWidget::mouseReleaseEvent(event); -} - -/*! \internal - - Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then - determines the affected layout element and forwards the event to it. - -*/ -void QCustomPlot::wheelEvent(QWheelEvent *event) -{ - emit mouseWheel(event); - - // call event of affected layout element: - if (QCPLayoutElement *el = layoutElementAt(event->pos())) - el->wheelEvent(event); - - QWidget::wheelEvent(event); -} - -/*! \internal - - This is the main draw function. It draws the entire plot, including background pixmap, with the - specified \a painter. Note that it does not fill the background with the background brush (as the - user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective - functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). -*/ -void QCustomPlot::draw(QCPPainter *painter) -{ - // run through layout phases: - mPlotLayout->update(QCPLayoutElement::upPreparation); - mPlotLayout->update(QCPLayoutElement::upMargins); - mPlotLayout->update(QCPLayoutElement::upLayout); - - // draw viewport background pixmap: - drawBackground(painter); - - // draw all layered objects (grid, axes, plottables, items, legend,...): - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *child, layer->children()) - { - if (child->realVisibility()) - { - painter->save(); - painter->setClipRect(child->clipRect().translated(0, -1)); - child->applyDefaultAntialiasingHint(painter); - child->draw(painter); - painter->restore(); - } - } - } - - /* Debug code to draw all layout element rects - foreach (QCPLayoutElement* el, findChildren()) - { - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->rect()); - painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->outerRect()); - } - */ -} - -/*! \internal - - Draws the viewport background pixmap of the plot. - - If a pixmap was provided via \ref setBackground, this function buffers the scaled version - depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside - the viewport with the provided \a painter. The scaled version is buffered in - mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when - the axis rect has changed in a way that requires a rescale of the background pixmap (this is - dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was - set. - - Note that this function does not draw a fill with the background brush (\ref setBackground(const - QBrush &brush)) beneath the pixmap. - - \see setBackground, setBackgroundScaled, setBackgroundScaledMode -*/ -void QCustomPlot::drawBackground(QCPPainter *painter) -{ - // Note: background color is handled in individual replot/save functions - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mViewport.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); - } - } -} - - -/*! \internal - - This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot - so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. -*/ -void QCustomPlot::axisRemoved(QCPAxis *axis) -{ - if (xAxis == axis) - xAxis = 0; - if (xAxis2 == axis) - xAxis2 = 0; - if (yAxis == axis) - yAxis = 0; - if (yAxis2 == axis) - yAxis2 = 0; - - // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers -} - -/*! \internal - - This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so - it may clear its QCustomPlot::legend member accordingly. -*/ -void QCustomPlot::legendRemoved(QCPLegend *legend) -{ - if (this->legend == legend) - this->legend = 0; -} - -/*! \internal - - Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called - after every operation that changes the layer indices, like layer removal, layer creation, layer - moving. -*/ -void QCustomPlot::updateLayerIndices() const -{ - for (int i=0; imIndex = i; -} - -/*! \internal - - Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those - layerables that are selectable will be considered. (Layerable subclasses communicate their - selectability via the QCPLayerable::selectTest method, by returning -1.) - - \a selectionDetails is an output parameter that contains selection specifics of the affected - layerable. This is useful if the respective layerable shall be given a subsequent - QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains - information about which part of the layerable was hit, in multi-part layerables (e.g. - QCPAxis::SelectablePart). -*/ -QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const -{ - for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) - { - const QList layerables = mLayers.at(layerIndex)->children(); - double minimumDistance = selectionTolerance()*1.1; - QCPLayerable *minimumDistanceLayerable = 0; - for (int i=layerables.size()-1; i>=0; --i) - { - if (!layerables.at(i)->realVisibility()) - continue; - QVariant details; - double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); - if (dist >= 0 && dist < minimumDistance) - { - minimumDistance = dist; - minimumDistanceLayerable = layerables.at(i); - if (selectionDetails) *selectionDetails = details; - } - } - if (minimumDistance < selectionTolerance()) - return minimumDistanceLayerable; - } - return 0; -} - -/*! - Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is - sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead - to a full resolution file with width 200.) If the \a format supports compression, \a quality may - be between 0 and 100 to control it. - - Returns true on success. If this function fails, most likely the given \a format isn't supported - by the system, see Qt docs about QImageWriter::supportedImageFormats(). - - \see saveBmp, saveJpg, savePng, savePdf -*/ -bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) -{ - QPixmap buffer = toPixmap(width, height, scale); - if (!buffer.isNull()) - return buffer.save(fileName, format, quality); - else - return false; -} - -/*! - Renders the plot to a pixmap and returns it. - - The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and - scale 2.0 lead to a full resolution pixmap with width 200.) - - \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf -*/ -QPixmap QCustomPlot::toPixmap(int width, int height, double scale) -{ - // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - int scaledWidth = qRound(scale*newWidth); - int scaledHeight = qRound(scale*newHeight); - - QPixmap result(scaledWidth, scaledHeight); - result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later - QCPPainter painter; - painter.begin(&result); - if (painter.isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter.setMode(QCPPainter::pmNoCaching); - if (!qFuzzyCompare(scale, 1.0)) - { - if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales - painter.setMode(QCPPainter::pmNonCosmetic); - painter.scale(scale, scale); - } - if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - setViewport(oldViewport); - painter.end(); - } else // might happen if pixmap has width or height zero - { - qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; - return QPixmap(); - } - return result; -} - -/*! - Renders the plot using the passed \a painter. - - The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will - appear scaled accordingly. - - \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter - on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with - the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. - - \see toPixmap -*/ -void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) -{ - // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - - if (painter->isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter->setMode(QCPPainter::pmNoCaching); - if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here - painter->fillRect(mViewport, mBackgroundBrush); - draw(painter); - setViewport(oldViewport); - } else - qDebug() << Q_FUNC_INFO << "Passed painter is not active"; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPColorGradient -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPColorGradient - \brief Defines a color gradient for use with e.g. \ref QCPColorMap - - This class describes a color gradient which can be used to encode data with color. For example, - QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which - take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) - with a \a position from 0 to 1. In between these defined color positions, the - color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. - - Alternatively, load one of the preset color gradients shown in the image below, with \ref - loadPreset, or by directly specifying the preset in the constructor. - - \image html QCPColorGradient.png - - The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly - converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref - GradientPreset to all the \a setGradient methods, e.g.: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient - - The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the - color gradient shall be applied periodically (wrapping around) to data values that lie outside - the data range specified on the plottable instance can be controlled with \ref setPeriodic. -*/ - -/*! - Constructs a new QCPColorGradient initialized with the colors and color interpolation according - to \a preset. - - The color level count is initialized to 350. -*/ -QCPColorGradient::QCPColorGradient(GradientPreset preset) : - mLevelCount(350), - mColorInterpolation(ciRGB), - mPeriodic(false), - mColorBufferInvalidated(true) -{ - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); - loadPreset(preset); -} - -/* undocumented operator */ -bool QCPColorGradient::operator==(const QCPColorGradient &other) const -{ - return ((other.mLevelCount == this->mLevelCount) && - (other.mColorInterpolation == this->mColorInterpolation) && - (other.mPeriodic == this->mPeriodic) && - (other.mColorStops == this->mColorStops)); -} - -/*! - Sets the number of discretization levels of the color gradient to \a n. The default is 350 which - is typically enough to create a smooth appearance. - - \image html QCPColorGradient-levelcount.png -*/ -void QCPColorGradient::setLevelCount(int n) -{ - if (n < 2) - { - qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; - n = 2; - } - if (n != mLevelCount) - { - mLevelCount = n; - mColorBufferInvalidated = true; - } -} - -/*! - Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the - colors are the values of the passed QMap \a colorStops. In between these color stops, the color - is interpolated according to \ref setColorInterpolation. - - A more convenient way to create a custom gradient may be to clear all color stops with \ref - clearColorStops and then adding them one by one with \ref setColorStopAt. - - \see clearColorStops -*/ -void QCPColorGradient::setColorStops(const QMap &colorStops) -{ - mColorStops = colorStops; - mColorBufferInvalidated = true; -} - -/*! - Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between - these color stops, the color is interpolated according to \ref setColorInterpolation. - - \see setColorStops, clearColorStops -*/ -void QCPColorGradient::setColorStopAt(double position, const QColor &color) -{ - mColorStops.insert(position, color); - mColorBufferInvalidated = true; -} - -/*! - Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be - interpolated linearly in RGB or in HSV color space. - - For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, - whereas in HSV space the intermediate color is yellow. -*/ -void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) -{ - if (interpolation != mColorInterpolation) - { - mColorInterpolation = interpolation; - mColorBufferInvalidated = true; - } -} - -/*! - Sets whether data points that are outside the configured data range (e.g. \ref - QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether - they all have the same color, corresponding to the respective gradient boundary color. - - \image html QCPColorGradient-periodic.png - - As shown in the image above, gradients that have the same start and end color are especially - suitable for a periodic gradient mapping, since they produce smooth color transitions throughout - the color map. A preset that has this property is \ref gpHues. - - In practice, using periodic color gradients makes sense when the data corresponds to a periodic - dimension, such as an angle or a phase. If this is not the case, the color encoding might become - ambiguous, because multiple different data values are shown as the same color. -*/ -void QCPColorGradient::setPeriodic(bool enabled) -{ - mPeriodic = enabled; -} - -/*! - This method is used to quickly convert a \a data array to colors. The colors will be output in - the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this - function. The data range that shall be used for mapping the data value to the gradient is passed - in \a range. \a logarithmic indicates whether the data values shall be mapped to colors - logarithmically. - - if \a data actually contains 2D-data linearized via [row*columnCount + column], you can - set \a dataIndexFactor to columnCount to convert a column instead of a row of the data - array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data - is addressed data[i*dataIndexFactor]. -*/ -void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) -{ - // If you change something here, make sure to also adapt ::color() - if (!data) - { - qDebug() << Q_FUNC_INFO << "null pointer given as data"; - return; - } - if (!scanLine) - { - qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; - return; - } - if (mColorBufferInvalidated) - updateColorBuffer(); - - if (!logarithmic) - { - const double posToIndexFactor = (mLevelCount-1)/range.size(); - if (mPeriodic) - { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); - } - } - } else // logarithmic == true - { - if (mPeriodic) - { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); - } - } - } -} - -/*! \internal - - This method is used to colorize a single data value given in \a position, to colors. The data - range that shall be used for mapping the data value to the gradient is passed in \a range. \a - logarithmic indicates whether the data value shall be mapped to a color logarithmically. - - If an entire array of data values shall be converted, rather use \ref colorize, for better - performance. -*/ -QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) -{ - // If you change something here, make sure to also adapt ::colorize() - if (mColorBufferInvalidated) - updateColorBuffer(); - int index = 0; - if (!logarithmic) - index = (position-range.lower)*(mLevelCount-1)/range.size(); - else - index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); - if (mPeriodic) - { - index = index % mLevelCount; - if (index < 0) - index += mLevelCount; - } else - { - if (index < 0) - index = 0; - else if (index >= mLevelCount) - index = mLevelCount-1; - } - return mColorBuffer.at(index); -} - -/*! - Clears the current color stops and loads the specified \a preset. A preset consists of predefined - color stops and the corresponding color interpolation method. - - The available presets are: - \image html QCPColorGradient.png -*/ -void QCPColorGradient::loadPreset(GradientPreset preset) -{ - clearColorStops(); - switch (preset) - { - case gpGrayscale: - setColorInterpolation(ciRGB); - setColorStopAt(0, Qt::black); - setColorStopAt(1, Qt::white); - break; - case gpHot: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 0, 0)); - setColorStopAt(0.2, QColor(180, 10, 0)); - setColorStopAt(0.4, QColor(245, 50, 0)); - setColorStopAt(0.6, QColor(255, 150, 10)); - setColorStopAt(0.8, QColor(255, 255, 50)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpCold: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.2, QColor(0, 10, 180)); - setColorStopAt(0.4, QColor(0, 50, 245)); - setColorStopAt(0.6, QColor(10, 150, 255)); - setColorStopAt(0.8, QColor(50, 255, 255)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpNight: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(10, 20, 30)); - setColorStopAt(1, QColor(250, 255, 250)); - break; - case gpCandy: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(0, 0, 255)); - setColorStopAt(1, QColor(255, 250, 250)); - break; - case gpGeography: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(70, 170, 210)); - setColorStopAt(0.20, QColor(90, 160, 180)); - setColorStopAt(0.25, QColor(45, 130, 175)); - setColorStopAt(0.30, QColor(100, 140, 125)); - setColorStopAt(0.5, QColor(100, 140, 100)); - setColorStopAt(0.6, QColor(130, 145, 120)); - setColorStopAt(0.7, QColor(140, 130, 120)); - setColorStopAt(0.9, QColor(180, 190, 190)); - setColorStopAt(1, QColor(210, 210, 230)); - break; - case gpIon: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 10, 10)); - setColorStopAt(0.45, QColor(0, 0, 255)); - setColorStopAt(0.8, QColor(0, 255, 255)); - setColorStopAt(1, QColor(0, 255, 0)); - break; - case gpThermal: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.15, QColor(20, 0, 120)); - setColorStopAt(0.33, QColor(200, 30, 140)); - setColorStopAt(0.6, QColor(255, 100, 0)); - setColorStopAt(0.85, QColor(255, 255, 40)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpPolar: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 255, 255)); - setColorStopAt(0.18, QColor(10, 70, 255)); - setColorStopAt(0.28, QColor(10, 10, 190)); - setColorStopAt(0.5, QColor(0, 0, 0)); - setColorStopAt(0.72, QColor(190, 10, 10)); - setColorStopAt(0.82, QColor(255, 70, 10)); - setColorStopAt(1, QColor(255, 255, 50)); - break; - case gpSpectrum: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 0, 50)); - setColorStopAt(0.15, QColor(0, 0, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.6, QColor(255, 255, 0)); - setColorStopAt(0.75, QColor(255, 30, 0)); - setColorStopAt(1, QColor(50, 0, 0)); - break; - case gpJet: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 100)); - setColorStopAt(0.15, QColor(0, 50, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.65, QColor(255, 255, 0)); - setColorStopAt(0.85, QColor(255, 30, 0)); - setColorStopAt(1, QColor(100, 0, 0)); - break; - case gpHues: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(255, 0, 0)); - setColorStopAt(1.0/3.0, QColor(0, 0, 255)); - setColorStopAt(2.0/3.0, QColor(0, 255, 0)); - setColorStopAt(1, QColor(255, 0, 0)); - break; - } -} - -/*! - Clears all color stops. - - \see setColorStops, setColorStopAt -*/ -void QCPColorGradient::clearColorStops() -{ - mColorStops.clear(); - mColorBufferInvalidated = true; -} - -/*! - Returns an inverted gradient. The inverted gradient has all properties as this \ref - QCPColorGradient, but the order of the color stops is inverted. - - \see setColorStops, setColorStopAt -*/ -QCPColorGradient QCPColorGradient::inverted() const -{ - QCPColorGradient result(*this); - result.clearColorStops(); - for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) - result.setColorStopAt(1.0-it.key(), it.value()); - return result; -} - -/*! \internal - - Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly - convert positions to colors. This is where the interpolation between color stops is calculated. -*/ -void QCPColorGradient::updateColorBuffer() -{ - if (mColorBuffer.size() != mLevelCount) - mColorBuffer.resize(mLevelCount); - if (mColorStops.size() > 1) - { - double indexToPosFactor = 1.0/(double)(mLevelCount-1); - for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); - if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop - { - mColorBuffer[i] = (it-1).value().rgb(); - } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop - { - mColorBuffer[i] = it.value().rgb(); - } else // position is in between stops (or on an intermediate stop), interpolate color - { - QMap::const_iterator high = it; - QMap::const_iterator low = it-1; - double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 - switch (mColorInterpolation) - { - case ciRGB: - { - mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), - (1-t)*low.value().green() + t*high.value().green(), - (1-t)*low.value().blue() + t*high.value().blue()); - break; - } - case ciHSV: - { - QColor lowHsv = low.value().toHsv(); - QColor highHsv = high.value().toHsv(); - double hue = 0; - double hueDiff = highHsv.hueF()-lowHsv.hueF(); - if (hueDiff > 0.5) - hue = lowHsv.hueF() - t*(1.0-hueDiff); - else if (hueDiff < -0.5) - hue = lowHsv.hueF() + t*(1.0+hueDiff); - else - hue = lowHsv.hueF() + t*hueDiff; - if (hue < 0) hue += 1.0; - else if (hue >= 1.0) hue -= 1.0; - mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); - break; - } - } - } - } - } else if (mColorStops.size() == 1) - { - mColorBuffer.fill(mColorStops.constBegin().value().rgb()); - } else // mColorStops is empty, fill color buffer with black - { - mColorBuffer.fill(qRgb(0, 0, 0)); - } - mColorBufferInvalidated = false; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAxisRect -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAxisRect - \brief Holds multiple axes and arranges them in a rectangular shape. - - This class represents an axis rect, a rectangular area that is bounded on all sides with an - arbitrary number of axes. - - Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the - layout system allows to have multiple axis rects, e.g. arranged in a grid layout - (QCustomPlot::plotLayout). - - By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be - accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. - If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be - invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref - addAxes. To remove an axis, use \ref removeAxis. - - The axis rect layerable itself only draws a background pixmap or color, if specified (\ref - setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an - explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be - placed on other layers, independently of the axis rect. - - Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref - insetLayout and can be used to have other layout elements (or even other layouts with multiple - elements) hovering inside the axis rect. - - If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The - behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel - is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable - via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are - only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref - QCP::iRangeZoom. - - \image html AxisRectSpacingOverview.png -
Overview of the spacings and paddings that define the geometry of an axis. The dashed - line on the far left indicates the viewport/widget border.
-*/ - -/* start documentation of inline functions */ - -/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const - - Returns the inset layout of this axis rect. It can be used to place other layout elements (or - even layouts with multiple other elements) inside/on top of an axis rect. - - \see QCPLayoutInset -*/ - -/*! \fn int QCPAxisRect::left() const - - Returns the pixel position of the left border of this axis rect. Margins are not taken into - account here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn int QCPAxisRect::right() const - - Returns the pixel position of the right border of this axis rect. Margins are not taken into - account here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn int QCPAxisRect::top() const - - Returns the pixel position of the top border of this axis rect. Margins are not taken into - account here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn int QCPAxisRect::bottom() const - - Returns the pixel position of the bottom border of this axis rect. Margins are not taken into - account here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn int QCPAxisRect::width() const - - Returns the pixel width of this axis rect. Margins are not taken into account here, so the - returned value is with respect to the inner \ref rect. -*/ - -/*! \fn int QCPAxisRect::height() const - - Returns the pixel height of this axis rect. Margins are not taken into account here, so the - returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QSize QCPAxisRect::size() const - - Returns the pixel size of this axis rect. Margins are not taken into account here, so the - returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QPoint QCPAxisRect::topLeft() const - - Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, - so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QPoint QCPAxisRect::topRight() const - - Returns the top right corner of this axis rect in pixels. Margins are not taken into account - here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QPoint QCPAxisRect::bottomLeft() const - - Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account - here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QPoint QCPAxisRect::bottomRight() const - - Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account - here, so the returned value is with respect to the inner \ref rect. -*/ - -/*! \fn QPoint QCPAxisRect::center() const - - Returns the center of this axis rect in pixels. Margins are not taken into account here, so the - returned value is with respect to the inner \ref rect. -*/ - -/* end documentation of inline functions */ - -/*! - Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four - sides, the top and right axes are set invisible initially. -*/ -QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : - QCPLayoutElement(parentPlot), - mBackgroundBrush(Qt::NoBrush), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mInsetLayout(new QCPLayoutInset), - mRangeDrag(Qt::Horizontal|Qt::Vertical), - mRangeZoom(Qt::Horizontal|Qt::Vertical), - mRangeZoomFactorHorz(0.85), - mRangeZoomFactorVert(0.85), - mDragging(false) -{ - mInsetLayout->initializeParentPlot(mParentPlot); - mInsetLayout->setParentLayerable(this); - mInsetLayout->setParent(this); - - setMinimumSize(50, 50); - setMinimumMargins(QMargins(15, 15, 15, 15)); - mAxes.insert(QCPAxis::atLeft, QList()); - mAxes.insert(QCPAxis::atRight, QList()); - mAxes.insert(QCPAxis::atTop, QList()); - mAxes.insert(QCPAxis::atBottom, QList()); - - if (setupDefaultAxes) - { - QCPAxis *xAxis = addAxis(QCPAxis::atBottom); - QCPAxis *yAxis = addAxis(QCPAxis::atLeft); - QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); - QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); - setRangeDragAxes(xAxis, yAxis); - setRangeZoomAxes(xAxis, yAxis); - xAxis2->setVisible(false); - yAxis2->setVisible(false); - xAxis->grid()->setVisible(true); - yAxis->grid()->setVisible(true); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - xAxis2->grid()->setZeroLinePen(Qt::NoPen); - yAxis2->grid()->setZeroLinePen(Qt::NoPen); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - } -} - -QCPAxisRect::~QCPAxisRect() -{ - delete mInsetLayout; - mInsetLayout = 0; - - QList axesList = axes(); - for (int i=0; i ax(mAxes.value(type)); - if (index >= 0 && index < ax.size()) - { - return ax.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; - return 0; - } -} - -/*! - Returns all axes on the axis rect sides specified with \a types. - - \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of - multiple sides. - - \see axis -*/ -QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const -{ - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << mAxes.value(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << mAxes.value(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << mAxes.value(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << mAxes.value(QCPAxis::atBottom); - return result; -} - -/*! \overload - - Returns all axes of this axis rect. -*/ -QList QCPAxisRect::axes() const -{ - QList result; - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - result << it.value(); - } - return result; -} - -/*! - Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a - new QCPAxis instance is created internally. - - You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was - previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership - of the axis, so you may not delete it afterwards. Further, the \a axis must have been created - with this axis rect as parent and with the same axis type as specified in \a type. If this is not - the case, a debug output is generated, the axis is not added, and the method returns 0. - - This method can not be used to move \a axis between axis rects. The same \a axis instance must - not be added multiple times to the same or different axis rects. - - If an axis rect side already contains one or more axes, the lower and upper endings of the new - axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref - QCPLineEnding::esHalfBar. - - \see addAxes, setupFullAxesBox -*/ -QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) -{ - QCPAxis *newAxis = axis; - if (!newAxis) - { - newAxis = new QCPAxis(this, type); - } else // user provided existing axis instance, do some sanity checks - { - if (newAxis->axisType() != type) - { - qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; - return 0; - } - if (newAxis->axisRect() != this) - { - qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; - return 0; - } - if (axes().contains(newAxis)) - { - qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; - return 0; - } - } - if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset - { - bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); - newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); - newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); - } - mAxes[type].append(newAxis); - return newAxis; -} - -/*! - Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an - or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. - - Returns a list of the added axes. - - \see addAxis, setupFullAxesBox -*/ -QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) -{ - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << addAxis(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << addAxis(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << addAxis(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << addAxis(QCPAxis::atBottom); - return result; -} - -/*! - Removes the specified \a axis from the axis rect and deletes it. - - Returns true on success, i.e. if \a axis was a valid axis in this axis rect. - - \see addAxis -*/ -bool QCPAxisRect::removeAxis(QCPAxis *axis) -{ - // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - if (it.value().contains(axis)) - { - mAxes[it.key()].removeOne(axis); - if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) - parentPlot()->axisRemoved(axis); - delete axis; - return true; - } - } - qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); - return false; -} - -/*! - Convenience function to create an axis on each side that doesn't have any axes yet and set their - visibility to true. Further, the top/right axes are assigned the following properties of the - bottom/left axes: - - \li range (\ref QCPAxis::setRange) - \li range reversed (\ref QCPAxis::setRangeReversed) - \li scale type (\ref QCPAxis::setScaleType) - \li scale log base (\ref QCPAxis::setScaleLogBase) - \li ticks (\ref QCPAxis::setTicks) - \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) - \li sub tick count (\ref QCPAxis::setSubTickCount) - \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) - \li tick step (\ref QCPAxis::setTickStep) - \li auto tick step (\ref QCPAxis::setAutoTickStep) - \li number format (\ref QCPAxis::setNumberFormat) - \li number precision (\ref QCPAxis::setNumberPrecision) - \li tick label type (\ref QCPAxis::setTickLabelType) - \li date time format (\ref QCPAxis::setDateTimeFormat) - \li date time spec (\ref QCPAxis::setDateTimeSpec) - - Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. - - If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom - and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. -*/ -void QCPAxisRect::setupFullAxesBox(bool connectRanges) -{ - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - if (axisCount(QCPAxis::atBottom) == 0) - xAxis = addAxis(QCPAxis::atBottom); - else - xAxis = axis(QCPAxis::atBottom); - - if (axisCount(QCPAxis::atLeft) == 0) - yAxis = addAxis(QCPAxis::atLeft); - else - yAxis = axis(QCPAxis::atLeft); - - if (axisCount(QCPAxis::atTop) == 0) - xAxis2 = addAxis(QCPAxis::atTop); - else - xAxis2 = axis(QCPAxis::atTop); - - if (axisCount(QCPAxis::atRight) == 0) - yAxis2 = addAxis(QCPAxis::atRight); - else - yAxis2 = axis(QCPAxis::atRight); - - xAxis->setVisible(true); - yAxis->setVisible(true); - xAxis2->setVisible(true); - yAxis2->setVisible(true); - xAxis2->setTickLabels(false); - yAxis2->setTickLabels(false); - - xAxis2->setRange(xAxis->range()); - xAxis2->setRangeReversed(xAxis->rangeReversed()); - xAxis2->setScaleType(xAxis->scaleType()); - xAxis2->setScaleLogBase(xAxis->scaleLogBase()); - xAxis2->setTicks(xAxis->ticks()); - xAxis2->setAutoTickCount(xAxis->autoTickCount()); - xAxis2->setSubTickCount(xAxis->subTickCount()); - xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); - xAxis2->setTickStep(xAxis->tickStep()); - xAxis2->setAutoTickStep(xAxis->autoTickStep()); - xAxis2->setNumberFormat(xAxis->numberFormat()); - xAxis2->setNumberPrecision(xAxis->numberPrecision()); - xAxis2->setTickLabelType(xAxis->tickLabelType()); - xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); - xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); - - yAxis2->setRange(yAxis->range()); - yAxis2->setRangeReversed(yAxis->rangeReversed()); - yAxis2->setScaleType(yAxis->scaleType()); - yAxis2->setScaleLogBase(yAxis->scaleLogBase()); - yAxis2->setTicks(yAxis->ticks()); - yAxis2->setAutoTickCount(yAxis->autoTickCount()); - yAxis2->setSubTickCount(yAxis->subTickCount()); - yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); - yAxis2->setTickStep(yAxis->tickStep()); - yAxis2->setAutoTickStep(yAxis->autoTickStep()); - yAxis2->setNumberFormat(yAxis->numberFormat()); - yAxis2->setNumberPrecision(yAxis->numberPrecision()); - yAxis2->setTickLabelType(yAxis->tickLabelType()); - yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); - yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); - - if (connectRanges) - { - connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); - connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); - } -} - -/*! - Returns a list of all the plottables that are associated with this axis rect. - - A plottable is considered associated with an axis rect if its key or value axis (or both) is in - this axis rect. - - \see graphs, items -*/ -QList QCPAxisRect::plottables() const -{ - // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries - QList result; - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; -} - -/*! - Returns a list of all the graphs that are associated with this axis rect. - - A graph is considered associated with an axis rect if its key or value axis (or both) is in - this axis rect. - - \see plottables, items -*/ -QList QCPAxisRect::graphs() const -{ - // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries - QList result; - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; -} - -/*! - Returns a list of all the items that are associated with this axis rect. - - An item is considered associated with an axis rect if any of its positions has key or value axis - set to an axis that is in this axis rect, or if any of its positions has \ref - QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref - QCPAbstractItem::setClipAxisRect) is set to this axis rect. - - \see plottables, graphs -*/ -QList QCPAxisRect::items() const -{ - // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries - // and miss those items that have this axis rect as clipAxisRect. - QList result; - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - continue; - } - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdaxisRect() == this || - positions.at(posId)->keyAxis()->axisRect() == this || - positions.at(posId)->valueAxis()->axisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } - } - } - return result; -} - -/*! - This method is called automatically upon replot and doesn't need to be called by users of - QCPAxisRect. - - Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), - and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its - QCPInsetLayout::update function. -*/ -void QCPAxisRect::update(UpdatePhase phase) -{ - QCPLayoutElement::update(phase); - - switch (phase) - { - case upPreparation: - { - QList allAxes = axes(); - for (int i=0; isetupTickVectors(); - break; - } - case upLayout: - { - mInsetLayout->setOuterRect(rect()); - break; - } - default: break; - } - - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): - mInsetLayout->update(phase); -} - -/* inherits documentation from base class */ -QList QCPAxisRect::elements(bool recursive) const -{ - QList result; - if (mInsetLayout) - { - result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); - } - return result; -} - -/* inherits documentation from base class */ -void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - painter->setAntialiasing(false); -} - -/* inherits documentation from base class */ -void QCPAxisRect::draw(QCPPainter *painter) -{ - drawBackground(painter); -} - -/*! - Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the - axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect - backgrounds are usually drawn below everything else. - - For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be - enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio - is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, - consider using the overloaded version of this function. - - Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref - setBackground(const QBrush &brush). - - \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) -*/ -void QCPAxisRect::setBackground(const QPixmap &pm) -{ - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); -} - -/*! \overload - - Sets \a brush as the background brush. The axis rect background will be filled with this brush. - Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds - are usually drawn below everything else. - - The brush will be drawn before (under) any background pixmap, which may be specified with \ref - setBackground(const QPixmap &pm). - - To disable drawing of a background brush, set \a brush to Qt::NoBrush. - - \see setBackground(const QPixmap &pm) -*/ -void QCPAxisRect::setBackground(const QBrush &brush) -{ - mBackgroundBrush = brush; -} - -/*! \overload - - Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it - shall be scaled in one call. - - \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode -*/ -void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) -{ - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; -} - -/*! - Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled - is set to true, you may control whether and how the aspect ratio of the original pixmap is - preserved with \ref setBackgroundScaledMode. - - Note that the scaled version of the original pixmap is buffered, so there is no performance - penalty on replots. (Except when the axis rect dimensions are changed continuously.) - - \see setBackground, setBackgroundScaledMode -*/ -void QCPAxisRect::setBackgroundScaled(bool scaled) -{ - mBackgroundScaled = scaled; -} - -/*! - If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to - define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. - \see setBackground, setBackgroundScaled -*/ -void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) -{ - mBackgroundScaledMode = mode; -} - -/*! - Returns the range drag axis of the \a orientation provided. - - \see setRangeDragAxes -*/ -QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) -{ - return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); -} - -/*! - Returns the range zoom axis of the \a orientation provided. - - \see setRangeZoomAxes -*/ -QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) -{ - return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); -} - -/*! - Returns the range zoom factor of the \a orientation provided. - - \see setRangeZoomFactor -*/ -double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) -{ - return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); -} - -/*! - Sets which axis orientation may be range dragged by the user with mouse interaction. - What orientation corresponds to which specific axis can be set with - \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By - default, the horizontal axis is the bottom axis (xAxis) and the vertical axis - is the left axis (yAxis). - - To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref - QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | - Qt::Vertical as \a orientations. - - In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions - contains \ref QCP::iRangeDrag to enable the range dragging interaction. - - \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag -*/ -void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) -{ - mRangeDrag = orientations; -} - -/*! - Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation - corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, - QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical - axis is the left axis (yAxis). - - To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref - QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | - Qt::Vertical as \a orientations. - - In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions - contains \ref QCP::iRangeZoom to enable the range zooming interaction. - - \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag -*/ -void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) -{ - mRangeZoom = orientations; -} - -/*! - Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging - on the QCustomPlot widget. - - \see setRangeZoomAxes -*/ -void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) -{ - mRangeDragHorzAxis = horizontal; - mRangeDragVertAxis = vertical; -} - -/*! - Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the - QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors - are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). - - \see setRangeDragAxes -*/ -void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) -{ - mRangeZoomHorzAxis = horizontal; - mRangeZoomVertAxis = vertical; -} - -/*! - Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with - \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to - let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal - and which is vertical, can be set with \ref setRangeZoomAxes. - - When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) - will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the - same scrolling direction will zoom out. -*/ -void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) -{ - mRangeZoomFactorHorz = horizontalFactor; - mRangeZoomFactorVert = verticalFactor; -} - -/*! \overload - - Sets both the horizontal and vertical zoom \a factor. -*/ -void QCPAxisRect::setRangeZoomFactor(double factor) -{ - mRangeZoomFactorHorz = factor; - mRangeZoomFactorVert = factor; -} - -/*! \internal - - Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a - pixmap. - - If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an - according filling inside the axis rect with the provided \a painter. - - Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version - depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside - the axis rect with the provided \a painter. The scaled version is buffered in - mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when - the axis rect has changed in a way that requires a rescale of the background pixmap (this is - dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was - set. - - \see setBackground, setBackgroundScaled, setBackgroundScaledMode -*/ -void QCPAxisRect::drawBackground(QCPPainter *painter) -{ - // draw background fill: - if (mBackgroundBrush != Qt::NoBrush) - painter->fillRect(mRect, mBackgroundBrush); - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mRect.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); - } - } -} - -/*! \internal - - This function makes sure multiple axes on the side specified with \a type don't collide, but are - distributed according to their respective space requirement (QCPAxis::calculateMargin). - - It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the - one with index zero. - - This function is called by \ref calculateAutoMargin. -*/ -void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) -{ - const QList axesList = mAxes.value(type); - if (axesList.isEmpty()) - return; - - bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false - for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); - if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) - { - if (!isFirstVisible) - offset += axesList.at(i)->tickLengthIn(); - isFirstVisible = false; - } - axesList.at(i)->setOffset(offset); - } -} - -/* inherits documentation from base class */ -int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) -{ - if (!mAutoMargins.testFlag(side)) - qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; - - updateAxesOffset(QCPAxis::marginSideToAxisType(side)); - - // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call - const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); - if (axesList.size() > 0) - return axesList.last()->offset() + axesList.last()->calculateMargin(); - else - return 0; -} - -/*! \internal - - Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is - pressed, the range dragging interaction is initialized (the actual range manipulation happens in - the \ref mouseMoveEvent). - - The mDragging flag is set to true and some anchor points are set that are needed to determine the - distance the mouse was dragged in the mouse move/release events later. - - \see mouseMoveEvent, mouseReleaseEvent -*/ -void QCPAxisRect::mousePressEvent(QMouseEvent *event) -{ - mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); - } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - if (mRangeDragHorzAxis) - mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); - if (mRangeDragVertAxis) - mDragStartVertRange = mRangeDragVertAxis.data()->range(); - } - } -} - -/*! \internal - - Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a - preceding \ref mousePressEvent, the range is moved accordingly. - - \see mousePressEvent, mouseReleaseEvent -*/ -void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) -{ - // Mouse range dragging interaction: - if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - if (mRangeDrag.testFlag(Qt::Horizontal)) - { - if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) - { - if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) - { - double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); - rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); - } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) - { - double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); - rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); - } - } - } - if (mRangeDrag.testFlag(Qt::Vertical)) - { - if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) - { - if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) - { - double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); - rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); - } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) - { - double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); - rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); - } - } - } - if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot - { - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(); - } - } -} - -/* inherits documentation from base class */ -void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) -{ - Q_UNUSED(event) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } -} - -/*! \internal - - Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the - ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of - the scaling operation is the current cursor position inside the axis rect. The scaling factor is - dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural - zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. - - Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse - wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be - multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as - exponent of the range zoom factor. This takes care of the wheel direction automatically, by - inverting the factor, when the wheel step is negative (f^-1 = 1/f). -*/ -void QCPAxisRect::wheelEvent(QWheelEvent *event) -{ - // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { - if (mRangeZoom != 0) - { - double factor; - double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - if (mRangeZoom.testFlag(Qt::Horizontal)) - { - factor = qPow(mRangeZoomFactorHorz, wheelSteps); - if (mRangeZoomHorzAxis.data()) - mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); - } - if (mRangeZoom.testFlag(Qt::Vertical)) - { - factor = qPow(mRangeZoomFactorVert, wheelSteps); - if (mRangeZoomVertAxis.data()) - mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); - } - mParentPlot->replot(); - } - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPAbstractLegendItem -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPAbstractLegendItem - \brief The abstract base class for all entries in a QCPLegend. - - It defines a very basic interface for entries in a QCPLegend. For representing plottables in the - legend, the subclass \ref QCPPlottableLegendItem is more suitable. - - Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry - that's not even associated with a plottable). - - You must implement the following pure virtual functions: - \li \ref draw (from QCPLayerable) - - You inherit the following members you may use: - - - - - - - - -
QCPLegend *\b mParentLegendA pointer to the parent QCPLegend.
QFont \b mFontThe generic font of the item. You should use this font for all or at least the most prominent text of the item.
-*/ - -/* start of documentation of signals */ - -/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) - - This signal is emitted when the selection state of this legend item has changed, either by user - interaction or by a direct call to \ref setSelected. -*/ - -/* end of documentation of signals */ - -/*! - Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not - cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. -*/ -QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : - QCPLayoutElement(parent->parentPlot()), - mParentLegend(parent), - mFont(parent->font()), - mTextColor(parent->textColor()), - mSelectedFont(parent->selectedFont()), - mSelectedTextColor(parent->selectedTextColor()), - mSelectable(true), - mSelected(false) -{ - setLayer(QLatin1String("legend")); - setMargins(QMargins(8, 2, 8, 2)); -} - -/*! - Sets the default font of this specific legend item to \a font. - - \see setTextColor, QCPLegend::setFont -*/ -void QCPAbstractLegendItem::setFont(const QFont &font) -{ - mFont = font; -} - -/*! - Sets the default text color of this specific legend item to \a color. - - \see setFont, QCPLegend::setTextColor -*/ -void QCPAbstractLegendItem::setTextColor(const QColor &color) -{ - mTextColor = color; -} - -/*! - When this legend item is selected, \a font is used to draw generic text, instead of the normal - font set with \ref setFont. - - \see setFont, QCPLegend::setSelectedFont -*/ -void QCPAbstractLegendItem::setSelectedFont(const QFont &font) -{ - mSelectedFont = font; -} - -/*! - When this legend item is selected, \a color is used to draw generic text, instead of the normal - color set with \ref setTextColor. - - \see setTextColor, QCPLegend::setSelectedTextColor -*/ -void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) -{ - mSelectedTextColor = color; -} - -/*! - Sets whether this specific legend item is selectable. - - \see setSelectedParts, QCustomPlot::setInteractions -*/ -void QCPAbstractLegendItem::setSelectable(bool selectable) -{ - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } -} - -/*! - Sets whether this specific legend item is selected. - - It is possible to set the selection state of this item by calling this function directly, even if - setSelectable is set to false. - - \see setSelectableParts, QCustomPlot::setInteractions -*/ -void QCPAbstractLegendItem::setSelected(bool selected) -{ - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } -} - -/* inherits documentation from base class */ -double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (!mParentPlot) return -1; - if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) - return -1; - - if (mRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; -} - -/* inherits documentation from base class */ -void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); -} - -/* inherits documentation from base class */ -QRect QCPAbstractLegendItem::clipRect() const -{ - return mOuterRect; -} - -/* inherits documentation from base class */ -void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) -{ - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPPlottableLegendItem -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPPlottableLegendItem - \brief A legend item representing a plottable with an icon and the plottable name. - - This is the standard legend item for plottables. It displays an icon of the plottable next to the - plottable name. The icon is drawn by the respective plottable itself (\ref - QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. - For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the - middle. - - Legend items of this type are always associated with one plottable (retrievable via the - plottable() function and settable with the constructor). You may change the font of the plottable - name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref - QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. - - The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend - creates/removes legend items of this type in the default implementation. However, these functions - may be reimplemented such that a different kind of legend item (e.g a direct subclass of - QCPAbstractLegendItem) is used for that plottable. - - Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of - QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout - interface, QCPLegend has specialized functions for handling legend items conveniently, see the - documentation of \ref QCPLegend. -*/ - -/*! - Creates a new legend item associated with \a plottable. - - Once it's created, it can be added to the legend via \ref QCPLegend::addItem. - - A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref - QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. -*/ -QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : - QCPAbstractLegendItem(parent), - mPlottable(plottable) -{ -} - -/*! \internal - - Returns the pen that shall be used to draw the icon border, taking into account the selection - state of this item. -*/ -QPen QCPPlottableLegendItem::getIconBorderPen() const -{ - return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); -} - -/*! \internal - - Returns the text color that shall be used to draw text, taking into account the selection state - of this item. -*/ -QColor QCPPlottableLegendItem::getTextColor() const -{ - return mSelected ? mSelectedTextColor : mTextColor; -} - -/*! \internal - - Returns the font that shall be used to draw text, taking into account the selection state of this - item. -*/ -QFont QCPPlottableLegendItem::getFont() const -{ - return mSelected ? mSelectedFont : mFont; -} - -/*! \internal - - Draws the item with \a painter. The size and position of the drawn legend item is defined by the - parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint - of this legend item. -*/ -void QCPPlottableLegendItem::draw(QCPPainter *painter) -{ - if (!mPlottable) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); - QSizeF iconSize = mParentLegend->iconSize(); - QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - QRectF iconRect(mRect.topLeft(), iconSize); - int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops - painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); - // draw icon: - painter->save(); - painter->setClipRect(iconRect, Qt::IntersectClip); - mPlottable->drawLegendIcon(painter, iconRect); - painter->restore(); - // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) - { - painter->setPen(getIconBorderPen()); - painter->setBrush(Qt::NoBrush); - painter->drawRect(iconRect); - } -} - -/*! \internal - - Calculates and returns the size of this item. This includes the icon, the text and the padding in - between. -*/ -QSize QCPPlottableLegendItem::minimumSizeHint() const -{ - if (!mPlottable) return QSize(); - QSize result(0, 0); - QRect textRect; - QFontMetrics fontMetrics(getFont()); - QSize iconSize = mParentLegend->iconSize(); - textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); - result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); - return result; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPLegend -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPLegend - \brief Manages a legend inside a QCustomPlot. - - A legend is a small box somewhere in the plot which lists plottables with their name and icon. - - Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The - respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, - QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref - itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. - - The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a - QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are - placed in the grid layout of the legend. QCPLegend only adds an interface specialized for - handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any - other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. - However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will - only return the number of items with QCPAbstractLegendItems type). - - By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset - layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another - position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend - outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. -*/ - -/* start of documentation of signals */ - -/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); - - This signal is emitted when the selection state of this legend has changed. - - \see setSelectedParts, setSelectableParts -*/ - -/* end of documentation of signals */ - -/*! - Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. - - Note that by default, QCustomPlot already contains a legend ready to be used as - QCustomPlot::legend -*/ -QCPLegend::QCPLegend() -{ - setRowSpacing(0); - setColumnSpacing(10); - setMargins(QMargins(2, 3, 2, 2)); - setAntialiased(false); - setIconSize(32, 18); - - setIconTextPadding(7); - - setSelectableParts(spLegendBox | spItems); - setSelectedParts(spNone); - - setBorderPen(QPen(Qt::black)); - setSelectedBorderPen(QPen(Qt::blue, 2)); - setIconBorderPen(Qt::NoPen); - setSelectedIconBorderPen(QPen(Qt::blue, 2)); - setBrush(Qt::white); - setSelectedBrush(Qt::white); - setTextColor(Qt::black); - setSelectedTextColor(Qt::blue); -} - -QCPLegend::~QCPLegend() -{ - clearItems(); - if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) - mParentPlot->legendRemoved(this); -} - -/* no doc for getter, see setSelectedParts */ -QCPLegend::SelectableParts QCPLegend::selectedParts() const -{ - // check whether any legend elements selected, if yes, add spItems to return value - bool hasSelectedItems = false; - for (int i=0; iselected()) - { - hasSelectedItems = true; - break; - } - } - if (hasSelectedItems) - return mSelectedParts | spItems; - else - return mSelectedParts & ~spItems; -} - -/*! - Sets the pen, the border of the entire legend is drawn with. -*/ -void QCPLegend::setBorderPen(const QPen &pen) -{ - mBorderPen = pen; -} - -/*! - Sets the brush of the legend background. -*/ -void QCPLegend::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will - use this font by default. However, a different font can be specified on a per-item-basis by - accessing the specific legend item. - - This function will also set \a font on all already existing legend items. - - \see QCPAbstractLegendItem::setFont -*/ -void QCPLegend::setFont(const QFont &font) -{ - mFont = font; - for (int i=0; isetFont(mFont); - } -} - -/*! - Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) - will use this color by default. However, a different colors can be specified on a per-item-basis - by accessing the specific legend item. - - This function will also set \a color on all already existing legend items. - - \see QCPAbstractLegendItem::setTextColor -*/ -void QCPLegend::setTextColor(const QColor &color) -{ - mTextColor = color; - for (int i=0; isetTextColor(color); - } -} - -/*! - Sets the size of legend icons. Legend items that draw an icon (e.g. a visual - representation of the graph) will use this size by default. -*/ -void QCPLegend::setIconSize(const QSize &size) -{ - mIconSize = size; -} - -/*! \overload -*/ -void QCPLegend::setIconSize(int width, int height) -{ - mIconSize.setWidth(width); - mIconSize.setHeight(height); -} - -/*! - Sets the horizontal space in pixels between the legend icon and the text next to it. - Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the - name of the graph) will use this space by default. -*/ -void QCPLegend::setIconTextPadding(int padding) -{ - mIconTextPadding = padding; -} - -/*! - Sets the pen used to draw a border around each legend icon. Legend items that draw an - icon (e.g. a visual representation of the graph) will use this pen by default. - - If no border is wanted, set this to \a Qt::NoPen. -*/ -void QCPLegend::setIconBorderPen(const QPen &pen) -{ - mIconBorderPen = pen; -} - -/*! - Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. - (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) - - However, even when \a selectable is set to a value not allowing the selection of a specific part, - it is still possible to set the selection of this part manually, by calling \ref setSelectedParts - directly. - - \see SelectablePart, setSelectedParts -*/ -void QCPLegend::setSelectableParts(const SelectableParts &selectable) -{ - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } -} - -/*! - Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part - is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected - doesn't contain \ref spItems, those items become deselected. - - The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions - contains iSelectLegend. You only need to call this function when you wish to change the selection - state manually. - - This function can change the selection state of a part even when \ref setSelectableParts was set to a - value that actually excludes the part. - - emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - - Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set - before, because there's no way to specify which exact items to newly select. Do this by calling - \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. - - \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, - setSelectedFont -*/ -void QCPLegend::setSelectedParts(const SelectableParts &selected) -{ - SelectableParts newSelected = selected; - mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed - - if (mSelectedParts != newSelected) - { - if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) - { - qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; - newSelected &= ~spItems; - } - if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection - { - for (int i=0; isetSelected(false); - } - } - mSelectedParts = newSelected; - emit selectionChanged(mSelectedParts); - } -} - -/*! - When the legend box is selected, this pen is used to draw the border instead of the normal pen - set via \ref setBorderPen. - - \see setSelectedParts, setSelectableParts, setSelectedBrush -*/ -void QCPLegend::setSelectedBorderPen(const QPen &pen) -{ - mSelectedBorderPen = pen; -} - -/*! - Sets the pen legend items will use to draw their icon borders, when they are selected. - - \see setSelectedParts, setSelectableParts, setSelectedFont -*/ -void QCPLegend::setSelectedIconBorderPen(const QPen &pen) -{ - mSelectedIconBorderPen = pen; -} - -/*! - When the legend box is selected, this brush is used to draw the legend background instead of the normal brush - set via \ref setBrush. - - \see setSelectedParts, setSelectableParts, setSelectedBorderPen -*/ -void QCPLegend::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/*! - Sets the default font that is used by legend items when they are selected. - - This function will also set \a font on all already existing legend items. - - \see setFont, QCPAbstractLegendItem::setSelectedFont -*/ -void QCPLegend::setSelectedFont(const QFont &font) -{ - mSelectedFont = font; - for (int i=0; isetSelectedFont(font); - } -} - -/*! - Sets the default text color that is used by legend items when they are selected. - - This function will also set \a color on all already existing legend items. - - \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor -*/ -void QCPLegend::setSelectedTextColor(const QColor &color) -{ - mSelectedTextColor = color; - for (int i=0; isetSelectedTextColor(color); - } -} - -/*! - Returns the item with index \a i. - - \see itemCount -*/ -QCPAbstractLegendItem *QCPLegend::item(int index) const -{ - return qobject_cast(elementAt(index)); -} - -/*! - Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). - If such an item isn't in the legend, returns 0. - - \see hasItemWithPlottable -*/ -QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const -{ - for (int i=0; i(item(i))) - { - if (pli->plottable() == plottable) - return pli; - } - } - return 0; -} - -/*! - Returns the number of items currently in the legend. - \see item -*/ -int QCPLegend::itemCount() const -{ - return elementCount(); -} - -/*! - Returns whether the legend contains \a itm. -*/ -bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const -{ - for (int i=0; iitem(i)) - return true; - } - return false; -} - -/*! - Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). - If such an item isn't in the legend, returns false. - - \see itemWithPlottable -*/ -bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const -{ - return itemWithPlottable(plottable); -} - -/*! - Adds \a item to the legend, if it's not present already. - - Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. - - The legend takes ownership of the item. -*/ -bool QCPLegend::addItem(QCPAbstractLegendItem *item) -{ - if (!hasItem(item)) - { - return addElement(rowCount(), 0, item); - } else - return false; -} - -/*! - Removes the item with index \a index from the legend. - - Returns true, if successful. - - \see itemCount, clearItems -*/ -bool QCPLegend::removeItem(int index) -{ - if (QCPAbstractLegendItem *ali = item(index)) - { - bool success = remove(ali); - simplify(); - return success; - } else - return false; -} - -/*! \overload - - Removes \a item from the legend. - - Returns true, if successful. - - \see clearItems -*/ -bool QCPLegend::removeItem(QCPAbstractLegendItem *item) -{ - bool success = remove(item); - simplify(); - return success; -} - -/*! - Removes all items from the legend. -*/ -void QCPLegend::clearItems() -{ - for (int i=itemCount()-1; i>=0; --i) - removeItem(i); -} - -/*! - Returns the legend items that are currently selected. If no items are selected, - the list is empty. - - \see QCPAbstractLegendItem::setSelected, setSelectable -*/ -QList QCPLegend::selectedItems() const -{ - QList result; - for (int i=0; iselected()) - result.append(ali); - } - } - return result; -} - -/*! \internal - - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter - before drawing main legend elements. - - This is the antialiasing state the painter passed to the \ref draw method is in by default. - - This function takes into account the local setting of the antialiasing flag as well as the - overrides set with \ref QCustomPlot::setAntialiasedElements and \ref - QCustomPlot::setNotAntialiasedElements. - - \see setAntialiased -*/ -void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); -} - -/*! \internal - - Returns the pen used to paint the border of the legend, taking into account the selection state - of the legend box. -*/ -QPen QCPLegend::getBorderPen() const -{ - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; -} - -/*! \internal - - Returns the brush used to paint the background of the legend, taking into account the selection - state of the legend box. -*/ -QBrush QCPLegend::getBrush() const -{ - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; -} - -/*! \internal - - Draws the legend box with the provided \a painter. The individual legend items are layerables - themselves, thus are drawn independently. -*/ -void QCPLegend::draw(QCPPainter *painter) -{ - // draw background rect: - painter->setBrush(getBrush()); - painter->setPen(getBorderPen()); - painter->drawRect(mOuterRect); -} - -/* inherits documentation from base class */ -double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - if (!mParentPlot) return -1; - if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) - return -1; - - if (mOuterRect.contains(pos.toPoint())) - { - if (details) details->setValue(spLegendBox); - return mParentPlot->selectionTolerance()*0.99; - } - return -1; -} - -/* inherits documentation from base class */ -void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - mSelectedParts = selectedParts(); // in case item selection has changed - if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPLegend::deselectEvent(bool *selectionStateChanged) -{ - mSelectedParts = selectedParts(); // in case item selection has changed - if (mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(selectedParts() & ~spLegendBox); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } -} - -/* inherits documentation from base class */ -QCP::Interaction QCPLegend::selectionCategory() const -{ - return QCP::iSelectLegend; -} - -/* inherits documentation from base class */ -QCP::Interaction QCPAbstractLegendItem::selectionCategory() const -{ - return QCP::iSelectLegend; -} - -/* inherits documentation from base class */ -void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) -{ - Q_UNUSED(parentPlot) -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPPlotTitle -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPPlotTitle - \brief A layout element displaying a plot title text - - The text may be specified with \ref setText, theformatting can be controlled with \ref setFont - and \ref setTextColor. - - A plot title can be added as follows: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation - - Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for - easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the - signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref - QCustomPlot::titleDoubleClick signal. -*/ - -/* start documentation of signals */ - -/*! \fn void QCPPlotTitle::selectionChanged(bool selected) - - This signal is emitted when the selection state has changed to \a selected, either by user - interaction or by a direct call to \ref setSelected. - - \see setSelected, setSelectable -*/ - -/* end documentation of signals */ - -/*! - Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). - - To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). -*/ -QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)), - mTextColor(Qt::black), - mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) -{ - if (parentPlot) - { - setLayer(parentPlot->currentLayer()); - mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); - mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); - } - setMargins(QMargins(5, 5, 5, 0)); -} - -/*! \overload - - Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. -*/ -QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : - QCPLayoutElement(parentPlot), - mText(text), - mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), - mTextColor(Qt::black), - mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) -{ - setLayer(QLatin1String("axes")); - setMargins(QMargins(5, 5, 5, 0)); -} - -/*! - Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". - - \see setFont, setTextColor -*/ -void QCPPlotTitle::setText(const QString &text) -{ - mText = text; -} - -/*! - Sets the \a font of the title text. - - \see setTextColor, setSelectedFont -*/ -void QCPPlotTitle::setFont(const QFont &font) -{ - mFont = font; -} - -/*! - Sets the \a color of the title text. - - \see setFont, setSelectedTextColor -*/ -void QCPPlotTitle::setTextColor(const QColor &color) -{ - mTextColor = color; -} - -/*! - Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). - - \see setFont -*/ -void QCPPlotTitle::setSelectedFont(const QFont &font) -{ - mSelectedFont = font; -} - -/*! - Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). - - \see setTextColor -*/ -void QCPPlotTitle::setSelectedTextColor(const QColor &color) -{ - mSelectedTextColor = color; -} - -/*! - Sets whether the user may select this plot title to \a selectable. - - Note that even when \a selectable is set to false, the selection state may be changed - programmatically via \ref setSelected. -*/ -void QCPPlotTitle::setSelectable(bool selectable) -{ - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } -} - -/*! - Sets the selection state of this plot title to \a selected. If the selection has changed, \ref - selectionChanged is emitted. - - Note that this function can change the selection state independently of the current \ref - setSelectable state. -*/ -void QCPPlotTitle::setSelected(bool selected) -{ - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } -} - -/* inherits documentation from base class */ -void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); -} - -/* inherits documentation from base class */ -void QCPPlotTitle::draw(QCPPainter *painter) -{ - painter->setFont(mainFont()); - painter->setPen(QPen(mainTextColor())); - painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); -} - -/* inherits documentation from base class */ -QSize QCPPlotTitle::minimumSizeHint() const -{ - QFontMetrics metrics(mFont); - QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); - result.rwidth() += mMargins.left() + mMargins.right(); - result.rheight() += mMargins.top() + mMargins.bottom(); - return result; -} - -/* inherits documentation from base class */ -QSize QCPPlotTitle::maximumSizeHint() const -{ - QFontMetrics metrics(mFont); - QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); - result.rheight() += mMargins.top() + mMargins.bottom(); - result.setWidth(QWIDGETSIZE_MAX); - return result; -} - -/* inherits documentation from base class */ -void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) -{ - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) -{ - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } -} - -/* inherits documentation from base class */ -double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - if (mTextBoundingRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; -} - -/*! \internal - - Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to - true, else mFont is returned. -*/ -QFont QCPPlotTitle::mainFont() const -{ - return mSelected ? mSelectedFont : mFont; -} - -/*! \internal - - Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to - true, else mTextColor is returned. -*/ -QColor QCPPlotTitle::mainTextColor() const -{ - return mSelected ? mSelectedTextColor : mTextColor; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPColorScale -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPColorScale - \brief A color scale for use with color coding data such as QCPColorMap - - This layout element can be placed on the plot to correlate a color gradient with data values. It - is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". - - \image html QCPColorScale.png - - The color scale can be either horizontal or vertical, as shown in the image above. The - orientation and the side where the numbers appear is controlled with \ref setType. - - Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are - connected, they share their gradient, data range and data scale type (\ref setGradient, \ref - setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color - scale, to make them all synchronize these properties. - - To have finer control over the number display and axis behaviour, you can directly access the - \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if - you want to change the number of automatically generated ticks, call - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount - - Placing a color scale next to the main axis rect works like with any other layout element: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation - In this case we have placed it to the right of the default axis rect, so it wasn't necessary to - call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color - scale can be set with \ref setLabel. - - For optimum appearance (like in the image above), it may be desirable to line up the axis rect and - the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup - - Color scales are initialized with a non-zero minimum top and bottom margin (\ref - setMinimumMargins), because vertical color scales are most common and the minimum top/bottom - margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a - horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you - might want to also change the minimum margins accordingly, e.g. setMinimumMargins(QMargins(6, 0, 6, 0)). -*/ - -/* start documentation of inline functions */ - -/*! \fn QCPAxis *QCPColorScale::axis() const - - Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the - appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its - interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref - setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref - QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on - the QCPColorScale or on its QCPAxis. - - If the type of the color scale is changed with \ref setType, the axis returned by this method - will change, too, to either the left, right, bottom or top axis, depending on which type was set. -*/ - -/* end documentation of signals */ -/* start documentation of signals */ - -/*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); - - This signal is emitted when the data range changes. - - \see setDataRange -*/ - -/*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - - This signal is emitted when the data scale type changes. - - \see setDataScaleType -*/ - -/*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); - - This signal is emitted when the gradient changes. - - \see setGradient -*/ - -/* end documentation of signals */ - -/*! - Constructs a new QCPColorScale. -*/ -QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight - mDataScaleType(QCPAxis::stLinear), - mBarWidth(20), - mAxisRect(new QCPColorScaleAxisRectPrivate(this)) -{ - setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) - setType(QCPAxis::atRight); - setDataRange(QCPRange(0, 6)); -} - -QCPColorScale::~QCPColorScale() -{ - delete mAxisRect; -} - -/* undocumented getter */ -QString QCPColorScale::label() const -{ - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return QString(); - } - - return mColorAxis.data()->label(); -} - -/* undocumented getter */ -bool QCPColorScale::rangeDrag() const -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); -} - -/* undocumented getter */ -bool QCPColorScale::rangeZoom() const -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); -} - -/*! - Sets at which side of the color scale the axis is placed, and thus also its orientation. - - Note that after setting \a type to a different value, the axis returned by \ref axis() will - be a different one. The new axis will adopt the following properties from the previous axis: The - range, scale type, log base and label. -*/ -void QCPColorScale::setType(QCPAxis::AxisType type) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - if (mType != type) - { - mType = type; - QCPRange rangeTransfer(0, 6); - double logBaseTransfer = 10; - QString labelTransfer; - // revert some settings on old axis: - if (mColorAxis) - { - rangeTransfer = mColorAxis.data()->range(); - labelTransfer = mColorAxis.data()->label(); - logBaseTransfer = mColorAxis.data()->scaleLogBase(); - mColorAxis.data()->setLabel(QString()); - disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } - QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; - foreach (QCPAxis::AxisType atype, allAxisTypes) - { - mAxisRect.data()->axis(atype)->setTicks(atype == mType); - mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); - } - // set new mColorAxis pointer: - mColorAxis = mAxisRect.data()->axis(mType); - // transfer settings to new axis: - mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) - mColorAxis.data()->setLabel(labelTransfer); - mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here - connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, - QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); - } -} - -/*! - Sets the range spanned by the color gradient and that is shown by the axis in the color scale. - - It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is - also equivalent to directly accessing the \ref axis and setting its range with \ref - QCPAxis::setRange. - - \see setDataScaleType, setGradient, rescaleDataRange -*/ -void QCPColorScale::setDataRange(const QCPRange &dataRange) -{ - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - mDataRange = dataRange; - if (mColorAxis) - mColorAxis.data()->setRange(mDataRange); - emit dataRangeChanged(mDataRange); - } -} - -/*! - Sets the scale type of the color scale, i.e. whether values are linearly associated with colors - or logarithmically. - - It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is - also equivalent to directly accessing the \ref axis and setting its scale type with \ref - QCPAxis::setScaleType. - - \see setDataRange, setGradient -*/ -void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) -{ - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - if (mColorAxis) - mColorAxis.data()->setScaleType(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - emit dataScaleTypeChanged(mDataScaleType); - } -} - -/*! - Sets the color gradient that will be used to represent data values. - - It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. - - \see setDataRange, setDataScaleType -*/ -void QCPColorScale::setGradient(const QCPColorGradient &gradient) -{ - if (mGradient != gradient) - { - mGradient = gradient; - if (mAxisRect) - mAxisRect.data()->mGradientImageInvalidated = true; - emit gradientChanged(mGradient); - } -} - -/*! - Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on - the internal \ref axis. -*/ -void QCPColorScale::setLabel(const QString &str) -{ - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return; - } - - mColorAxis.data()->setLabel(str); -} - -/*! - Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed - will have. -*/ -void QCPColorScale::setBarWidth(int width) -{ - mBarWidth = width; -} - -/*! - Sets whether the user can drag the data range (\ref setDataRange). - - Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref - QCustomPlot::setInteractions) to allow range dragging. -*/ -void QCPColorScale::setRangeDrag(bool enabled) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeDrag(0); -} - -/*! - Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. - - Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref - QCustomPlot::setInteractions) to allow range dragging. -*/ -void QCPColorScale::setRangeZoom(bool enabled) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeZoom(0); -} - -/*! - Returns a list of all the color maps associated with this color scale. -*/ -QList QCPColorScale::colorMaps() const -{ - QList result; - for (int i=0; iplottableCount(); ++i) - { - if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) - if (cm->colorScale() == this) - result.append(cm); - } - return result; -} - -/*! - Changes the data range such that all color maps associated with this color scale are fully mapped - to the gradient in the data dimension. - - \see setDataRange -*/ -void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) -{ - QList maps = colorMaps(); - QCPRange newRange; - bool haveRange = false; - int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) - if (mDataScaleType == QCPAxis::stLogarithmic) - sign = (mDataRange.upper < 0 ? -1 : 1); - for (int i=0; irealVisibility() && onlyVisibleMaps) - continue; - QCPRange mapRange; - if (maps.at(i)->colorScale() == this) - { - bool currentFoundRange = true; - mapRange = maps.at(i)->data()->dataBounds(); - if (sign == 1) - { - if (mapRange.lower <= 0 && mapRange.upper > 0) - mapRange.lower = mapRange.upper*1e-3; - else if (mapRange.lower <= 0 && mapRange.upper <= 0) - currentFoundRange = false; - } else if (sign == -1) - { - if (mapRange.upper >= 0 && mapRange.lower < 0) - mapRange.upper = mapRange.lower*1e-3; - else if (mapRange.upper >= 0 && mapRange.lower >= 0) - currentFoundRange = false; - } - if (currentFoundRange) - { - if (!haveRange) - newRange = mapRange; - else - newRange.expand(mapRange); - haveRange = true; - } - } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mDataScaleType == QCPAxis::stLinear) - { - newRange.lower = center-mDataRange.size()/2.0; - newRange.upper = center+mDataRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); - newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); - } - } - setDataRange(newRange); - } -} - -/* inherits documentation from base class */ -void QCPColorScale::update(UpdatePhase phase) -{ - QCPLayoutElement::update(phase); - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - mAxisRect.data()->update(phase); - - switch (phase) - { - case upMargins: - { - if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) - { - setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); - setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); - } else - { - setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); - setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); - } - break; - } - case upLayout: - { - mAxisRect.data()->setOuterRect(rect()); - break; - } - default: break; - } -} - -/* inherits documentation from base class */ -void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const -{ - painter->setAntialiasing(false); -} - -/* inherits documentation from base class */ -void QCPColorScale::mousePressEvent(QMouseEvent *event) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mousePressEvent(event); -} - -/* inherits documentation from base class */ -void QCPColorScale::mouseMoveEvent(QMouseEvent *event) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseMoveEvent(event); -} - -/* inherits documentation from base class */ -void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseReleaseEvent(event); -} - -/* inherits documentation from base class */ -void QCPColorScale::wheelEvent(QWheelEvent *event) -{ - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->wheelEvent(event); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPColorScaleAxisRectPrivate -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPColorScaleAxisRectPrivate - - \internal - \brief An axis rect subclass for use in a QCPColorScale - - This is a private class and not part of the public QCustomPlot interface. - - It provides the axis rect functionality for the QCPColorScale class. -*/ - - -/*! - Creates a new instance, as a child of \a parentColorScale. -*/ -QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : - QCPAxisRect(parentColorScale->parentPlot(), true), - mParentColorScale(parentColorScale), - mGradientImageInvalidated(true) -{ - setParentLayerable(parentColorScale); - setMinimumMargins(QMargins(0, 0, 0, 0)); - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - axis(type)->setVisible(true); - axis(type)->grid()->setVisible(false); - axis(type)->setPadding(0); - connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); - connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); - } - - connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); - - // make layer transfers of color scale transfer to axis rect and axes - // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); - foreach (QCPAxis::AxisType type, allAxisTypes) - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); -} - -/*! \internal - Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws - it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. -*/ -void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) -{ - if (mGradientImageInvalidated) - updateGradientImage(); - - bool mirrorHorz = false; - bool mirrorVert = false; - if (mParentColorScale->mColorAxis) - { - mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); - mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); - } - - painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); - QCPAxisRect::draw(painter); -} - -/*! \internal - - Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to - generate a gradient image. This gradient image will be used in the \ref draw method. -*/ -void QCPColorScaleAxisRectPrivate::updateGradientImage() -{ - if (rect().isEmpty()) - return; - - int n = mParentColorScale->mGradient.levelCount(); - int w, h; - QVector data(n); - for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) - { - w = n; - h = rect().height(); - mGradientImage = QImage(w, h, QImage::Format_RGB32); - QVector pixels; - for (int y=0; y(mGradientImage.scanLine(y))); - mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); - for (int y=1; y(mGradientImage.scanLine(y)); - const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); - for (int x=0; x allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectedParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); - else - axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); - } - } -} - -/*! \internal - - This slot is connected to the selectableChanged signals of the four axes in the constructor. It - synchronizes the selectability of the axes. -*/ -void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) -{ - // synchronize axis base selectability: - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectableParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); - else - axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); - } - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPData -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPData - \brief Holds the data of one single data point for QCPGraph. - - The container for storing multiple data points is \ref QCPDataMap. - - The stored data is: - \li \a key: coordinate on the key axis of this data point - \li \a value: coordinate on the value axis of this data point - \li \a keyErrorMinus: negative error in the key dimension (for error bars) - \li \a keyErrorPlus: positive error in the key dimension (for error bars) - \li \a valueErrorMinus: negative error in the value dimension (for error bars) - \li \a valueErrorPlus: positive error in the value dimension (for error bars) - - \see QCPDataMap -*/ - -/*! - Constructs a data point with key, value and all errors set to zero. -*/ -QCPData::QCPData() : - key(0), - value(0), - keyErrorPlus(0), - keyErrorMinus(0), - valueErrorPlus(0), - valueErrorMinus(0) -{ -} - -/*! - Constructs a data point with the specified \a key and \a value. All errors are set to zero. -*/ -QCPData::QCPData(double key, double value) : - key(key), - value(value), - keyErrorPlus(0), - keyErrorMinus(0), - valueErrorPlus(0), - valueErrorMinus(0) -{ -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPGraph -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPGraph - \brief A plottable representing a graph in a plot. - - \image html QCPGraph.png - - Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be - accessed via QCustomPlot::graph. - - To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can - also access and modify the graph's data via the \ref data method, which returns a pointer to the - internal \ref QCPDataMap. - - Graphs are used to display single-valued data. Single-valued means that there should only be one - data point per unique key coordinate. In other words, the graph can't have \a loops. If you do - want to plot non-single-valued curves, rather use the QCPCurve plottable. - - Gaps in the graph line can be created by adding data points with NaN as value - (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be - separated. - - \section appearance Changing the appearance - - The appearance of the graph is mainly determined by the line style, scatter style, brush and pen - of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). - - \subsection filling Filling under or between graphs - - QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to - the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, - just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. - - By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill - between this graph and another one, call \ref setChannelFillGraph with the other graph as - parameter. - - \see QCustomPlot::addGraph, QCustomPlot::graph -*/ - -/* start of documentation of inline functions */ - -/*! \fn QCPDataMap *QCPGraph::data() const - - Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to - directly manipulate the data, which may be more convenient and faster than using the regular \ref - setData or \ref addData methods, in certain situations. -*/ - -/* end of documentation of inline functions */ - -/*! - Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value - axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have - the same orientation. If either of these restrictions is violated, a corresponding message is - printed to the debug output (qDebug), the construction is not aborted, though. - - The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the graph. - - To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. -*/ -QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis) -{ - mData = new QCPDataMap; - - setPen(QPen(Qt::blue, 0)); - setErrorPen(QPen(Qt::black)); - setBrush(Qt::NoBrush); - setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); - setSelectedBrush(Qt::NoBrush); - - setLineStyle(lsLine); - setErrorType(etNone); - setErrorBarSize(6); - setErrorBarSkipSymbol(true); - setChannelFillGraph(0); - setAdaptiveSampling(true); -} - -QCPGraph::~QCPGraph() -{ - delete mData; -} - -/*! - Replaces the current data with the provided \a data. - - If \a copy is set to true, data points in \a data will only be copied. if false, the graph - takes ownership of the passed data and replaces the internal data pointer with it. This is - significantly faster than copying for large datasets. - - Alternatively, you can also access and modify the graph's data via the \ref data method, which - returns a pointer to the internal \ref QCPDataMap. -*/ -void QCPGraph::setData(QCPDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } -} - -/*! \overload - - Replaces the current data with the provided points in \a key and \a value pairs. The provided - vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. -*/ -void QCPGraph::setData(const QVector &key, const QVector &value) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } -} - -/*! - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - symmetrical value error of the data points are set to the values in \a valueError. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. - - For asymmetrical errors (plus different from minus), see the overloaded version of this function. -*/ -void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueError) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, valueError.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - -/*! - \overload - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - negative value error of the data points are set to the values in \a valueErrorMinus, the positive - value error to \a valueErrorPlus. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. -*/ -void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, valueErrorMinus.size()); - n = qMin(n, valueErrorPlus.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - -/*! - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - symmetrical key error of the data points are set to the values in \a keyError. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. - - For asymmetrical errors (plus different from minus), see the overloaded version of this function. -*/ -void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, keyError.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - -/*! - \overload - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - negative key error of the data points are set to the values in \a keyErrorMinus, the positive - key error to \a keyErrorPlus. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. -*/ -void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, keyErrorMinus.size()); - n = qMin(n, keyErrorPlus.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - -/*! - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. - - For asymmetrical errors (plus different from minus), see the overloaded version of this function. -*/ -void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, valueError.size()); - n = qMin(n, keyError.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - -/*! - \overload - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the - negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive - key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. - For error bars to show appropriately, see \ref setErrorType. - The provided vectors should have equal length. Else, the number of added points will be the size of the - smallest vector. -*/ -void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, valueErrorMinus.size()); - n = qMin(n, valueErrorPlus.size()); - n = qMin(n, keyErrorMinus.size()); - n = qMin(n, keyErrorPlus.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } -} - - -/*! - Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to - \ref lsNone and \ref setScatterStyle to the desired scatter style. - - \see setScatterStyle -*/ -void QCPGraph::setLineStyle(LineStyle ls) -{ - mLineStyle = ls; -} - -/*! - Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points - are drawn (e.g. for line-only-plots with appropriate line style). - - \see QCPScatterStyle, setLineStyle -*/ -void QCPGraph::setScatterStyle(const QCPScatterStyle &style) -{ - mScatterStyle = style; -} - -/*! - Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data - point. If you set \a errorType to something other than \ref etNone, make sure to actually pass - error data via the specific setData functions along with the data points (e.g. \ref - setDataValueError, \ref setDataKeyError, \ref setDataBothError). - - \see ErrorType -*/ -void QCPGraph::setErrorType(ErrorType errorType) -{ - mErrorType = errorType; -} - -/*! - Sets the pen with which the error bars will be drawn. - \see setErrorBarSize, setErrorType -*/ -void QCPGraph::setErrorPen(const QPen &pen) -{ - mErrorPen = pen; -} - -/*! - Sets the width of the handles at both ends of an error bar in pixels. -*/ -void QCPGraph::setErrorBarSize(double size) -{ - mErrorBarSize = size; -} - -/*! - If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but - leave some free space around the symbol. - - This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size - of the area to leave blank. So when drawing Pixmaps as scatter points (\ref - QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the - size of the Pixmap, if the error bars should leave gaps to its boundaries. - - \ref setErrorType, setErrorBarSize, setScatterStyle -*/ -void QCPGraph::setErrorBarSkipSymbol(bool enabled) -{ - mErrorBarSkipSymbol = enabled; -} - -/*! - Sets the target graph for filling the area between this graph and \a targetGraph with the current - brush (\ref setBrush). - - When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To - disable any filling, set the brush to Qt::NoBrush. - - \see setBrush -*/ -void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) -{ - // prevent setting channel target to this graph itself: - if (targetGraph == this) - { - qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; - mChannelFillGraph = 0; - return; - } - // prevent setting channel target to a graph not in the plot: - if (targetGraph && targetGraph->mParentPlot != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; - mChannelFillGraph = 0; - return; - } - - mChannelFillGraph = targetGraph; -} - -/*! - Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive - sampling technique can drastically improve the replot performance for graphs with a larger number - of points (e.g. above 10,000), without notably changing the appearance of the graph. - - By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive - sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no - disadvantage in almost all cases. - - \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" - - As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are - reproduced reliably, as well as the overall shape of the data set. The replot time reduces - dramatically though. This allows QCustomPlot to display large amounts of data in realtime. - - \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" - - Care must be taken when using high-density scatter plots in combination with adaptive sampling. - The adaptive sampling algorithm treats scatter plots more carefully than line plots which still - gives a significant reduction of replot times, but not quite as much as for line plots. This is - because scatter plots inherently need more data points to be preserved in order to still resemble - the original, non-adaptive-sampling plot. As shown above, the results still aren't quite - identical, as banding occurs for the outer data points. This is in fact intentional, such that - the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, - depends on the point density, i.e. the number of points in the plot. - - For some situations with scatter plots it might thus be desirable to manually turn adaptive - sampling off. For example, when saving the plot to disk. This can be achieved by setting \a - enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled - back to true afterwards. -*/ -void QCPGraph::setAdaptiveSampling(bool enabled) -{ - mAdaptiveSampling = enabled; -} - -/*! - Adds the provided data points in \a dataMap to the current data. - - Alternatively, you can also access and modify the graph's data via the \ref data method, which - returns a pointer to the internal \ref QCPDataMap. - - \see removeData -*/ -void QCPGraph::addData(const QCPDataMap &dataMap) -{ - mData->unite(dataMap); -} - -/*! \overload - Adds the provided single data point in \a data to the current data. - - Alternatively, you can also access and modify the graph's data via the \ref data method, which - returns a pointer to the internal \ref QCPDataMap. - - \see removeData -*/ -void QCPGraph::addData(const QCPData &data) -{ - mData->insertMulti(data.key, data); -} - -/*! \overload - Adds the provided single data point as \a key and \a value pair to the current data. - - Alternatively, you can also access and modify the graph's data via the \ref data method, which - returns a pointer to the internal \ref QCPDataMap. - - \see removeData -*/ -void QCPGraph::addData(double key, double value) -{ - QCPData newData; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.key, newData); -} - -/*! \overload - Adds the provided data points as \a key and \a value pairs to the current data. - - Alternatively, you can also access and modify the graph's data via the \ref data method, which - returns a pointer to the internal \ref QCPDataMap. - - \see removeData -*/ -void QCPGraph::addData(const QVector &keys, const QVector &values) -{ - int n = qMin(keys.size(), values.size()); - QCPData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } -} - -/*! - Removes all data points with keys smaller than \a key. - \see addData, clearData -*/ -void QCPGraph::removeDataBefore(double key) -{ - QCPDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); -} - -/*! - Removes all data points with keys greater than \a key. - \see addData, clearData -*/ -void QCPGraph::removeDataAfter(double key) -{ - if (mData->isEmpty()) return; - QCPDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); -} - -/*! - Removes all data points with keys between \a fromKey and \a toKey. - if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove - a single data point with known key, use \ref removeData(double key). - - \see addData, clearData -*/ -void QCPGraph::removeData(double fromKey, double toKey) -{ - if (fromKey >= toKey || mData->isEmpty()) return; - QCPDataMap::iterator it = mData->upperBound(fromKey); - QCPDataMap::iterator itEnd = mData->upperBound(toKey); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \overload - - Removes a single data point at \a key. If the position is not known with absolute precision, - consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around - the suspected position, depeding on the precision with which the key is known. - - \see addData, clearData -*/ -void QCPGraph::removeData(double key) -{ - mData->remove(key); -} - -/*! - Removes all data points. - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPGraph::clearData() -{ - mData->clear(); -} - -/* inherits documentation from base class */ -double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - return pointDistance(pos); - else - return -1; -} - -/*! \overload - - Allows to define whether error bars are taken into consideration when determining the new axis - range. - - \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes -*/ -void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const -{ - rescaleKeyAxis(onlyEnlarge, includeErrorBars); - rescaleValueAxis(onlyEnlarge, includeErrorBars); -} - -/*! \overload - - Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration - when determining the new axis range. - - \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis -*/ -void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const -{ - // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change - // that getKeyRange is passed the includeErrorBars value. - if (mData->isEmpty()) return; - - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - SignDomain signDomain = sdBoth; - if (keyAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); - - if (foundRange) - { - if (onlyEnlarge) - { - if (keyAxis->range().lower < newRange.lower) - newRange.lower = keyAxis->range().lower; - if (keyAxis->range().upper > newRange.upper) - newRange.upper = keyAxis->range().upper; - } - keyAxis->setRange(newRange); - } -} - -/*! \overload - - Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration - when determining the new axis range. - - \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis -*/ -void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const -{ - // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change - // is that getValueRange is passed the includeErrorBars value. - if (mData->isEmpty()) return; - - QCPAxis *valueAxis = mValueAxis.data(); - if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } - - SignDomain signDomain = sdBoth; - if (valueAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); - - bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); - - if (foundRange) - { - if (onlyEnlarge) - { - if (valueAxis->range().lower < newRange.lower) - newRange.lower = valueAxis->range().lower; - if (valueAxis->range().upper > newRange.upper) - newRange.upper = valueAxis->range().upper; - } - valueAxis->setRange(newRange); - } -} - -/* inherits documentation from base class */ -void QCPGraph::draw(QCPPainter *painter) -{ - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; - if (mLineStyle == lsNone && mScatterStyle.isNone()) return; - - // allocate line and (if necessary) point vectors: - QVector *lineData = new QVector; - QVector *scatterData = 0; - if (!mScatterStyle.isNone()) - scatterData = new QVector; - - // fill vectors with data appropriate to plot style: - getPlotData(lineData, scatterData); - - // check data validity if flag set: -#ifdef QCUSTOMPLOT_CHECK_DATA - QCPDataMap::const_iterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++it) - { - if (QCP::isInvalidData(it.value().key, it.value().value) || - QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || - QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) - qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); - } -#endif - - // draw fill of graph: - if (mLineStyle != lsNone) - drawFill(painter, lineData); - - // draw line: - if (mLineStyle == lsImpulse) - drawImpulsePlot(painter, lineData); - else if (mLineStyle != lsNone) - drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot - - // draw scatters: - if (scatterData) - drawScatterPlot(painter, scatterData); - - // free allocated line and point vectors: - delete lineData; - if (scatterData) - delete scatterData; -} - -/* inherits documentation from base class */ -void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); - } - } -} - -/*! \internal - - This function branches out to the line style specific "get(...)PlotData" functions, according to - the line style of the graph. - - \a lineData will be filled with raw points that will be drawn with the according draw functions, - e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data - points, since for step plots for example, additional points are needed for drawing lines that - make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left - untouched. - - \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the - scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is - \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. - - \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, - getStepCenterPlotData, getImpulsePlotData -*/ -void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const -{ - switch(mLineStyle) - { - case lsNone: getScatterPlotData(scatterData); break; - case lsLine: getLinePlotData(lineData, scatterData); break; - case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; - case lsStepRight: getStepRightPlotData(lineData, scatterData); break; - case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; - case lsImpulse: getImpulsePlotData(lineData, scatterData); break; - } -} - -/*! \internal - - If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, - this function serves at providing the visible data points in \a scatterData, so the \ref - drawScatterPlot function can draw the scatter points accordingly. - - If line style is not \ref lsNone, this function is not called and the data for the scatter points - are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. - - \see drawScatterPlot -*/ -void QCPGraph::getScatterPlotData(QVector *scatterData) const -{ - getPreparedData(0, scatterData); -} - -/*! \internal - - Places the raw data points needed for a normal linearly connected graph in \a linePixelData. - - As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) - points that are visible for drawing scatter points, if necessary. If drawing scatter points is - disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a - scatterData, and the function will skip filling the vector. - - \see drawLinePlot -*/ -void QCPGraph::getLinePlotData(QVector *linePixelData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } - - QVector lineData; - getPreparedData(&lineData, scatterData); - linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill - linePixelData->resize(lineData.size()); - - // transform lineData points to pixels: - if (keyAxis->orientation() == Qt::Vertical) - { - for (int i=0; icoordToPixel(lineData.at(i).value)); - (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); - } - } else // key axis is horizontal - { - for (int i=0; icoordToPixel(lineData.at(i).key)); - (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); - } - } -} - -/*! - \internal - Places the raw data points needed for a step plot with left oriented steps in \a lineData. - - As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) - points that are visible for drawing scatter points, if necessary. If drawing scatter points is - disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a - scatterData, and the function will skip filling the vector. - - \see drawLinePlot -*/ -void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } - - QVector lineData; - getPreparedData(&lineData, scatterData); - linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill - linePixelData->resize(lineData.size()*2); - - // calculate steps from lineData and transform to pixel coordinates: - if (keyAxis->orientation() == Qt::Vertical) - { - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - for (int i=0; icoordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(lastValue); - (*linePixelData)[i*2+0].setY(key); - lastValue = valueAxis->coordToPixel(lineData.at(i).value); - (*linePixelData)[i*2+1].setX(lastValue); - (*linePixelData)[i*2+1].setY(key); - } - } else // key axis is horizontal - { - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - for (int i=0; icoordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(key); - (*linePixelData)[i*2+0].setY(lastValue); - lastValue = valueAxis->coordToPixel(lineData.at(i).value); - (*linePixelData)[i*2+1].setX(key); - (*linePixelData)[i*2+1].setY(lastValue); - } - } -} - -/*! - \internal - Places the raw data points needed for a step plot with right oriented steps in \a lineData. - - As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) - points that are visible for drawing scatter points, if necessary. If drawing scatter points is - disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a - scatterData, and the function will skip filling the vector. - - \see drawLinePlot -*/ -void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } - - QVector lineData; - getPreparedData(&lineData, scatterData); - linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill - linePixelData->resize(lineData.size()*2); - - // calculate steps from lineData and transform to pixel coordinates: - if (keyAxis->orientation() == Qt::Vertical) - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double value; - for (int i=0; icoordToPixel(lineData.at(i).value); - (*linePixelData)[i*2+0].setX(value); - (*linePixelData)[i*2+0].setY(lastKey); - lastKey = keyAxis->coordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+1].setX(value); - (*linePixelData)[i*2+1].setY(lastKey); - } - } else // key axis is horizontal - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double value; - for (int i=0; icoordToPixel(lineData.at(i).value); - (*linePixelData)[i*2+0].setX(lastKey); - (*linePixelData)[i*2+0].setY(value); - lastKey = keyAxis->coordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+1].setX(lastKey); - (*linePixelData)[i*2+1].setY(value); - } - } -} - -/*! - \internal - Places the raw data points needed for a step plot with centered steps in \a lineData. - - As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) - points that are visible for drawing scatter points, if necessary. If drawing scatter points is - disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a - scatterData, and the function will skip filling the vector. - - \see drawLinePlot -*/ -void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } - - QVector lineData; - getPreparedData(&lineData, scatterData); - linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill - linePixelData->resize(lineData.size()*2); - // calculate steps from lineData and transform to pixel coordinates: - if (keyAxis->orientation() == Qt::Vertical) - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - (*linePixelData)[0].setX(lastValue); - (*linePixelData)[0].setY(lastKey); - for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; - (*linePixelData)[i*2-1].setX(lastValue); - (*linePixelData)[i*2-1].setY(key); - lastValue = valueAxis->coordToPixel(lineData.at(i).value); - lastKey = keyAxis->coordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(lastValue); - (*linePixelData)[i*2+0].setY(key); - } - (*linePixelData)[lineData.size()*2-1].setX(lastValue); - (*linePixelData)[lineData.size()*2-1].setY(lastKey); - } else // key axis is horizontal - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - (*linePixelData)[0].setX(lastKey); - (*linePixelData)[0].setY(lastValue); - for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; - (*linePixelData)[i*2-1].setX(key); - (*linePixelData)[i*2-1].setY(lastValue); - lastValue = valueAxis->coordToPixel(lineData.at(i).value); - lastKey = keyAxis->coordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(key); - (*linePixelData)[i*2+0].setY(lastValue); - } - (*linePixelData)[lineData.size()*2-1].setX(lastKey); - (*linePixelData)[lineData.size()*2-1].setY(lastValue); - } - -} - -/*! - \internal - Places the raw data points needed for an impulse plot in \a lineData. - - As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) - points that are visible for drawing scatter points, if necessary. If drawing scatter points is - disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a - scatterData, and the function will skip filling the vector. - - \see drawImpulsePlot -*/ -void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } - - QVector lineData; - getPreparedData(&lineData, scatterData); - linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill - - // transform lineData points to pixels: - if (keyAxis->orientation() == Qt::Vertical) - { - double zeroPointX = valueAxis->coordToPixel(0); - double key; - for (int i=0; icoordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(zeroPointX); - (*linePixelData)[i*2+0].setY(key); - (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); - (*linePixelData)[i*2+1].setY(key); - } - } else // key axis is horizontal - { - double zeroPointY = valueAxis->coordToPixel(0); - double key; - for (int i=0; icoordToPixel(lineData.at(i).key); - (*linePixelData)[i*2+0].setX(key); - (*linePixelData)[i*2+0].setY(zeroPointY); - (*linePixelData)[i*2+1].setX(key); - (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); - } - } -} - -/*! \internal - - Draws the fill of the graph with the specified brush. - - If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and - two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by - \ref removeFillBasePoints after the fill drawing is done). - - If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the - more complex polygon is calculated with the \ref getChannelFillPolygon function. - - \see drawLinePlot -*/ -void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const -{ - if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot - if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; - - applyFillAntialiasingHint(painter); - if (!mChannelFillGraph) - { - // draw base fill under graph, fill goes all the way to the zero-value-line: - addFillBasePoints(lineData); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(QPolygonF(*lineData)); - removeFillBasePoints(lineData); - } else - { - // draw channel fill between this graph and mChannelFillGraph: - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(getChannelFillPolygon(lineData)); - } -} - -/*! \internal - - Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent - of the line style and are always drawn if the scatter style's shape is not \ref - QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" - functions, together with the (line style dependent) line data. - - \see drawLinePlot, drawImpulsePlot -*/ -void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - // draw error bars: - if (mErrorType != etNone) - { - applyErrorBarsAntialiasingHint(painter); - painter->setPen(mErrorPen); - if (keyAxis->orientation() == Qt::Vertical) - { - for (int i=0; isize(); ++i) - drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); - } else - { - for (int i=0; isize(); ++i) - drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); - } - } - - // draw scatter point symbols: - applyScattersAntialiasingHint(painter); - mScatterStyle.applyTo(painter, mPen); - if (keyAxis->orientation() == Qt::Vertical) - { - for (int i=0; isize(); ++i) - if (!qIsNaN(scatterData->at(i).value)) - mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); - } else - { - for (int i=0; isize(); ++i) - if (!qIsNaN(scatterData->at(i).value)) - mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); - } -} - -/*! \internal - - Draws line graphs from the provided data. It connects all points in \a lineData, which was - created by one of the "get(...)PlotData" functions for line styles that require simple line - connections between the point vector they create. These are for example \ref getLinePlotData, - \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. - - \see drawScatterPlot, drawImpulsePlot -*/ -void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const -{ - // draw line of graph: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - - /* Draws polyline in batches, currently not used: - int p = 0; - while (p < lineData->size()) - { - int batch = qMin(25, lineData->size()-p); - if (p != 0) - { - ++batch; - --p; // to draw the connection lines between two batches - } - painter->drawPolyline(lineData->constData()+p, batch); - p += batch; - } - */ - - // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: - if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && - painter->pen().style() == Qt::SolidLine && - !painter->modes().testFlag(QCPPainter::pmVectorized) && - !painter->modes().testFlag(QCPPainter::pmNoCaching)) - { - int i = 0; - bool lastIsNan = false; - const int lineDataSize = lineData->size(); - while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN - ++i; - ++i; // because drawing works in 1 point retrospect - while (i < lineDataSize) - { - if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line - { - if (!lastIsNan) - painter->drawLine(lineData->at(i-1), lineData->at(i)); - else - lastIsNan = false; - } else - lastIsNan = true; - ++i; - } - } else - { - int segmentStart = 0; - int i = 0; - const int lineDataSize = lineData->size(); - while (i < lineDataSize) - { - if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()) || qIsInf(lineData->at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block - { - painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point - segmentStart = i+1; - } - ++i; - } - // draw last segment: - painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); - } - } -} - -/*! \internal - - Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was - created by \ref getImpulsePlotData. - - \see drawScatterPlot, drawLinePlot -*/ -void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const -{ - // draw impulses: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - QPen pen = mainPen(); - pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawLines(*lineData); - } -} - -/*! \internal - - Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into - consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point - densities. - - 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't - needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a - scatterData should be 0 to prevent unnecessary calculations. - - This method is used by the various "get(...)PlotData" methods to get the basic working set of data. -*/ -void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - // get visible data range: - QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point - getVisibleDataBounds(lower, upper); - if (lower == mData->constEnd() || upper == mData->constEnd()) - return; - - // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: - int maxCount = std::numeric_limits::max(); - if (mAdaptiveSampling) - { - int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); - maxCount = 2*keyPixelSpan+2; - } - int dataCount = countDataInBounds(lower, upper, maxCount); - - if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average - { - if (lineData) - { - QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; - double minValue = it.value().value; - double maxValue = it.value().value; - QCPDataMap::const_iterator currentIntervalFirstPoint = it; - int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction - int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey - double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); - double lastIntervalEndKey = currentIntervalStartKey; - double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates - bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) - int intervalDataCount = 1; - ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect - while (it != upperEnd) - { - if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary - { - if (it.value().value < minValue) - minValue = it.value().value; - else if (it.value().value > maxValue) - maxValue = it.value().value; - ++intervalDataCount; - } else // new pixel interval started - { - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster - { - if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); - if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); - } else - lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); - lastIntervalEndKey = (it-1).value().key; - minValue = it.value().value; - maxValue = it.value().value; - currentIntervalFirstPoint = it; - currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); - if (keyEpsilonVariable) - keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); - intervalDataCount = 1; - } - ++it; - } - // handle last interval: - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster - { - if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); - lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); - } else - lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); - } - - if (scatterData) - { - double valueMaxRange = valueAxis->range().upper; - double valueMinRange = valueAxis->range().lower; - QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; - double minValue = it.value().value; - double maxValue = it.value().value; - QCPDataMap::const_iterator minValueIt = it; - QCPDataMap::const_iterator maxValueIt = it; - QCPDataMap::const_iterator currentIntervalStart = it; - int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction - int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey - double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); - double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates - bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) - int intervalDataCount = 1; - ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect - while (it != upperEnd) - { - if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary - { - if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) - { - minValue = it.value().value; - minValueIt = it; - } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) - { - maxValue = it.value().value; - maxValueIt = it; - } - ++intervalDataCount; - } else // new pixel started - { - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them - { - // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): - double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); - int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average - QCPDataMap::const_iterator intervalIt = currentIntervalStart; - int c = 0; - while (intervalIt != it) - { - if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) - scatterData->append(intervalIt.value()); - ++c; - ++intervalIt; - } - } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) - scatterData->append(currentIntervalStart.value()); - minValue = it.value().value; - maxValue = it.value().value; - currentIntervalStart = it; - currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); - if (keyEpsilonVariable) - keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); - intervalDataCount = 1; - } - ++it; - } - // handle last interval: - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them - { - // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): - double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); - int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average - QCPDataMap::const_iterator intervalIt = currentIntervalStart; - int c = 0; - while (intervalIt != it) - { - if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) - scatterData->append(intervalIt.value()); - ++c; - ++intervalIt; - } - } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) - scatterData->append(currentIntervalStart.value()); - } - } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters - { - QVector *dataVector = 0; - if (lineData) - dataVector = lineData; - else if (scatterData) - dataVector = scatterData; - if (dataVector) - { - QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; - dataVector->reserve(dataCount+2); // +2 for possible fill end points - while (it != upperEnd) - { - dataVector->append(it.value()); - ++it; - } - } - if (lineData && scatterData) - *scatterData = *dataVector; - } -} - -/*! \internal - - called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data - point. \a x and \a y pixel positions of the data point are passed since they are already known in - pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a - data is therefore only used for the errors, not key and value. -*/ -void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const -{ - if (qIsNaN(data.value)) - return; - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - double a, b; // positions of error bar bounds in pixels - double barWidthHalf = mErrorBarSize*0.5; - double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true - - if (keyAxis->orientation() == Qt::Vertical) - { - // draw key error vertically and value error horizontally - if (mErrorType == etKey || mErrorType == etBoth) - { - a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); - b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); - if (keyAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin - painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); - if (y-b > skipSymbolMargin) - painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); - } else - painter->drawLine(QLineF(x, a, x, b)); - // draw handles: - painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); - painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); - } - if (mErrorType == etValue || mErrorType == etBoth) - { - a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); - b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); - if (valueAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin - painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); - if (b-x > skipSymbolMargin) - painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); - } else - painter->drawLine(QLineF(a, y, b, y)); - // draw handles: - painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); - painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); - } - } else // mKeyAxis->orientation() is Qt::Horizontal - { - // draw value error vertically and key error horizontally - if (mErrorType == etKey || mErrorType == etBoth) - { - a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); - b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); - if (keyAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin - painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); - if (b-x > skipSymbolMargin) - painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); - } else - painter->drawLine(QLineF(a, y, b, y)); - // draw handles: - painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); - painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); - } - if (mErrorType == etValue || mErrorType == etBoth) - { - a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); - b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); - if (valueAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin - painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); - if (y-b > skipSymbolMargin) - painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); - } else - painter->drawLine(QLineF(x, a, x, b)); - // draw handles: - painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); - painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); - } - } -} - -/*! \internal - - called by \ref getPreparedData to determine which data (key) range is visible at the current key - axis range setting, so only that needs to be processed. - - \a lower returns an iterator to the lowest data point that needs to be taken into account when - plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a - lower may still be just outside the visible range. - - \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie - just outside of the visible range. - - if the graph contains no data, both \a lower and \a upper point to constEnd. -*/ -void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const -{ - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) - { - lower = mData->constEnd(); - upper = mData->constEnd(); - return; - } - - // get visible data range as QMap iterators - QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); - QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); - bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range - bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range - - lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn - upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn -} - -/*! \internal - - Counts the number of data points between \a lower and \a upper (including them), up to a maximum - of \a maxCount. - - This function is used by \ref getPreparedData to determine whether adaptive sampling shall be - used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points - only needs to be done until \a maxCount is reached, which should be set to the number of data - points at which adaptive sampling sets in. -*/ -int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const -{ - if (upper == mData->constEnd() && lower == mData->constEnd()) - return 0; - QCPDataMap::const_iterator it = lower; - int count = 1; - while (it != upper && count < maxCount) - { - ++it; - ++count; - } - return count; -} - -/*! \internal - - The line data vector generated by e.g. getLinePlotData contains only the line that connects the - data points. If the graph needs to be filled, two additional points need to be added at the - value-zero-line in the lower and upper key positions of the graph. This function calculates these - points and adds them to the end of \a lineData. Since the fill is typically drawn before the line - stroke, these added points need to be removed again after the fill is done, with the - removeFillBasePoints function. - - The expanding of \a lineData by two points will not cause unnecessary memory reallocations, - because the data vector generation functions (getLinePlotData etc.) reserve two extra points when - they allocate memory for \a lineData. - - \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint -*/ -void QCPGraph::addFillBasePoints(QVector *lineData) const -{ - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } - if (lineData->isEmpty()) return; - - // append points that close the polygon fill at the key axis: - if (mKeyAxis.data()->orientation() == Qt::Vertical) - { - *lineData << upperFillBasePoint(lineData->last().y()); - *lineData << lowerFillBasePoint(lineData->first().y()); - } else - { - *lineData << upperFillBasePoint(lineData->last().x()); - *lineData << lowerFillBasePoint(lineData->first().x()); - } -} - -/*! \internal - - removes the two points from \a lineData that were added by \ref addFillBasePoints. - - \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint -*/ -void QCPGraph::removeFillBasePoints(QVector *lineData) const -{ - if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } - if (lineData->isEmpty()) return; - - lineData->remove(lineData->size()-2, 2); -} - -/*! \internal - - called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon - on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale - case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative - infinity. So this case is handled separately by just closing the fill polygon on the axis which - lies in the direction towards the zero value. - - \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key - axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned - point, respectively. - - \see upperFillBasePoint, addFillBasePoints -*/ -QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - QPointF point; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->axisType() == QCPAxis::atLeft) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atRight) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atTop) - { - point.setX(lowerKey); - point.setY(valueAxis->coordToPixel(0)); - } else if (keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(lowerKey); - point.setY(valueAxis->coordToPixel(0)); - } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value zero so we just fill all the way - // to the axis which is in the direction towards zero - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setX(keyAxis->axisRect()->right()); - else - point.setX(keyAxis->axisRect()->left()); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(lowerKey); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setY(keyAxis->axisRect()->top()); - else - point.setY(keyAxis->axisRect()->bottom()); - } - } - return point; -} - -/*! \internal - - called by \ref addFillBasePoints to conveniently assign the point which closes the fill - polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis - scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or - negative infinity. So this case is handled separately by just closing the fill polygon on the - axis which lies in the direction towards the zero value. - - \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key - axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned - point, respectively. - - \see lowerFillBasePoint, addFillBasePoints -*/ -QPointF QCPGraph::upperFillBasePoint(double upperKey) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - QPointF point; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->axisType() == QCPAxis::atLeft) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atRight) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atTop) - { - point.setX(upperKey); - point.setY(valueAxis->coordToPixel(0)); - } else if (keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(upperKey); - point.setY(valueAxis->coordToPixel(0)); - } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value 0 so we just fill all the way - // to the axis which is in the direction towards 0 - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setX(keyAxis->axisRect()->right()); - else - point.setX(keyAxis->axisRect()->left()); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(upperKey); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setY(keyAxis->axisRect()->top()); - else - point.setY(keyAxis->axisRect()->bottom()); - } - } - return point; -} - -/*! \internal - - Generates the polygon needed for drawing channel fills between this graph (data passed via \a - lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref - getPlotData function). May return an empty polygon if the key ranges have no overlap or fill - target graph and this graph don't have same orientation (i.e. both key axes horizontal or both - key axes vertical). For increased performance (due to implicit sharing), keep the returned - QPolygonF const. -*/ -const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const -{ - if (!mChannelFillGraph) - return QPolygonF(); - - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } - if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } - - if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) - return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) - - if (lineData->isEmpty()) return QPolygonF(); - QVector otherData; - mChannelFillGraph.data()->getPlotData(&otherData, 0); - if (otherData.isEmpty()) return QPolygonF(); - QVector thisData; - thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function - for (int i=0; isize(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() - thisData << lineData->at(i); - - // pointers to be able to swap them, depending which data range needs cropping: - QVector *staticData = &thisData; - QVector *croppedData = &otherData; - - // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): - if (keyAxis->orientation() == Qt::Horizontal) - { - // x is key - // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: - if (staticData->first().x() > staticData->last().x()) - { - int size = staticData->size(); - for (int i=0; ifirst().x() > croppedData->last().x()) - { - int size = croppedData->size(); - for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexBelowX(croppedData, staticData->first().x()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (croppedData->at(1).x()-croppedData->at(0).x() != 0) - slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); - else - slope = 0; - (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); - (*croppedData)[0].setX(staticData->first().x()); - - // crop upper bound: - if (staticData->last().x() > croppedData->last().x()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveX(croppedData, staticData->last().x()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) - slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); - else - slope = 0; - (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); - (*croppedData)[li].setX(staticData->last().x()); - } else // mKeyAxis->orientation() == Qt::Vertical - { - // y is key - // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, - // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. - // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: - if (staticData->first().y() < staticData->last().y()) - { - int size = staticData->size(); - for (int i=0; ifirst().y() < croppedData->last().y()) - { - int size = croppedData->size(); - for (int i=0; ifirst().y() > croppedData->first().y()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexAboveY(croppedData, staticData->first().y()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots - slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); - else - slope = 0; - (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); - (*croppedData)[0].setY(staticData->first().y()); - - // crop upper bound: - if (staticData->last().y() < croppedData->last().y()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexBelowY(croppedData, staticData->last().y()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots - slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); - else - slope = 0; - (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); - (*croppedData)[li].setY(staticData->last().y()); - } - - // return joined: - for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted - thisData << otherData.at(i); - return QPolygonF(thisData); -} - -/*! \internal - - Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in - \a data points are ordered ascending, as is the case when plotting with horizontal key axis. - - Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. -*/ -int QCPGraph::findIndexAboveX(const QVector *data, double x) const -{ - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).x() < x) - { - if (isize()-1) - return i+1; - else - return data->size()-1; - } - } - return -1; -} - -/*! \internal - - Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in - \a data points are ordered ascending, as is the case when plotting with horizontal key axis. - - Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. -*/ -int QCPGraph::findIndexBelowX(const QVector *data, double x) const -{ - for (int i=0; isize(); ++i) - { - if (data->at(i).x() > x) - { - if (i>0) - return i-1; - else - return 0; - } - } - return -1; -} - -/*! \internal - - Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in - \a data points are ordered descending, as is the case when plotting with vertical key axis. - - Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. -*/ -int QCPGraph::findIndexAboveY(const QVector *data, double y) const -{ - for (int i=0; isize(); ++i) - { - if (data->at(i).y() < y) - { - if (i>0) - return i-1; - else - return 0; - } - } - return -1; -} - -/*! \internal - - Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a - pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in - \ref selectTest. - - If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape - is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0. -*/ -double QCPGraph::pointDistance(const QPointF &pixelPoint) const -{ - if (mData->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - // calculate minimum distances to graph representation: - if (mLineStyle == lsNone) - { - // no line displayed, only calculate distance to scatter points: - QVector scatterData; - getScatterPlotData(&scatterData); - if (scatterData.size() > 0) - { - double minDistSqr = std::numeric_limits::max(); - for (int i=0; i lineData; - getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here - if (lineData.size() > 1) // at least one line segment, compare distance to line segments - { - double minDistSqr = std::numeric_limits::max(); - if (mLineStyle == lsImpulse) - { - // impulse plot differs from other line styles in that the lineData points are only pairwise connected: - for (int i=0; i 0) // only single data point, calculate distance to that point - { - return QVector2D(lineData.at(0)-pixelPoint).length(); - } else // no data available in view to calculate distance to - return -1.0; - } -} - -/*! \internal - - Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in - \a data points are ordered descending, as is the case when plotting with vertical key axis (since - keys are ordered ascending). - - Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. -*/ -int QCPGraph::findIndexBelowY(const QVector *data, double y) const -{ - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).y() > y) - { - if (isize()-1) - return i+1; - else - return data->size()-1; - } - } - return -1; -} - -/* inherits documentation from base class */ -QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - // just call the specialized version which takes an additional argument whether error bars - // should also be taken into consideration for range calculation. We set this to true here. - return getKeyRange(foundRange, inSignDomain, true); -} - -/* inherits documentation from base class */ -QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - // just call the specialized version which takes an additional argument whether error bars - // should also be taken into consideration for range calculation. We set this to true here. - return getValueRange(foundRange, inSignDomain, true); -} - -/*! \overload - - Allows to specify whether the error bars should be included in the range calculation. - - \see getKeyRange(bool &foundRange, SignDomain inSignDomain) -*/ -QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current, currentErrorMinus, currentErrorPlus; - - if (inSignDomain == sdBoth) // range may be anywhere - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - if (!qIsNaN(it.value().value)) - { - current = it.value().key; - currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); - if (current-currentErrorMinus < range.lower || !haveLower) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if (current+currentErrorPlus > range.upper || !haveUpper) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - } - ++it; - } - } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - if (!qIsNaN(it.value().value)) - { - current = it.value().key; - currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); - if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. - { - if ((current < range.lower || !haveLower) && current < 0) - { - range.lower = current; - haveLower = true; - } - if ((current > range.upper || !haveUpper) && current < 0) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - if (!qIsNaN(it.value().value)) - { - current = it.value().key; - currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); - if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. - { - if ((current < range.lower || !haveLower) && current > 0) - { - range.lower = current; - haveLower = true; - } - if ((current > range.upper || !haveUpper) && current > 0) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - } - - foundRange = haveLower && haveUpper; - return range; -} - -/*! \overload - - Allows to specify whether the error bars should be included in the range calculation. - - \see getValueRange(bool &foundRange, SignDomain inSignDomain) -*/ -QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current, currentErrorMinus, currentErrorPlus; - - if (inSignDomain == sdBoth) // range may be anywhere - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value; - if (!qIsNaN(current)) - { - currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); - if (current-currentErrorMinus < range.lower || !haveLower) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if (current+currentErrorPlus > range.upper || !haveUpper) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - } - ++it; - } - } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value; - if (!qIsNaN(current)) - { - currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); - if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. - { - if ((current < range.lower || !haveLower) && current < 0) - { - range.lower = current; - haveLower = true; - } - if ((current > range.upper || !haveUpper) && current < 0) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain - { - QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value; - if (!qIsNaN(current)) - { - currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); - if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) - { - range.lower = current-currentErrorMinus; - haveLower = true; - } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) - { - range.upper = current+currentErrorPlus; - haveUpper = true; - } - if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. - { - if ((current < range.lower || !haveLower) && current > 0) - { - range.lower = current; - haveLower = true; - } - if ((current > range.upper || !haveUpper) && current > 0) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - } - - foundRange = haveLower && haveUpper; - return range; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPCurveData -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPCurveData - \brief Holds the data of one single data point for QCPCurve. - - The container for storing multiple data points is \ref QCPCurveDataMap. - - The stored data is: - \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) - \li \a key: coordinate on the key axis of this curve point - \li \a value: coordinate on the value axis of this curve point - - \see QCPCurveDataMap -*/ - -/*! - Constructs a curve data point with t, key and value set to zero. -*/ -QCPCurveData::QCPCurveData() : - t(0), - key(0), - value(0) -{ -} - -/*! - Constructs a curve data point with the specified \a t, \a key and \a value. -*/ -QCPCurveData::QCPCurveData(double t, double key, double value) : - t(t), - key(key), - value(value) -{ -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPCurve -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPCurve - \brief A plottable representing a parametric curve in a plot. - - \image html QCPCurve.png - - Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, - so their visual representation can have \a loops. This is realized by introducing a third - coordinate \a t, which defines the order of the points described by the other two coordinates \a - x and \a y. - - To plot data, assign it with the \ref setData or \ref addData functions. - - Gaps in the curve can be created by adding data points with NaN as key and value - (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be - separated. - - \section appearance Changing the appearance - - The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). - \section usage Usage - - Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So - the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) - - Usually, you first create an instance and add it to the customPlot: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 - and then modify the properties of the newly created plottable, e.g.: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2 -*/ - -/*! - Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value - axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have - the same orientation. If either of these restrictions is violated, a corresponding message is - printed to the debug output (qDebug), the construction is not aborted, though. - - The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the graph. -*/ -QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis) -{ - mData = new QCPCurveDataMap; - mPen.setColor(Qt::blue); - mPen.setStyle(Qt::SolidLine); - mBrush.setColor(Qt::blue); - mBrush.setStyle(Qt::NoBrush); - mSelectedPen = mPen; - mSelectedPen.setWidthF(2.5); - mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen - mSelectedBrush = mBrush; - - setScatterStyle(QCPScatterStyle()); - setLineStyle(lsLine); -} - -QCPCurve::~QCPCurve() -{ - delete mData; -} - -/*! - Replaces the current data with the provided \a data. - - If \a copy is set to true, data points in \a data will only be copied. if false, the plottable - takes ownership of the passed data and replaces the internal data pointer with it. This is - significantly faster than copying for large datasets. -*/ -void QCPCurve::setData(QCPCurveDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } -} - -/*! \overload - - Replaces the current data with the provided points in \a t, \a key and \a value tuples. The - provided vectors should have equal length. Else, the number of added points will be the size of - the smallest vector. -*/ -void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) -{ - mData->clear(); - int n = t.size(); - n = qMin(n, key.size()); - n = qMin(n, value.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } -} - -/*! \overload - - Replaces the current data with the provided \a key and \a value pairs. The t parameter - of each data point will be set to the integer index of the respective key/value pair. -*/ -void QCPCurve::setData(const QVector &key, const QVector &value) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } -} - -/*! - Sets the visual appearance of single data points in the plot. If set to \ref - QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate - line style). - - \see QCPScatterStyle, setLineStyle -*/ -void QCPCurve::setScatterStyle(const QCPScatterStyle &style) -{ - mScatterStyle = style; -} - -/*! - Sets how the single data points are connected in the plot or how they are represented visually - apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref - setScatterStyle to the desired scatter style. - - \see setScatterStyle -*/ -void QCPCurve::setLineStyle(QCPCurve::LineStyle style) -{ - mLineStyle = style; -} - -/*! - Adds the provided data points in \a dataMap to the current data. - \see removeData -*/ -void QCPCurve::addData(const QCPCurveDataMap &dataMap) -{ - mData->unite(dataMap); -} - -/*! \overload - Adds the provided single data point in \a data to the current data. - \see removeData -*/ -void QCPCurve::addData(const QCPCurveData &data) -{ - mData->insertMulti(data.t, data); -} - -/*! \overload - Adds the provided single data point as \a t, \a key and \a value tuple to the current data - \see removeData -*/ -void QCPCurve::addData(double t, double key, double value) -{ - QCPCurveData newData; - newData.t = t; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.t, newData); -} - -/*! \overload - - Adds the provided single data point as \a key and \a value pair to the current data The t - parameter of the data point is set to the t of the last data point plus 1. If there is no last - data point, t will be set to 0. - - \see removeData -*/ -void QCPCurve::addData(double key, double value) -{ - QCPCurveData newData; - if (!mData->isEmpty()) - newData.t = (mData->constEnd()-1).key()+1; - else - newData.t = 0; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.t, newData); -} - -/*! \overload - Adds the provided data points as \a t, \a key and \a value tuples to the current data. - \see removeData -*/ -void QCPCurve::addData(const QVector &ts, const QVector &keys, const QVector &values) -{ - int n = ts.size(); - n = qMin(n, keys.size()); - n = qMin(n, values.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } -} - -/*! - Removes all data points with curve parameter t smaller than \a t. - \see addData, clearData -*/ -void QCPCurve::removeDataBefore(double t) -{ - QCPCurveDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < t) - it = mData->erase(it); -} - -/*! - Removes all data points with curve parameter t greater than \a t. - \see addData, clearData -*/ -void QCPCurve::removeDataAfter(double t) -{ - if (mData->isEmpty()) return; - QCPCurveDataMap::iterator it = mData->upperBound(t); - while (it != mData->end()) - it = mData->erase(it); -} - -/*! - Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is - greater or equal to \a tot, the function does nothing. To remove a single data point with known - t, use \ref removeData(double t). - - \see addData, clearData -*/ -void QCPCurve::removeData(double fromt, double tot) -{ - if (fromt >= tot || mData->isEmpty()) return; - QCPCurveDataMap::iterator it = mData->upperBound(fromt); - QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \overload - - Removes a single data point at curve parameter \a t. If the position is not known with absolute - precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness - interval around the suspected position, depeding on the precision with which the curve parameter - is known. - - \see addData, clearData -*/ -void QCPCurve::removeData(double t) -{ - mData->remove(t); -} - -/*! - Removes all data points. - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPCurve::clearData() -{ - mData->clear(); -} - -/* inherits documentation from base class */ -double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - return pointDistance(pos); - else - return -1; -} - -/* inherits documentation from base class */ -void QCPCurve::draw(QCPPainter *painter) -{ - if (mData->isEmpty()) return; - - // allocate line vector: - QVector *lineData = new QVector; - - // fill with curve data: - getCurveData(lineData); - - // check data validity if flag set: -#ifdef QCUSTOMPLOT_CHECK_DATA - QCPCurveDataMap::const_iterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++it) - { - if (QCP::isInvalidData(it.value().t) || - QCP::isInvalidData(it.value().key, it.value().value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); - } -#endif - - // draw curve fill: - if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) - { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(QPolygonF(*lineData)); - } - - // draw curve line: - if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: - if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && - painter->pen().style() == Qt::SolidLine && - !painter->modes().testFlag(QCPPainter::pmVectorized) && - !painter->modes().testFlag(QCPPainter::pmNoCaching)) - { - int i = 0; - bool lastIsNan = false; - const int lineDataSize = lineData->size(); - while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN - ++i; - ++i; // because drawing works in 1 point retrospect - while (i < lineDataSize) - { - if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line - { - if (!lastIsNan) - painter->drawLine(lineData->at(i-1), lineData->at(i)); - else - lastIsNan = false; - } else - lastIsNan = true; - ++i; - } - } else - { - int segmentStart = 0; - int i = 0; - const int lineDataSize = lineData->size(); - while (i < lineDataSize) - { - if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line - { - painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point - segmentStart = i+1; - } - ++i; - } - // draw last segment: - painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); - } - } - - // draw scatters: - if (!mScatterStyle.isNone()) - drawScatterPlot(painter, lineData); - - // free allocated line data: - delete lineData; -} - -/* inherits documentation from base class */ -void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); - } - } -} - -/*! \internal - - Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of - the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. -*/ -void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const -{ - // draw scatter point symbols: - applyScattersAntialiasingHint(painter); - mScatterStyle.applyTo(painter, mPen); - for (int i=0; isize(); ++i) - if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) - mScatterStyle.drawShape(painter, pointData->at(i)); -} - -/*! \internal - - called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the - line of the curve. - - Line segments that aren't visible in the current axis rect are handled in an optimized way. They - are projected onto a rectangle slightly larger than the visible axis rect and simplified - regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside - the visible axis rect by generating new temporary points on the outer rect if necessary. - - Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref - getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. -*/ -void QCPCurve::getCurveData(QVector *lineData) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - // add margins to rect to compensate for stroke width - double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety - if (!mScatterStyle.isNone()) - strokeMargin = qMax(strokeMargin, mScatterStyle.size()); - double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); - double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); - double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); - double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); - int currentRegion; - QCPCurveDataMap::const_iterator it = mData->constBegin(); - QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1; - int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom); - QVector trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right) - while (it != mData->constEnd()) - { - currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); - if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R - { - if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal - { - QPointF crossA, crossB; - if (prevRegion == 5) // we're coming from R, so add this point optimized - { - lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom)); - // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point - *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); - } else if (mayTraverse(prevRegion, currentRegion) && - getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB)) - { - // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point: - QVector beforeTraverseCornerPoints, afterTraverseCornerPoints; - getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints); - if (it != mData->constBegin()) - { - *lineData << beforeTraverseCornerPoints; - lineData->append(crossA); - lineData->append(crossB); - *lineData << afterTraverseCornerPoints; - } else - { - lineData->append(crossB); - *lineData << afterTraverseCornerPoints; - trailingPoints << beforeTraverseCornerPoints << crossA ; - } - } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s) - { - *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); - } - } else // segment does end in R, so we add previous point optimized and this point at original position - { - if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end - trailingPoints << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); - else - lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom)); - lineData->append(coordsToPixels(it.value().key, it.value().value)); - } - } else // region didn't change - { - if (currentRegion == 5) // still in R, keep adding original points - { - lineData->append(coordsToPixels(it.value().key, it.value().value)); - } else // still outside R, no need to add anything - { - // see how this is not doing anything? That's the main optimization... - } - } - prevIt = it; - prevRegion = currentRegion; - ++it; - } - *lineData << trailingPoints; -} - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a - rectLeft, \a rectTop, \a rectRight, and \a rectBottom. - - The regions are enumerated from top to bottom and left to right: - - - - - -
147
258
369
- - With the rectangle being region 5, and the outer regions extending infinitely outwards. In the - curve optimization algorithm, region 5 is considered to be the visible portion of the plot. -*/ -int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const -{ - if (x < rectLeft) // region 123 - { - if (y > rectTop) - return 1; - else if (y < rectBottom) - return 3; - else - return 2; - } else if (x > rectRight) // region 789 - { - if (y > rectTop) - return 7; - else if (y < rectBottom) - return 9; - else - return 8; - } else // region 456 - { - if (y > rectTop) - return 4; - else if (y < rectBottom) - return 6; - else - return 5; - } -} - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - This method is used in case the current segment passes from inside the visible rect (region 5, - see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by - the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). - - It returns the intersection point of the segment with the border of region 5. - - For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or - whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or - leaving it. It is important though that \a otherRegion correctly identifies the other region not - equal to 5. -*/ -QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const -{ - double intersectKey = rectLeft; // initial value is just fail-safe - double intersectValue = rectTop; // initial value is just fail-safe - switch (otherRegion) - { - case 1: // top and left edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - case 2: // left edge - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - break; - } - case 3: // bottom and left edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - case 4: // top edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - break; - } - case 5: - { - break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table - } - case 6: // bottom edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - break; - } - case 7: // top and right edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - case 8: // right edge - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - break; - } - case 9: // bottom and right edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - } - return coordsToPixels(intersectKey, intersectValue); -} - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - In situations where a single segment skips over multiple regions it might become necessary to add - extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment - doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. - This method provides these points that must be added, assuming the original segment doesn't - start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by - \ref getTraverseCornerPoints.) - - For example, consider a segment which directly goes from region 4 to 2 but originally is far out - to the top left such that it doesn't cross region 5. Naively optimizing these points by - projecting them on the top and left borders of region 5 will create a segment that surely crosses - 5, creating a visual artifact in the plot. This method prevents this by providing extra points at - the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without - traversing 5. -*/ -QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const -{ - QVector result; - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 2: { result << coordsToPixels(rectLeft, rectTop); break; } - case 4: { result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; } - case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } - else - { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } - break; - } - } - break; - } - case 2: - { - switch (currentRegion) - { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 3: - { - switch (currentRegion) - { - case 2: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 6: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; } - case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; } - case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } - else - { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } - break; - } - } - break; - } - case 4: - { - switch (currentRegion) - { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 5: - { - switch (currentRegion) - { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } - } - break; - } - case 6: - { - switch (currentRegion) - { - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } - } - break; - } - case 7: - { - switch (currentRegion) - { - case 4: { result << coordsToPixels(rectRight, rectTop); break; } - case 8: { result << coordsToPixels(rectRight, rectTop); break; } - case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; } - case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } - else - { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } - break; - } - } - break; - } - case 8: - { - switch (currentRegion) - { - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } - } - break; - } - case 9: - { - switch (currentRegion) - { - case 6: { result << coordsToPixels(rectRight, rectBottom); break; } - case 8: { result << coordsToPixels(rectRight, rectBottom); break; } - case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; } - case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } - else - { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } - break; - } - } - break; - } - } - return result; -} - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref - getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion - nor \a currentRegion is 5 itself. - - If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the - segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref - getTraverse). -*/ -bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const -{ - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 4: - case 7: - case 2: - case 3: return false; - default: return true; - } - } - case 2: - { - switch (currentRegion) - { - case 1: - case 3: return false; - default: return true; - } - } - case 3: - { - switch (currentRegion) - { - case 1: - case 2: - case 6: - case 9: return false; - default: return true; - } - } - case 4: - { - switch (currentRegion) - { - case 1: - case 7: return false; - default: return true; - } - } - case 5: return false; // should never occur - case 6: - { - switch (currentRegion) - { - case 3: - case 9: return false; - default: return true; - } - } - case 7: - { - switch (currentRegion) - { - case 1: - case 4: - case 8: - case 9: return false; - default: return true; - } - } - case 8: - { - switch (currentRegion) - { - case 7: - case 9: return false; - default: return true; - } - } - case 9: - { - switch (currentRegion) - { - case 3: - case 6: - case 8: - case 7: return false; - default: return true; - } - } - default: return true; - } -} - - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - This method assumes that the \ref mayTraverse test has returned true, so there is a chance the - segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible - region 5. - - The return value of this method indicates whether the segment actually traverses region 5 or not. - - If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and - exit points of region 5. They will become the optimized points for that segment. -*/ -bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const -{ - QList intersections; // x of QPointF corresponds to key and y to value - if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis - { - // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here - intersections.append(QPointF(key, rectBottom)); // direction will be taken care of at end of method - intersections.append(QPointF(key, rectTop)); - } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis - { - // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here - intersections.append(QPointF(rectLeft, value)); // direction will be taken care of at end of method - intersections.append(QPointF(rectRight, value)); - } else // line is skewed - { - double gamma; - double keyPerValue = (key-prevKey)/(value-prevValue); - // check top of rect: - gamma = prevKey + (rectTop-prevValue)*keyPerValue; - if (gamma >= rectLeft && gamma <= rectRight) - intersections.append(QPointF(gamma, rectTop)); - // check bottom of rect: - gamma = prevKey + (rectBottom-prevValue)*keyPerValue; - if (gamma >= rectLeft && gamma <= rectRight) - intersections.append(QPointF(gamma, rectBottom)); - double valuePerKey = 1.0/keyPerValue; - // check left of rect: - gamma = prevValue + (rectLeft-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectLeft, gamma)); - // check right of rect: - gamma = prevValue + (rectRight-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectRight, gamma)); - } - - // handle cases where found points isn't exactly 2: - if (intersections.size() > 2) - { - // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: - double distSqrMax = 0; - QPointF pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = intersections.at(i); - pv2 = intersections.at(k); - distSqrMax = distSqr; - } - } - } - intersections = QList() << pv1 << pv2; - } else if (intersections.size() != 2) - { - // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment - return false; - } - - // possibly re-sort points so optimized point segment has same direction as original segment: - if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction - intersections.move(0, 1); - crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); - crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); - return true; -} - -/*! \internal - - This function is part of the curve optimization algorithm of \ref getCurveData. - - This method assumes that the \ref getTraverse test has returned true, so the segment definitely - traverses the visible region 5 when going from \a prevRegion to \a currentRegion. - - In certain situations it is not sufficient to merely generate the entry and exit points of the - segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in - addition to traversing region 5, skips another region outside of region 5, which makes it - necessary to add an optimized corner point there (very similar to the job \ref - getOptimizedCornerPoints does for segments that are completely in outside regions and don't - traverse 5). - - As an example, consider a segment going from region 1 to region 6, traversing the lower left - corner of region 5. In this configuration, the segment additionally crosses the border between - region 1 and 2 before entering region 5. This makes it necessary to add an additional point in - the top left corner, before adding the optimized traverse points. So in this case, the output - parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be - empty. - - In some cases, such as when going from region 1 to 9, it may even be necessary to add additional - corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse - return the respective corner points. -*/ -void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const -{ - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } - } - break; - } - case 2: - { - switch (currentRegion) - { - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 3: - { - switch (currentRegion) - { - case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; } - case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } - } - break; - } - case 4: - { - switch (currentRegion) - { - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 5: { break; } // shouldn't happen because this method only handles full traverses - case 6: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } - } - break; - } - case 7: - { - switch (currentRegion) - { - case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } - case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } - } - break; - } - case 8: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - } - break; - } - case 9: - { - switch (currentRegion) - { - case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } - case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - } -} - -/*! \internal - - Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a - pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in - \ref selectTest. -*/ -double QCPCurve::pointDistance(const QPointF &pixelPoint) const -{ - if (mData->isEmpty()) - { - qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; - return 500; - } - if (mData->size() == 1) - { - QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); - return QVector2D(dataPoint-pixelPoint).length(); - } - - // calculate minimum distance to line segments: - QVector *lineData = new QVector; - getCurveData(lineData); - double minDistSqr = std::numeric_limits::max(); - for (int i=0; isize()-1; ++i) - { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - delete lineData; - return qSqrt(minDistSqr); -} - -/* inherits documentation from base class */ -QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - - QCPCurveDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (!qIsNaN(current) && !qIsNaN(it.value().value)) - { - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} - -/* inherits documentation from base class */ -QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - - QCPCurveDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value; - if (!qIsNaN(current) && !qIsNaN(it.value().key)) - { - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPBarsGroup -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPBarsGroup - \brief Groups multiple QCPBars together so they appear side by side - - \image html QCPBarsGroup.png - - When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable - to have them appearing next to each other at each key. This is what adding the respective QCPBars - plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each - other, see \ref QCPBars::moveAbove.) - - \section qcpbarsgroup-usage Usage - - To add a QCPBars plottable to the group, create a new group and then add the respective bars - intances: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation - Alternatively to appending to the group like shown above, you can also set the group on the - QCPBars plottable via \ref QCPBars::setBarsGroup. - - The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The - bars in this group appear in the plot in the order they were appended. To insert a bars plottable - at a certain index position, or to reposition a bars plottable which is already in the group, use - \ref insert. - - To remove specific bars from the group, use either \ref remove or call \ref - QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. - - To clear the entire group, call \ref clear, or simply delete the group. - - \section qcpbarsgroup-example Example - - The image above is generated with the following code: - \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example -*/ - -/* start of documentation of inline functions */ - -/*! \fn QList QCPBarsGroup::bars() const - - Returns all bars currently in this group. - - \see bars(int index) -*/ - -/*! \fn int QCPBarsGroup::size() const - - Returns the number of QCPBars plottables that are part of this group. - -*/ - -/*! \fn bool QCPBarsGroup::isEmpty() const - - Returns whether this bars group is empty. - - \see size -*/ - -/*! \fn bool QCPBarsGroup::contains(QCPBars *bars) - - Returns whether the specified \a bars plottable is part of this group. - -*/ - -/* end of documentation of inline functions */ - -/*! - Constructs a new bars group for the specified QCustomPlot instance. -*/ -QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot), - mSpacingType(stAbsolute), - mSpacing(4) -{ -} - -QCPBarsGroup::~QCPBarsGroup() -{ - clear(); -} - -/*! - Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. - - The actual spacing can then be specified with \ref setSpacing. - - \see setSpacing -*/ -void QCPBarsGroup::setSpacingType(SpacingType spacingType) -{ - mSpacingType = spacingType; -} - -/*! - Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is - defined by the current \ref SpacingType, which can be set with \ref setSpacingType. - - \see setSpacingType -*/ -void QCPBarsGroup::setSpacing(double spacing) -{ - mSpacing = spacing; -} - -/*! - Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars - exists, returns 0. - - \see bars(), size -*/ -QCPBars *QCPBarsGroup::bars(int index) const -{ - if (index >= 0 && index < mBars.size()) - { - return mBars.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } -} - -/*! - Removes all QCPBars plottables from this group. - - \see isEmpty -*/ -void QCPBarsGroup::clear() -{ - foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay - bars->setBarsGroup(0); // removes itself via removeBars -} - -/*! - Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref - QCPBars::setBarsGroup on the \a bars instance. - - \see insert, remove -*/ -void QCPBarsGroup::append(QCPBars *bars) -{ - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - else - qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); -} - -/*! - Inserts the specified \a bars plottable into this group at the specified index position \a i. - This gives you full control over the ordering of the bars. - - \a bars may already be part of this group. In that case, \a bars is just moved to the new index - position. - - \see append, remove -*/ -void QCPBarsGroup::insert(int i, QCPBars *bars) -{ - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - // first append to bars list normally: - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - // then move to according position: - mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); -} - -/*! - Removes the specified \a bars plottable from this group. - - \see contains, clear -*/ -void QCPBarsGroup::remove(QCPBars *bars) -{ - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (mBars.contains(bars)) - bars->setBarsGroup(0); - else - qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); -} - -/*! \internal - - Adds the specified \a bars to the internal mBars list of bars. This method does not change the - barsGroup property on \a bars. - - \see unregisterBars -*/ -void QCPBarsGroup::registerBars(QCPBars *bars) -{ - if (!mBars.contains(bars)) - mBars.append(bars); -} - -/*! \internal - - Removes the specified \a bars from the internal mBars list of bars. This method does not change - the barsGroup property on \a bars. - - \see registerBars -*/ -void QCPBarsGroup::unregisterBars(QCPBars *bars) -{ - mBars.removeOne(bars); -} - -/*! \internal - - Returns the pixel offset in the key dimension the specified \a bars plottable should have at the - given key coordinate \a keyCoord. The offset is relative to the pixel position of the key - coordinate \a keyCoord. -*/ -double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) -{ - // find list of all base bars in case some mBars are stacked: - QList baseBars; - foreach (const QCPBars *b, mBars) - { - while (b->barBelow()) - b = b->barBelow(); - if (!baseBars.contains(b)) - baseBars.append(b); - } - // find base bar this "bars" is stacked on: - const QCPBars *thisBase = bars; - while (thisBase->barBelow()) - thisBase = thisBase->barBelow(); - - // determine key pixel offset of this base bars considering all other base bars in this barsgroup: - double result = 0; - int index = baseBars.indexOf(thisBase); - if (index >= 0) - { - int startIndex; - double lowerPixelWidth, upperPixelWidth; - if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) - { - return result; - } else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center - { - if (baseBars.size() % 2 == 0) // even number of bars - { - startIndex = baseBars.size()/2-1; - result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing - } else // uneven number of bars - { - startIndex = (baseBars.size()-1)/2-1; - baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar - result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing - } - for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars - { - baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth); - result -= getPixelSpacing(baseBars.at(i), keyCoord); - } - // finally half of our bars width: - baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; - } else // bar is to the right of center - { - if (baseBars.size() % 2 == 0) // even number of bars - { - startIndex = baseBars.size()/2; - result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing - } else // uneven number of bars - { - startIndex = (baseBars.size()-1)/2+1; - baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar - result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing - } - for (int i=startIndex; igetPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result += qAbs(upperPixelWidth-lowerPixelWidth); - result += getPixelSpacing(baseBars.at(i), keyCoord); - } - // finally half of our bars width: - baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; - } - } - return result; -} - -/*! \internal - - Returns the spacing in pixels which is between this \a bars and the following one, both at the - key coordinate \a keyCoord. - - \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only - needed to get acces to the key axis transformation and axis rect for the modes \ref - stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in - \ref stPlotCoords on a logarithmic axis. -*/ -double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) -{ - switch (mSpacingType) - { - case stAbsolute: - { - return mSpacing; - } - case stAxisRectRatio: - { - if (bars->keyAxis()->orientation() == Qt::Horizontal) - return bars->keyAxis()->axisRect()->width()*mSpacing; - else - return bars->keyAxis()->axisRect()->height()*mSpacing; - } - case stPlotCoords: - { - double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); - return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; - } - } - return 0; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPBarData -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPBarData - \brief Holds the data of one single data point (one bar) for QCPBars. - - The container for storing multiple data points is \ref QCPBarDataMap. - - The stored data is: - \li \a key: coordinate on the key axis of this bar - \li \a value: height coordinate on the value axis of this bar - - \see QCPBarDataaMap -*/ - -/*! - Constructs a bar data point with key and value set to zero. -*/ -QCPBarData::QCPBarData() : - key(0), - value(0) -{ -} - -/*! - Constructs a bar data point with the specified \a key and \a value. -*/ -QCPBarData::QCPBarData(double key, double value) : - key(key), - value(value) -{ -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPBars -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPBars - \brief A plottable representing a bar chart in a plot. - - \image html QCPBars.png - - To plot data, assign it with the \ref setData or \ref addData functions. - - \section appearance Changing the appearance - - The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). - The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. - - Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other - (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear - stacked. - - If you would like to group multiple QCPBars plottables together so they appear side by side as - shown below, use QCPBarsGroup. - - \image html QCPBarsGroup.png - - \section usage Usage - - Like all data representing objects in QCustomPlot, the QCPBars is a plottable - (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies - (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) - - Usually, you first create an instance: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 - add it to the customPlot with QCustomPlot::addPlottable: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2 - and then modify the properties of the newly created plottable, e.g.: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3 -*/ - -/* start of documentation of inline functions */ - -/*! \fn QCPBars *QCPBars::barBelow() const - Returns the bars plottable that is directly below this bars plottable. - If there is no such plottable, returns 0. - - \see barAbove, moveBelow, moveAbove -*/ - -/*! \fn QCPBars *QCPBars::barAbove() const - Returns the bars plottable that is directly above this bars plottable. - If there is no such plottable, returns 0. - - \see barBelow, moveBelow, moveAbove -*/ - -/* end of documentation of inline functions */ - -/*! - Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value - axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have - the same orientation. If either of these restrictions is violated, a corresponding message is - printed to the debug output (qDebug), the construction is not aborted, though. - - The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the bar chart. -*/ -QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(new QCPBarDataMap), - mWidth(0.75), - mWidthType(wtPlotCoords), - mBarsGroup(0), - mBaseValue(0) -{ - // modify inherited properties from abstract plottable: - mPen.setColor(Qt::blue); - mPen.setStyle(Qt::SolidLine); - mBrush.setColor(QColor(40, 50, 255, 30)); - mBrush.setStyle(Qt::SolidPattern); - mSelectedPen = mPen; - mSelectedPen.setWidthF(2.5); - mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen - mSelectedBrush = mBrush; -} - -QCPBars::~QCPBars() -{ - setBarsGroup(0); - if (mBarBelow || mBarAbove) - connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking - delete mData; -} - -/*! - Sets the width of the bars. - - How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...), - depends on the currently set width type, see \ref setWidthType and \ref WidthType. -*/ -void QCPBars::setWidth(double width) -{ - mWidth = width; -} - -/*! - Sets how the width of the bars is defined. See the documentation of \ref WidthType for an - explanation of the possible values for \a widthType. - - The default value is \ref wtPlotCoords. - - \see setWidth -*/ -void QCPBars::setWidthType(QCPBars::WidthType widthType) -{ - mWidthType = widthType; -} - -/*! - Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref - QCPBarsGroup::append. - - To remove this QCPBars from any group, set \a barsGroup to 0. -*/ -void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) -{ - // deregister at old group: - if (mBarsGroup) - mBarsGroup->unregisterBars(this); - mBarsGroup = barsGroup; - // register at new group: - if (mBarsGroup) - mBarsGroup->registerBars(this); -} - -/*! - Sets the base value of this bars plottable. - - The base value defines where on the value coordinate the bars start. How far the bars extend from - the base value is given by their individual value data. For example, if the base value is set to - 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at - 3. - - For stacked bars, only the base value of the bottom-most QCPBars has meaning. - - The default base value is 0. -*/ -void QCPBars::setBaseValue(double baseValue) -{ - mBaseValue = baseValue; -} - -/*! - Replaces the current data with the provided \a data. - - If \a copy is set to true, data points in \a data will only be copied. if false, the plottable - takes ownership of the passed data and replaces the internal data pointer with it. This is - significantly faster than copying for large datasets. -*/ -void QCPBars::setData(QCPBarDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } -} - -/*! \overload - - Replaces the current data with the provided points in \a key and \a value tuples. The - provided vectors should have equal length. Else, the number of added points will be the size of - the smallest vector. -*/ -void QCPBars::setData(const QVector &key, const QVector &value) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } -} - -/*! - Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear - below the bars of \a bars. The move target \a bars must use the same key and value axis as this - plottable. - - Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already - has a bars object below itself, this bars object is inserted between the two. If this bars object - is already between two other bars, the two other bars will be stacked on top of each other after - the operation. - - To remove this bars plottable from any stacking, set \a bars to 0. - - \see moveBelow, barAbove, barBelow -*/ -void QCPBars::moveBelow(QCPBars *bars) -{ - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar below it: - if (bars) - { - if (bars->mBarBelow) - connectBars(bars->mBarBelow.data(), this); - connectBars(this, bars); - } -} - -/*! - Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear - above the bars of \a bars. The move target \a bars must use the same key and value axis as this - plottable. - - Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already - has a bars object above itself, this bars object is inserted between the two. If this bars object - is already between two other bars, the two other bars will be stacked on top of each other after - the operation. - - To remove this bars plottable from any stacking, set \a bars to 0. - - \see moveBelow, barBelow, barAbove -*/ -void QCPBars::moveAbove(QCPBars *bars) -{ - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar above it: - if (bars) - { - if (bars->mBarAbove) - connectBars(this, bars->mBarAbove.data()); - connectBars(bars, this); - } -} - -/*! - Adds the provided data points in \a dataMap to the current data. - \see removeData -*/ -void QCPBars::addData(const QCPBarDataMap &dataMap) -{ - mData->unite(dataMap); -} - -/*! \overload - Adds the provided single data point in \a data to the current data. - \see removeData -*/ -void QCPBars::addData(const QCPBarData &data) -{ - mData->insertMulti(data.key, data); -} - -/*! \overload - Adds the provided single data point as \a key and \a value tuple to the current data - \see removeData -*/ -void QCPBars::addData(double key, double value) -{ - QCPBarData newData; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.key, newData); -} - -/*! \overload - Adds the provided data points as \a key and \a value tuples to the current data. - \see removeData -*/ -void QCPBars::addData(const QVector &keys, const QVector &values) -{ - int n = keys.size(); - n = qMin(n, values.size()); - QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } -} - -/*! - Removes all data points with key smaller than \a key. - \see addData, clearData -*/ -void QCPBars::removeDataBefore(double key) -{ - QCPBarDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); -} - -/*! - Removes all data points with key greater than \a key. - \see addData, clearData -*/ -void QCPBars::removeDataAfter(double key) -{ - if (mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); -} - -/*! - Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is - greater or equal to \a toKey, the function does nothing. To remove a single data point with known - key, use \ref removeData(double key). - - \see addData, clearData -*/ -void QCPBars::removeData(double fromKey, double toKey) -{ - if (fromKey >= toKey || mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(fromKey); - QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \overload - - Removes a single data point at \a key. If the position is not known with absolute precision, - consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval - around the suspected position, depeding on the precision with which the key is known. - - \see addData, clearData -*/ -void QCPBars::removeData(double key) -{ - mData->remove(key); -} - -/*! - Removes all data points. - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPBars::clearData() -{ - mData->clear(); -} - -/* inherits documentation from base class */ -double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - QCPBarDataMap::ConstIterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++it) - { - if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) - return mParentPlot->selectionTolerance()*0.99; - } - } - return -1; -} - -/* inherits documentation from base class */ -void QCPBars::draw(QCPPainter *painter) -{ - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mData->isEmpty()) return; - - QCPBarDataMap::const_iterator it, lower, upperEnd; - getVisibleDataBounds(lower, upperEnd); - for (it = lower; it != upperEnd; ++it) - { - // check data validity if flag set: -#ifdef QCUSTOMPLOT_CHECK_DATA - if (QCP::isInvalidData(it.value().key, it.value().value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); -#endif - QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); - // draw bar fill: - if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) - { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(barPolygon); - } - // draw bar line: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - painter->drawPolyline(barPolygon); - } - } -} - -/* inherits documentation from base class */ -void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setBrush(mBrush); - painter->setPen(mPen); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); -} - -/*! \internal - - called by \ref draw to determine which data (key) range is visible at the current key axis range - setting, so only that needs to be processed. It also takes into account the bar width. - - \a lower returns an iterator to the lowest data point that needs to be taken into account when - plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a - lower may still be just outside the visible range. - - \a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a - upperEnd may also lie just outside of the visible range. - - if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. -*/ -void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const -{ - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) - { - lower = mData->constEnd(); - upperEnd = mData->constEnd(); - return; - } - - // get visible data range as QMap iterators - lower = mData->lowerBound(mKeyAxis.data()->range().lower); - upperEnd = mData->upperBound(mKeyAxis.data()->range().upper); - double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); - double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); - bool isVisible = false; - // walk left from lbound to find lower bar that actually is completely outside visible pixel range: - QCPBarDataMap::const_iterator it = lower; - while (it != mData->constBegin()) - { - --it; - QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); - if (isVisible) - lower = it; - else - break; - } - // walk right from ubound to find upper bar that actually is completely outside visible pixel range: - it = upperEnd; - while (it != mData->constEnd()) - { - QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); - if (isVisible) - upperEnd = it+1; - else - break; - ++it; - } -} - -/*! \internal - - Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom - and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref - setBaseValue). -*/ -QPolygonF QCPBars::getBarPolygon(double key, double value) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } - - QPolygonF result; - double lowerPixelWidth, upperPixelWidth; - getPixelWidth(key, lowerPixelWidth, upperPixelWidth); - double base = getStackedBaseValue(key, value >= 0); - double basePixel = valueAxis->coordToPixel(base); - double valuePixel = valueAxis->coordToPixel(base+value); - double keyPixel = keyAxis->coordToPixel(key); - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, key); - if (keyAxis->orientation() == Qt::Horizontal) - { - result << QPointF(keyPixel+lowerPixelWidth, basePixel); - result << QPointF(keyPixel+lowerPixelWidth, valuePixel); - result << QPointF(keyPixel+upperPixelWidth, valuePixel); - result << QPointF(keyPixel+upperPixelWidth, basePixel); - } else - { - result << QPointF(basePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+upperPixelWidth); - result << QPointF(basePixel, keyPixel+upperPixelWidth); - } - return result; -} - -/*! \internal - - This function is used to determine the width of the bar at coordinate \a key, according to the - specified width (\ref setWidth) and width type (\ref setWidthType). - - The output parameters \a lower and \a upper return the number of pixels the bar extends to lower - and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a - lower is negative and \a upper positive). -*/ -void QCPBars::getPixelWidth(double key, double &lower, double &upper) const -{ - switch (mWidthType) - { - case wtAbsolute: - { - upper = mWidth*0.5; - lower = -upper; - if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) - qSwap(lower, upper); - break; - } - case wtAxisRectRatio: - { - if (mKeyAxis && mKeyAxis.data()->axisRect()) - { - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; - else - upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; - lower = -upper; - if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) - qSwap(lower, upper); - } else - qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; - break; - } - case wtPlotCoords: - { - if (mKeyAxis) - { - double keyPixel = mKeyAxis.data()->coordToPixel(key); - upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; - lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; - // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by - // coordinate transform which includes range direction - } else - qDebug() << Q_FUNC_INFO << "No key axis defined"; - break; - } - } -} - -/*! \internal - - This function is called to find at which value to start drawing the base of a bar at \a key, when - it is stacked on top of another QCPBars (e.g. with \ref moveAbove). - - positive and negative bars are separated per stack (positive are stacked above baseValue upwards, - negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the - bar for which we need the base value is negative, set \a positive to false. -*/ -double QCPBars::getStackedBaseValue(double key, bool positive) const -{ - if (mBarBelow) - { - double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack - // find bars of mBarBelow that are approximately at key and find largest one: - double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point - if (key == 0) - epsilon = 1e-6; - QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon); - QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon); - while (it != itEnd) - { - if ((positive && it.value().value > max) || - (!positive && it.value().value < max)) - max = it.value().value; - ++it; - } - // recurse down the bar-stack to find the total height: - return max + mBarBelow.data()->getStackedBaseValue(key, positive); - } else - return mBaseValue; -} - -/*! \internal - - Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) - currently above lower and below upper will become disconnected to lower/upper. - - If lower is zero, upper will be disconnected at the bottom. - If upper is zero, lower will be disconnected at the top. -*/ -void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) -{ - if (!lower && !upper) return; - - if (!lower) // disconnect upper at bottom - { - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - upper->mBarBelow = 0; - } else if (!upper) // disconnect lower at top - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - lower->mBarAbove = 0; - } else // connect lower and upper - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - lower->mBarAbove = upper; - upper->mBarBelow = lower; - } -} - -/* inherits documentation from base class */ -QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - // determine exact range of bars by including bar width and barsgroup offset: - if (haveLower && mKeyAxis) - { - double lowerPixelWidth, upperPixelWidth, keyPixel; - getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); - keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); - range.lower = mKeyAxis.data()->pixelToCoord(keyPixel); - } - if (haveUpper && mKeyAxis) - { - double lowerPixelWidth, upperPixelWidth, keyPixel; - getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); - keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); - range.upper = mKeyAxis.data()->pixelToCoord(keyPixel); - } - foundRange = haveLower && haveUpper; - return range; -} - -/* inherits documentation from base class */ -QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - range.lower = mBaseValue; - range.upper = mBaseValue; - bool haveLower = true; // set to true, because baseValue should always be visible in bar charts - bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts - double current; - - QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0); - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - - foundRange = true; // return true because bar charts always have the 0-line visible - return range; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPStatisticalBox -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPStatisticalBox - \brief A plottable representing a single statistical box in a plot. - - \image html QCPStatisticalBox.png - - To plot data, assign it with the individual parameter functions or use \ref setData to set all - parameters at once. The individual functions are: - \li \ref setMinimum - \li \ref setLowerQuartile - \li \ref setMedian - \li \ref setUpperQuartile - \li \ref setMaximum - - Additionally you can define a list of outliers, drawn as scatter datapoints: - \li \ref setOutliers - - \section appearance Changing the appearance - - The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change - the width of the box with \ref setWidth in plot coordinates (not pixels). - - Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref - setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top - (maximum) and bottom (minimum). - - The median indicator line has its own pen, \ref setMedianPen. - - If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the - backbone line might exceed the whisker bars by a few pixels due to the pen cap being not - perfectly flat. - - The Outlier data points are drawn as normal scatter points. Their look can be controlled with - \ref setOutlierStyle - - \section usage Usage - - Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable. - Usually, you first create an instance and add it to the customPlot: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1 - and then modify the properties of the newly created plottable, e.g.: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2 -*/ - -/*! - Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its - value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and - not have the same orientation. If either of these restrictions is violated, a corresponding - message is printed to the debug output (qDebug), the construction is not aborted, though. - - The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, - QCustomPlot then takes ownership of the statistical box. -*/ -QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mKey(0), - mMinimum(0), - mLowerQuartile(0), - mMedian(0), - mUpperQuartile(0), - mMaximum(0) -{ - setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); - setWhiskerWidth(0.2); - setWidth(0.5); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2.5)); - setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); - setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); - setWhiskerBarPen(QPen(Qt::black)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); -} - -/*! - Sets the key coordinate of the statistical box. -*/ -void QCPStatisticalBox::setKey(double key) -{ - mKey = key; -} - -/*! - Sets the parameter "minimum" of the statistical box plot. This is the position of the lower - whisker, typically the minimum measurement of the sample that's not considered an outlier. - - \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth -*/ -void QCPStatisticalBox::setMinimum(double value) -{ - mMinimum = value; -} - -/*! - Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the - box. The lower and the upper quartiles are the two statistical quartiles around the median of the - sample, they contain 50% of the sample data. - - \see setUpperQuartile, setPen, setBrush, setWidth -*/ -void QCPStatisticalBox::setLowerQuartile(double value) -{ - mLowerQuartile = value; -} - -/*! - Sets the parameter "median" of the statistical box plot. This is the value of the median mark - inside the quartile box. The median separates the sample data in half (50% of the sample data is - below/above the median). - - \see setMedianPen -*/ -void QCPStatisticalBox::setMedian(double value) -{ - mMedian = value; -} - -/*! - Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the - box. The lower and the upper quartiles are the two statistical quartiles around the median of the - sample, they contain 50% of the sample data. - - \see setLowerQuartile, setPen, setBrush, setWidth -*/ -void QCPStatisticalBox::setUpperQuartile(double value) -{ - mUpperQuartile = value; -} - -/*! - Sets the parameter "maximum" of the statistical box plot. This is the position of the upper - whisker, typically the maximum measurement of the sample that's not considered an outlier. - - \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth -*/ -void QCPStatisticalBox::setMaximum(double value) -{ - mMaximum = value; -} - -/*! - Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample - that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers - and displayed as such. - - \see setOutlierStyle -*/ -void QCPStatisticalBox::setOutliers(const QVector &values) -{ - mOutliers = values; -} - -/*! - Sets all parameters of the statistical box plot at once. - - \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum -*/ -void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) -{ - setKey(key); - setMinimum(minimum); - setLowerQuartile(lowerQuartile); - setMedian(median); - setUpperQuartile(upperQuartile); - setMaximum(maximum); -} - -/*! - Sets the width of the box in key coordinates. - - \see setWhiskerWidth -*/ -void QCPStatisticalBox::setWidth(double width) -{ - mWidth = width; -} - -/*! - Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. - - \see setWidth -*/ -void QCPStatisticalBox::setWhiskerWidth(double width) -{ - mWhiskerWidth = width; -} - -/*! - Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). - - Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching - a few pixels past the whisker bars, when using a non-zero pen width. - - \see setWhiskerBarPen -*/ -void QCPStatisticalBox::setWhiskerPen(const QPen &pen) -{ - mWhiskerPen = pen; -} - -/*! - Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at - each end of the whisker backbone). - - \see setWhiskerPen -*/ -void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) -{ - mWhiskerBarPen = pen; -} - -/*! - Sets the pen used for drawing the median indicator line inside the statistical box. -*/ -void QCPStatisticalBox::setMedianPen(const QPen &pen) -{ - mMedianPen = pen; -} - -/*! - Sets the appearance of the outlier data points. - - \see setOutliers -*/ -void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) -{ - mOutlierStyle = style; -} - -/* inherits documentation from base class */ -void QCPStatisticalBox::clearData() -{ - setOutliers(QVector()); - setKey(0); - setMinimum(0); - setLowerQuartile(0); - setMedian(0); - setUpperQuartile(0); - setMaximum(0); -} - -/* inherits documentation from base class */ -double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - // quartile box: - QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - QCPRange valueRange(mLowerQuartile, mUpperQuartile); - if (keyRange.contains(posKey) && valueRange.contains(posValue)) - return mParentPlot->selectionTolerance()*0.99; - - // min/max whiskers: - if (QCPRange(mMinimum, mMaximum).contains(posValue)) - return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); - } - return -1; -} - -/* inherits documentation from base class */ -void QCPStatisticalBox::draw(QCPPainter *painter) -{ - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - // check data validity if flag set: -#ifdef QCUSTOMPLOT_CHECK_DATA - if (QCP::isInvalidData(mKey, mMedian) || - QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || - QCP::isInvalidData(mMinimum, mMaximum)) - qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); - for (int i=0; isave(); - painter->setClipRect(quartileBox, Qt::IntersectClip); - drawMedian(painter); - painter->restore(); - - drawWhiskers(painter); - drawOutliers(painter); -} - -/* inherits documentation from base class */ -void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->setBrush(mBrush); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); -} - -/*! \internal - - Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel - coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so - the median doesn't draw outside the quartile box). -*/ -void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const -{ - QRectF box; - box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); - box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(box); - if (quartileBox) - *quartileBox = box; -} - -/*! \internal - - Draws the median line inside the quartile box. -*/ -void QCPStatisticalBox::drawMedian(QCPPainter *painter) const -{ - QLineF medianLine; - medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); - medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); - applyDefaultAntialiasingHint(painter); - painter->setPen(mMedianPen); - painter->drawLine(medianLine); -} - -/*! \internal - - Draws both whisker backbones and bars. -*/ -void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const -{ - QLineF backboneMin, backboneMax, barMin, barMax; - backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); - backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); - barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); - barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); - applyErrorBarsAntialiasingHint(painter); - painter->setPen(mWhiskerPen); - painter->drawLine(backboneMin); - painter->drawLine(backboneMax); - painter->setPen(mWhiskerBarPen); - painter->drawLine(barMin); - painter->drawLine(barMax); -} - -/*! \internal - - Draws the outlier scatter points. -*/ -void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const -{ - applyScattersAntialiasingHint(painter); - mOutlierStyle.applyTo(painter, mPen); - for (int i=0; i 0) - return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - else if (mKey > 0) - return QCPRange(mKey, mKey+mWidth*0.5); - else - { - foundRange = false; - return QCPRange(); - } - } - foundRange = false; - return QCPRange(); -} - -/* inherits documentation from base class */ -QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) - values.reserve(mOutliers.size() + 5); - values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; - values << mOutliers; - // go through values and find the ones in legal range: - bool haveUpper = false; - bool haveLower = false; - double upper = 0; - double lower = 0; - for (int i=0; i 0) || - (inSignDomain == sdBoth)) - { - if (values.at(i) > upper || !haveUpper) - { - upper = values.at(i); - haveUpper = true; - } - if (values.at(i) < lower || !haveLower) - { - lower = values.at(i); - haveLower = true; - } - } - } - // return the bounds if we found some sensible values: - if (haveLower && haveUpper) - { - foundRange = true; - return QCPRange(lower, upper); - } else // might happen if all values are in other sign domain - { - foundRange = false; - return QCPRange(); - } -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPColorMapData -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPColorMapData - \brief Holds the two-dimensional data of a QCPColorMap plottable. - - This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref - QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a - color, depending on the value. - - The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). - Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref - setKeyRange, \ref setValueRange). - - The data cells can be accessed in two ways: They can be directly addressed by an integer index - with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot - coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are - provided by the functions \ref coordToCell and \ref cellToCoord. - - This class also buffers the minimum and maximum values that are in the data set, to provide - QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value - that is greater than the current maximum increases this maximum to the new value. However, - setting the cell that currently holds the maximum value to a smaller value doesn't decrease the - maximum again, because finding the true new maximum would require going through the entire data - array, which might be time consuming. The same holds for the data minimum. This functionality is - given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the - true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience - parameter \a recalculateDataBounds which may be set to true to automatically call \ref - recalculateDataBounds internally. -*/ - -/* start of documentation of inline functions */ - -/*! \fn bool QCPColorMapData::isEmpty() const - - Returns whether this instance carries no data. This is equivalent to having a size where at least - one of the dimensions is 0 (see \ref setSize). -*/ - -/* end of documentation of inline functions */ - -/*! - Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction - and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap - at the coordinates \a keyRange and \a valueRange. - - \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange -*/ -QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : - mKeySize(0), - mValueSize(0), - mKeyRange(keyRange), - mValueRange(valueRange), - mIsEmpty(true), - mData(0), - mDataModified(true) -{ - setSize(keySize, valueSize); - fill(0); -} - -QCPColorMapData::~QCPColorMapData() -{ - if (mData) - delete[] mData; -} - -/*! - Constructs a new QCPColorMapData instance copying the data and range of \a other. -*/ -QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : - mKeySize(0), - mValueSize(0), - mIsEmpty(true), - mData(0), - mDataModified(true) -{ - *this = other; -} - -/*! - Overwrites this color map data instance with the data stored in \a other. -*/ -QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) -{ - if (&other != this) - { - const int keySize = other.keySize(); - const int valueSize = other.valueSize(); - setSize(keySize, valueSize); - setRange(other.keyRange(), other.valueRange()); - if (!mIsEmpty) - memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); - mDataBounds = other.mDataBounds; - mDataModified = true; - } - return *this; -} - -/* undocumented getter */ -double QCPColorMapData::data(double key, double value) -{ - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - return mData[valueCell*mKeySize + keyCell]; - else - return 0; -} - -/* undocumented getter */ -double QCPColorMapData::cell(int keyIndex, int valueIndex) -{ - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - return mData[valueIndex*mKeySize + keyIndex]; - else - return 0; -} - -/*! - Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in - the value dimension. - - The current data is discarded and the map cells are set to 0, unless the map had already the - requested size. - - Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref - isEmpty returns true. - - \see setRange, setKeySize, setValueSize -*/ -void QCPColorMapData::setSize(int keySize, int valueSize) -{ - if (keySize != mKeySize || valueSize != mValueSize) - { - mKeySize = keySize; - mValueSize = valueSize; - if (mData) - delete[] mData; - mIsEmpty = mKeySize == 0 || mValueSize == 0; - if (!mIsEmpty) - { -#ifdef __EXCEPTIONS - try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message -#endif - mData = new double[mKeySize*mValueSize]; -#ifdef __EXCEPTIONS - } catch (...) { mData = 0; } -#endif - if (mData) - fill(0); - else - qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; - } else - mData = 0; - mDataModified = true; - } -} - -/*! - Resizes the data array to have \a keySize cells in the key dimension. - - The current data is discarded and the map cells are set to 0, unless the map had already the - requested size. - - Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. - - \see setKeyRange, setSize, setValueSize -*/ -void QCPColorMapData::setKeySize(int keySize) -{ - setSize(keySize, mValueSize); -} - -/*! - Resizes the data array to have \a valueSize cells in the value dimension. - - The current data is discarded and the map cells are set to 0, unless the map had already the - requested size. - - Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. - - \see setValueRange, setSize, setKeySize -*/ -void QCPColorMapData::setValueSize(int valueSize) -{ - setSize(mKeySize, valueSize); -} - -/*! - Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area - covered by the color map in plot coordinates. - - The outer cells will be centered on the range boundaries given to this function. For example, if - the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will - be cells centered on the key coordinates 2, 2.5 and 3. - - \see setSize -*/ -void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) -{ - setKeyRange(keyRange); - setValueRange(valueRange); -} - -/*! - Sets the coordinate range the data shall be distributed over in the key dimension. Together with - the value range, This defines the rectangular area covered by the color map in plot coordinates. - - The outer cells will be centered on the range boundaries given to this function. For example, if - the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will - be cells centered on the key coordinates 2, 2.5 and 3. - - \see setRange, setValueRange, setSize -*/ -void QCPColorMapData::setKeyRange(const QCPRange &keyRange) -{ - mKeyRange = keyRange; -} - -/*! - Sets the coordinate range the data shall be distributed over in the value dimension. Together with - the key range, This defines the rectangular area covered by the color map in plot coordinates. - - The outer cells will be centered on the range boundaries given to this function. For example, if - the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there - will be cells centered on the value coordinates 2, 2.5 and 3. - - \see setRange, setKeyRange, setSize -*/ -void QCPColorMapData::setValueRange(const QCPRange &valueRange) -{ - mValueRange = valueRange; -} - -/*! - Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a - z. - - \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or - value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, - you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to - determine the cell index. Rather directly access the cell index with \ref - QCPColorMapData::setCell. - - \see setCell, setRange -*/ -void QCPColorMapData::setData(double key, double value, double z) -{ - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - { - mData[valueCell*mKeySize + keyCell] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } -} - -/*! - Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices - enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see - \ref setSize). - - In the standard plot configuration (horizontal key axis and vertical value axis, both not - range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with - indices (keySize-1, valueSize-1) is in the top right corner of the color map. - - \see setData, setSize -*/ -void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) -{ - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - { - mData[valueIndex*mKeySize + keyIndex] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } -} - -/*! - Goes through the data and updates the buffered minimum and maximum data values. - - Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange - and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten - with a smaller or larger value respectively, since the buffered maximum/minimum values have been - updated the last time. Why this is the case is explained in the class description (\ref - QCPColorMapData). - - Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a - recalculateDataBounds for convenience. Setting this to true will call this method for you, before - doing the rescale. -*/ -void QCPColorMapData::recalculateDataBounds() -{ - if (mKeySize > 0 && mValueSize > 0) - { - double minHeight = mData[0]; - double maxHeight = mData[0]; - const int dataCount = mValueSize*mKeySize; - for (int i=0; i maxHeight) - maxHeight = mData[i]; - if (mData[i] < minHeight) - minHeight = mData[i]; - } - mDataBounds.lower = minHeight; - mDataBounds.upper = maxHeight; - } -} - -/*! - Frees the internal data memory. - - This is equivalent to calling \ref setSize "setSize(0, 0)". -*/ -void QCPColorMapData::clear() -{ - setSize(0, 0); -} - -/*! - Sets all cells to the value \a z. -*/ -void QCPColorMapData::fill(double z) -{ - const int dataCount = mValueSize*mKeySize; - for (int i=0; i(data); - return; - } - if (copy) - { - *mMapData = *data; - } else - { - delete mMapData; - mMapData = data; - } - mMapImageInvalidated = true; -} - -/*! - Sets the data range of this color map to \a dataRange. The data range defines which data values - are mapped to the color gradient. - - To make the data range span the full range of the data set, use \ref rescaleDataRange. - - \see QCPColorScale::setDataRange -*/ -void QCPColorMap::setDataRange(const QCPRange &dataRange) -{ - if (!QCPRange::validRange(dataRange)) return; - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - if (mDataScaleType == QCPAxis::stLogarithmic) - mDataRange = dataRange.sanitizedForLogScale(); - else - mDataRange = dataRange.sanitizedForLinScale(); - mMapImageInvalidated = true; - emit dataRangeChanged(mDataRange); - } -} - -/*! - Sets whether the data is correlated with the color gradient linearly or logarithmically. - - \see QCPColorScale::setDataScaleType -*/ -void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) -{ - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - mMapImageInvalidated = true; - emit dataScaleTypeChanged(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - } -} - -/*! - Sets the color gradient that is used to represent the data. For more details on how to create an - own gradient or use one of the preset gradients, see \ref QCPColorGradient. - - The colors defined by the gradient will be used to represent data values in the currently set - data range, see \ref setDataRange. Data points that are outside this data range will either be - colored uniformly with the respective gradient boundary color, or the gradient will repeat, - depending on \ref QCPColorGradient::setPeriodic. - - \see QCPColorScale::setGradient -*/ -void QCPColorMap::setGradient(const QCPColorGradient &gradient) -{ - if (mGradient != gradient) - { - mGradient = gradient; - mMapImageInvalidated = true; - emit gradientChanged(mGradient); - } -} - -/*! - Sets whether the color map image shall use bicubic interpolation when displaying the color map - shrinked or expanded, and not at a 1:1 pixel-to-data scale. - - \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" -*/ -void QCPColorMap::setInterpolate(bool enabled) -{ - mInterpolate = enabled; - mMapImageInvalidated = true; // because oversampling factors might need to change -} - -/*! - Sets whether the outer most data rows and columns are clipped to the specified key and value - range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). - - if \a enabled is set to false, the data points at the border of the color map are drawn with the - same width and height as all other data points. Since the data points are represented by - rectangles of one color centered on the data coordinate, this means that the shown color map - extends by half a data point over the specified key/value range in each direction. - - \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" -*/ -void QCPColorMap::setTightBoundary(bool enabled) -{ - mTightBoundary = enabled; -} - -/*! - Associates the color scale \a colorScale with this color map. - - This means that both the color scale and the color map synchronize their gradient, data range and - data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps - can be associated with one single color scale. This causes the color maps to also synchronize - those properties, via the mutual color scale. - - This function causes the color map to adopt the current color gradient, data range and data scale - type of \a colorScale. After this call, you may change these properties at either the color map - or the color scale, and the setting will be applied to both. - - Pass 0 as \a colorScale to disconnect the color scale from this color map again. -*/ -void QCPColorMap::setColorScale(QCPColorScale *colorScale) -{ - if (mColorScale) // unconnect signals from old color scale - { - disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } - mColorScale = colorScale; - if (mColorScale) // connect signals to new color scale - { - setGradient(mColorScale.data()->gradient()); - setDataRange(mColorScale.data()->dataRange()); - setDataScaleType(mColorScale.data()->dataScaleType()); - connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } -} - -/*! - Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the - current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, - only for the third data dimension of the color map. - - The minimum and maximum values of the data set are buffered in the internal QCPColorMapData - instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref - QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For - performance reasons, however, they are only updated in an expanding fashion. So the buffered - maximum can only increase and the buffered minimum can only decrease. In consequence, changes to - the data that actually lower the maximum of the data set (by overwriting the cell holding the - current maximum with a smaller value), aren't recognized and the buffered maximum overestimates - the true maximum of the data set. The same happens for the buffered minimum. To recalculate the - true minimum and maximum by explicitly looking at each cell, the method - QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a - recalculateDataBounds calls this method before setting the data range to the buffered minimum and - maximum. - - \see setDataRange -*/ -void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) -{ - if (recalculateDataBounds) - mMapData->recalculateDataBounds(); - setDataRange(mMapData->dataBounds()); -} - -/*! - Takes the current appearance of the color map and updates the legend icon, which is used to - represent this color map in the legend (see \ref QCPLegend). - - The \a transformMode specifies whether the rescaling is done by a faster, low quality image - scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm - (Qt::SmoothTransformation). - - The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to - the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured - legend icon size, the thumb will be rescaled during drawing of the legend item. - - \see setDataRange -*/ -void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) -{ - if (mMapImage.isNull() && !data()->isEmpty()) - updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) - - if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again - { - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); - } -} - -/*! - Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also - resizes the map to 0x0 cells. -*/ -void QCPColorMap::clearData() -{ - mMapData->clear(); -} - -/* inherits documentation from base class */ -double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; -} - -/*! \internal - - Updates the internal map image buffer by going through the internal \ref QCPColorMapData and - turning the data values into color pixels with \ref QCPColorGradient::colorize. - - This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image - has been invalidated for a different reason (e.g. a change of the data range with \ref - setDataRange). - - If the map cell count is low, the image created will be oversampled in order to avoid a - QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images - without smooth transform enabled. Accordingly, oversampling isn't performed if \ref - setInterpolate is true. -*/ -void QCPColorMap::updateMapImage() -{ - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) return; - if (mMapData->isEmpty()) return; - - const int keySize = mMapData->keySize(); - const int valueSize = mMapData->valueSize(); - int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on - int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on - - // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation: - if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor)) - mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), QImage::Format_RGB32); - else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) - mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32); - - QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage - if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) - { - // resize undersampled map image to actual key/value cell sizes: - if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize)) - mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32); - else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) - mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); - localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image - } else if (!mUndersampledMapImage.isNull()) - mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it - - const double *rawData = mMapData->mData; - if (keyAxis->orientation() == Qt::Horizontal) - { - const int lineCount = valueSize; - const int rowCount = keySize; - for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) - mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); - } - } else // keyAxis->orientation() == Qt::Vertical - { - const int lineCount = keySize; - const int rowCount = valueSize; - for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) - mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); - } - } - - if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) - { - if (keyAxis->orientation() == Qt::Horizontal) - mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - else - mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - } - mMapData->mDataModified = false; - mMapImageInvalidated = false; -} - -/* inherits documentation from base class */ -void QCPColorMap::draw(QCPPainter *painter) -{ - if (mMapData->isEmpty()) return; - if (!mKeyAxis || !mValueAxis) return; - applyDefaultAntialiasingHint(painter); - - if (mMapData->mDataModified || mMapImageInvalidated) - updateMapImage(); - - // use buffer if painting vectorized (PDF): - bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); - QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized - QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in - QPixmap mapBuffer; - double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps - if (useBuffer) - { - mapBufferTarget = painter->clipRegion().boundingRect(); - mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); - mapBuffer.fill(Qt::transparent); - localPainter = new QCPPainter(&mapBuffer); - localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); - localPainter->translate(-mapBufferTarget.topLeft()); - } - - QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): - double halfCellWidth = 0; // in pixels - double halfCellHeight = 0; // in pixels - if (keyAxis()->orientation() == Qt::Horizontal) - { - if (mMapData->keySize() > 1) - halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1); - } else // keyAxis orientation is Qt::Vertical - { - if (mMapData->keySize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1); - } - imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); - QRegion clipBackup; - if (mTightBoundary) - { - clipBackup = localPainter->clipRegion(); - QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - localPainter->setClipRect(tightClipRect, Qt::IntersectClip); - } - localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); - if (mTightBoundary) - localPainter->setClipRegion(clipBackup); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); - - if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter - { - delete localPainter; - painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); - } -} - -/* inherits documentation from base class */ -void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - applyDefaultAntialiasingHint(painter); - // draw map thumbnail: - if (!mLegendIcon.isNull()) - { - QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); - QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); - iconRect.moveCenter(rect.center()); - painter->drawPixmap(iconRect.topLeft(), scaledIcon); - } - /* - // draw frame: - painter->setBrush(Qt::NoBrush); - painter->setPen(Qt::black); - painter->drawRect(rect.adjusted(1, 1, 0, 0)); - */ -} - -/* inherits documentation from base class */ -QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - foundRange = true; - QCPRange result = mMapData->keyRange(); - result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) - { - if (result.lower <= 0 && result.upper > 0) - result.lower = result.upper*1e-3; - else if (result.lower <= 0 && result.upper <= 0) - foundRange = false; - } else if (inSignDomain == QCPAbstractPlottable::sdNegative) - { - if (result.upper >= 0 && result.lower < 0) - result.upper = result.lower*1e-3; - else if (result.upper >= 0 && result.lower >= 0) - foundRange = false; - } - return result; -} - -/* inherits documentation from base class */ -QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - foundRange = true; - QCPRange result = mMapData->valueRange(); - result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) - { - if (result.lower <= 0 && result.upper > 0) - result.lower = result.upper*1e-3; - else if (result.lower <= 0 && result.upper <= 0) - foundRange = false; - } else if (inSignDomain == QCPAbstractPlottable::sdNegative) - { - if (result.upper >= 0 && result.lower < 0) - result.upper = result.lower*1e-3; - else if (result.upper >= 0 && result.lower >= 0) - foundRange = false; - } - return result; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPFinancialData -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPFinancialData - \brief Holds the data of one single data point for QCPFinancial. - - The container for storing multiple data points is \ref QCPFinancialDataMap. - - The stored data is: - \li \a key: coordinate on the key axis of this data point - \li \a open: The opening value at the data point - \li \a high: The high/maximum value at the data point - \li \a low: The low/minimum value at the data point - \li \a close: The closing value at the data point - - \see QCPFinancialDataMap -*/ - -/*! - Constructs a data point with key and all values set to zero. -*/ -QCPFinancialData::QCPFinancialData() : - key(0), - open(0), - high(0), - low(0), - close(0) -{ -} - -/*! - Constructs a data point with the specified \a key and OHLC values. -*/ -QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : - key(key), - open(open), - high(high), - low(low), - close(close) -{ -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPFinancial -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPFinancial - \brief A plottable representing a financial stock chart - - \image html QCPFinancial.png - - This plottable represents time series data binned to certain intervals, mainly used for stock - charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be - set via \ref setChartStyle. - - The data is passed via \ref setData as a set of open/high/low/close values at certain keys - (typically times). This means the data must be already binned appropriately. If data is only - available as a series of values (e.g. \a price against \a time), you can use the static - convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed - to \ref setData. - - The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot - key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. - - \section appearance Changing the appearance - - Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, - lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). - - If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are - represented with a different pen and brush than negative changes (\a close < \a open). These can - be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref - setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection - however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used, - irrespective of whether the chart is single- or two-colored. - -*/ - -/* start of documentation of inline functions */ - -/*! \fn QCPFinancialDataMap *QCPFinancial::data() const - - Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to - directly manipulate the data, which may be more convenient and faster than using the regular \ref - setData or \ref addData methods, in certain situations. -*/ - -/* end of documentation of inline functions */ - -/*! - Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value - axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have - the same orientation. If either of these restrictions is violated, a corresponding message is - printed to the debug output (qDebug), the construction is not aborted, though. - - The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the financial chart. -*/ -QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(0), - mChartStyle(csOhlc), - mWidth(0.5), - mTwoColored(false), - mBrushPositive(QBrush(QColor(210, 210, 255))), - mBrushNegative(QBrush(QColor(255, 210, 210))), - mPenPositive(QPen(QColor(10, 40, 180))), - mPenNegative(QPen(QColor(180, 40, 10))) -{ - mData = new QCPFinancialDataMap; - - setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); - setSelectedBrush(QBrush(QColor(80, 80, 255))); -} - -QCPFinancial::~QCPFinancial() -{ - delete mData; -} - -/*! - Replaces the current data with the provided \a data. - - If \a copy is set to true, data points in \a data will only be copied. if false, the plottable - takes ownership of the passed data and replaces the internal data pointer with it. This is - significantly faster than copying for large datasets. - - Alternatively, you can also access and modify the plottable's data via the \ref data method, which - returns a pointer to the internal \ref QCPFinancialDataMap. - - \see timeSeriesToOhlc -*/ -void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } -} - -/*! \overload - - Replaces the current data with the provided open/high/low/close data. The provided vectors should - have equal length. Else, the number of added points will be the size of the smallest vector. - - \see timeSeriesToOhlc -*/ -void QCPFinancial::setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, open.size()); - n = qMin(n, high.size()); - n = qMin(n, low.size()); - n = qMin(n, close.size()); - for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); - } -} - -/*! - Sets which representation style shall be used to display the OHLC data. -*/ -void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) -{ - mChartStyle = style; -} - -/*! - Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. - - A typical choice is to set it to (or slightly less than) one bin interval width. -*/ -void QCPFinancial::setWidth(double width) -{ - mWidth = width; -} - -/*! - Sets whether this chart shall contrast positive from negative trends per data point by using two - separate colors to draw the respective bars/candlesticks. - - If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref - setBrush). - - \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative -*/ -void QCPFinancial::setTwoColored(bool twoColored) -{ - mTwoColored = twoColored; -} - -/*! - If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills - of data points with a positive trend (i.e. bars/candlesticks with close >= open). - - If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref - setBrush). - - \see setBrushNegative, setPenPositive, setPenNegative -*/ -void QCPFinancial::setBrushPositive(const QBrush &brush) -{ - mBrushPositive = brush; -} - -/*! - If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills - of data points with a negative trend (i.e. bars/candlesticks with close < open). - - If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref - setBrush). - - \see setBrushPositive, setPenNegative, setPenPositive -*/ -void QCPFinancial::setBrushNegative(const QBrush &brush) -{ - mBrushNegative = brush; -} - -/*! - If \ref setTwoColored is set to true, this function controls the pen that is used to draw - outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). - - If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref - setBrush). - - \see setPenNegative, setBrushPositive, setBrushNegative -*/ -void QCPFinancial::setPenPositive(const QPen &pen) -{ - mPenPositive = pen; -} - -/*! - If \ref setTwoColored is set to true, this function controls the pen that is used to draw - outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). - - If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref - setBrush). - - \see setPenPositive, setBrushNegative, setBrushPositive -*/ -void QCPFinancial::setPenNegative(const QPen &pen) -{ - mPenNegative = pen; -} - -/*! - Adds the provided data points in \a dataMap to the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialDataMap. - - \see removeData -*/ -void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) -{ - mData->unite(dataMap); -} - -/*! \overload - - Adds the provided single data point in \a data to the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. - - \see removeData -*/ -void QCPFinancial::addData(const QCPFinancialData &data) -{ - mData->insertMulti(data.key, data); -} - -/*! \overload - - Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to - the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. - - \see removeData -*/ -void QCPFinancial::addData(double key, double open, double high, double low, double close) -{ - mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); -} - -/*! \overload - - Adds the provided open/high/low/close data to the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. - - \see removeData -*/ -void QCPFinancial::addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) -{ - int n = key.size(); - n = qMin(n, open.size()); - n = qMin(n, high.size()); - n = qMin(n, low.size()); - n = qMin(n, close.size()); - for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); - } -} - -/*! - Removes all data points with keys smaller than \a key. - - \see addData, clearData -*/ -void QCPFinancial::removeDataBefore(double key) -{ - QCPFinancialDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); -} - -/*! - Removes all data points with keys greater than \a key. - - \see addData, clearData -*/ -void QCPFinancial::removeDataAfter(double key) -{ - if (mData->isEmpty()) return; - QCPFinancialDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); -} - -/*! - Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or - equal to \a toKey, the function does nothing. To remove a single data point with known key, use - \ref removeData(double key). - - \see addData, clearData -*/ -void QCPFinancial::removeData(double fromKey, double toKey) -{ - if (fromKey >= toKey || mData->isEmpty()) return; - QCPFinancialDataMap::iterator it = mData->upperBound(fromKey); - QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \overload - - Removes a single data point at \a key. If the position is not known with absolute precision, - consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval - around the suspected position, depeding on the precision with which the key is known. - - \see addData, clearData -*/ -void QCPFinancial::removeData(double key) -{ - mData->remove(key); -} - -/*! - Removes all data points. - - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPFinancial::clearData() -{ - mData->clear(); -} - -/* inherits documentation from base class */ -double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - // get visible data range: - QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point - getVisibleDataBounds(lower, upper); - if (lower == mData->constEnd() || upper == mData->constEnd()) - return -1; - // perform select test according to configured style: - switch (mChartStyle) - { - case QCPFinancial::csOhlc: - return ohlcSelectTest(pos, lower, upper+1); break; - case QCPFinancial::csCandlestick: - return candlestickSelectTest(pos, lower, upper+1); break; - } - } - return -1; -} - -/*! - A convenience function that converts time series data (\a value against \a time) to OHLC binned - data points. The return value can then be passed on to \ref setData. - - The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. - For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour - each, set \a timeBinSize to 3600. - - \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The - value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. - It merely defines the mathematical offset/phase of the bins that will be used to process the - data. -*/ -QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) -{ - QCPFinancialDataMap map; - int count = qMin(time.size(), value.size()); - if (count == 0) - return QCPFinancialDataMap(); - - QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); - int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); - for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); - if (i == count-1) // last data point is in current bin, finalize bin: - { - currentBinData.close = value.at(i); - currentBinData.key = timeBinOffset+(index)*timeBinSize; - map.insert(currentBinData.key, currentBinData); - } - } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: - { - // finalize current bin: - currentBinData.close = value.at(i-1); - currentBinData.key = timeBinOffset+(index-1)*timeBinSize; - map.insert(currentBinData.key, currentBinData); - // start next bin: - currentBinIndex = index; - currentBinData.open = value.at(i); - currentBinData.high = value.at(i); - currentBinData.low = value.at(i); - } - } - - return map; -} - -/* inherits documentation from base class */ -void QCPFinancial::draw(QCPPainter *painter) -{ - // get visible data range: - QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point - getVisibleDataBounds(lower, upper); - if (lower == mData->constEnd() || upper == mData->constEnd()) - return; - - // draw visible data range according to configured style: - switch (mChartStyle) - { - case QCPFinancial::csOhlc: - drawOhlcPlot(painter, lower, upper+1); break; - case QCPFinancial::csCandlestick: - drawCandlestickPlot(painter, lower, upper+1); break; - } -} - -/* inherits documentation from base class */ -void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const -{ - painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing - if (mChartStyle == csOhlc) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); - // draw bottom right hald icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); - } - } else if (mChartStyle == csCandlestick) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); - // draw bottom right hald icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); - painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); - painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); - } - } -} - -/* inherits documentation from base class */ -QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - QCPFinancialDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - // determine exact range by including width of bars/flags: - if (haveLower && mKeyAxis) - range.lower = range.lower-mWidth*0.5; - if (haveUpper && mKeyAxis) - range.upper = range.upper+mWidth*0.5; - foundRange = haveLower && haveUpper; - return range; -} - -/* inherits documentation from base class */ -QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - QCPFinancialDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - // high: - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0)) - { - if (it.value().high < range.lower || !haveLower) - { - range.lower = it.value().high; - haveLower = true; - } - if (it.value().high > range.upper || !haveUpper) - { - range.upper = it.value().high; - haveUpper = true; - } - } - // low: - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0)) - { - if (it.value().low < range.lower || !haveLower) - { - range.lower = it.value().low; - haveLower = true; - } - if (it.value().low > range.upper || !haveUpper) - { - range.upper = it.value().low; - haveUpper = true; - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} - -/*! \internal - - Draws the data from \a begin to \a end as OHLC bars with the provided \a painter. - - This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. -*/ -void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QPen linePen; - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - linePen = mSelectedPen; - else if (mTwoColored) - linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; - else - linePen = mPen; - painter->setPen(linePen); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); - // draw backbone: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low))); - // draw open: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides - painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel)); - // draw close: - painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); - } - } else - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - linePen = mSelectedPen; - else if (mTwoColored) - linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; - else - linePen = mPen; - painter->setPen(linePen); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); - // draw backbone: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel)); - // draw open: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides - painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel)); - // draw close: - painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); - } - } -} - -/*! \internal - - Draws the data from \a begin to \a end as Candlesticks with the provided \a painter. - - This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. -*/ -void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QPen linePen; - QBrush boxBrush; - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; - } else if (mTwoColored) - { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; - } - } else - { - linePen = mPen; - boxBrush = mBrush; - } - painter->setPen(linePen); - painter->setBrush(boxBrush); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); - // draw high: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); - // draw low: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close)))); - // draw open-close box: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); - painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel))); - } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; - } else if (mTwoColored) - { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; - } - } else - { - linePen = mPen; - boxBrush = mBrush; - } - painter->setPen(linePen); - painter->setBrush(boxBrush); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); - // draw high: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); - // draw low: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel)); - // draw open-close box: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); - painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels))); - } - } -} - -/*! \internal - - This method is a helper function for \ref selectTest. It is used to test for selection when the - chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. -*/ -double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - double minDistSqr = std::numeric_limits::max(); - QCPFinancialDataMap::const_iterator it; - if (keyAxis->orientation() == Qt::Horizontal) - { - for (it = begin; it != end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it.value().key); - // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } else // keyAxis->orientation() == Qt::Vertical - { - for (it = begin; it != end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it.value().key); - // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } - return qSqrt(minDistSqr); -} - -/*! \internal - - This method is a helper function for \ref selectTest. It is used to test for selection when the - chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a - end. -*/ -double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const -{ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - double minDistSqr = std::numeric_limits::max(); - QCPFinancialDataMap::const_iterator it; - if (keyAxis->orientation() == Qt::Horizontal) - { - for (it = begin; it != end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); - QCPRange boxValueRange(it.value().close, it.value().open); - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - double keyPixel = keyAxis->coordToPixel(it.value().key); - double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos); - double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos); - currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); - } - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } else // keyAxis->orientation() == Qt::Vertical - { - for (it = begin; it != end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); - QCPRange boxValueRange(it.value().close, it.value().open); - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - double keyPixel = keyAxis->coordToPixel(it.value().key); - double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos); - double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos); - currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); - } - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } - return qSqrt(minDistSqr); -} - -/*! \internal - - called by the drawing methods to determine which data (key) range is visible at the current key - axis range setting, so only that needs to be processed. - - \a lower returns an iterator to the lowest data point that needs to be taken into account when - plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a - lower may still be just outside the visible range. - - \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie - just outside of the visible range. - - if the plottable contains no data, both \a lower and \a upper point to constEnd. - - \see QCPGraph::getVisibleDataBounds -*/ -void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const -{ - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) - { - lower = mData->constEnd(); - upper = mData->constEnd(); - return; - } - - // get visible data range as QMap iterators - QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); - QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); - bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range - bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range - - lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn - upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemStraightLine -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemStraightLine - \brief A straight line that spans infinitely in both directions - - \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a point1 and \a point2, which define the straight line. -*/ - -/*! - Creates a straight line item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - point1(createPosition(QLatin1String("point1"))), - point2(createPosition(QLatin1String("point2"))) -{ - point1->setCoords(0, 0); - point2->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); -} - -QCPItemStraightLine::~QCPItemStraightLine() -{ -} - -/*! - Sets the pen that will be used to draw the line - - \see setSelectedPen -*/ -void QCPItemStraightLine::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line when selected - - \see setPen, setSelected -*/ -void QCPItemStraightLine::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/* inherits documentation from base class */ -double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); -} - -/* inherits documentation from base class */ -void QCPItemStraightLine::draw(QCPPainter *painter) -{ - QVector2D start(point1->pixelPoint()); - QVector2D end(point2->pixelPoint()); - // get visible segment of straight line inside clipRect: - double clipPad = mainPen().widthF(); - QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - } -} - -/*! \internal - - finds the shortest distance of \a point to the straight line defined by the base point \a - base and the direction vector \a vec. - - This is a helper function for \ref selectTest. -*/ -double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const -{ - return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); -} - -/*! \internal - - Returns the section of the straight line defined by \a base and direction vector \a - vec, that is visible in the specified \a rect. - - This is a helper function for \ref draw. -*/ -QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const -{ - double bx, by; - double gamma; - QLineF result; - if (vec.x() == 0 && vec.y() == 0) - return result; - if (qFuzzyIsNull(vec.x())) // line is vertical - { - // check top of rect: - bx = rect.left(); - by = rect.top(); - gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); - if (gamma >= 0 && gamma <= rect.width()) - result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical - } else if (qFuzzyIsNull(vec.y())) // line is horizontal - { - // check left of rect: - bx = rect.left(); - by = rect.top(); - gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); - if (gamma >= 0 && gamma <= rect.height()) - result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal - } else // line is skewed - { - QList pointVectors; - // check top of rect: - bx = rect.left(); - by = rect.top(); - gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - // check bottom of rect: - bx = rect.left(); - by = rect.bottom(); - gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - // check left of rect: - bx = rect.left(); - by = rect.top(); - gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - // check right of rect: - bx = rect.right(); - by = rect.top(); - gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; - } - } - } - result.setPoints(pv1.toPointF(), pv2.toPointF()); - } - } - return result; -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the - item is not selected and mSelectedPen when it is. -*/ -QPen QCPItemStraightLine::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemLine -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemLine - \brief A line from one point to another - - \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a start and \a end, which define the end points of the line. - - With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. -*/ - -/*! - Creates a line item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - end(createPosition(QLatin1String("end"))) -{ - start->setCoords(0, 0); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); -} - -QCPItemLine::~QCPItemLine() -{ -} - -/*! - Sets the pen that will be used to draw the line - - \see setSelectedPen -*/ -void QCPItemLine::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line when selected - - \see setPen, setSelected -*/ -void QCPItemLine::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the line ending style of the head. The head corresponds to the \a end position. - - Note that due to the overloaded QCPLineEnding constructor, you may directly specify - a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - - \see setTail -*/ -void QCPItemLine::setHead(const QCPLineEnding &head) -{ - mHead = head; -} - -/*! - Sets the line ending style of the tail. The tail corresponds to the \a start position. - - Note that due to the overloaded QCPLineEnding constructor, you may directly specify - a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - - \see setHead -*/ -void QCPItemLine::setTail(const QCPLineEnding &tail) -{ - mTail = tail; -} - -/* inherits documentation from base class */ -double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); -} - -/* inherits documentation from base class */ -void QCPItemLine::draw(QCPPainter *painter) -{ - QVector2D startVec(start->pixelPoint()); - QVector2D endVec(end->pixelPoint()); - if (startVec.toPoint() == endVec.toPoint()) - return; - // get visible segment of straight line inside clipRect: - double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); - clipPad = qMax(clipPad, (double)mainPen().widthF()); - QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, startVec-endVec); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, endVec-startVec); - } -} - -/*! \internal - - Returns the section of the line defined by \a start and \a end, that is visible in the specified - \a rect. - - This is a helper function for \ref draw. -*/ -QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const -{ - bool containsStart = rect.contains(start.x(), start.y()); - bool containsEnd = rect.contains(end.x(), end.y()); - if (containsStart && containsEnd) - return QLineF(start.toPointF(), end.toPointF()); - - QVector2D base = start; - QVector2D vec = end-start; - double bx, by; - double gamma, mu; - QLineF result; - QList pointVectors; - - if (!qFuzzyIsNull(vec.y())) // line is not horizontal - { - // check top of rect: - bx = rect.left(); - by = rect.top(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - } - // check bottom of rect: - bx = rect.left(); - by = rect.bottom(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - } - } - if (!qFuzzyIsNull(vec.x())) // line is not vertical - { - // check left of rect: - bx = rect.left(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - } - // check right of rect: - bx = rect.right(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - } - } - - if (containsStart) - pointVectors.append(start); - if (containsEnd) - pointVectors.append(end); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; - } - } - } - result.setPoints(pv1.toPointF(), pv2.toPointF()); - } - return result; -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the - item is not selected and mSelectedPen when it is. -*/ -QPen QCPItemLine::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemCurve -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemCurve - \brief A curved line from one point to another - - \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." - - It has four positions, \a start and \a end, which define the end points of the line, and two - control points which define the direction the line exits from the start and the direction from - which it approaches the end: \a startDir and \a endDir. - - With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an - arrow. - - Often it is desirable for the control points to stay at fixed relative positions to the start/end - point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, - and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. -*/ - -/*! - Creates a curve item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - startDir(createPosition(QLatin1String("startDir"))), - endDir(createPosition(QLatin1String("endDir"))), - end(createPosition(QLatin1String("end"))) -{ - start->setCoords(0, 0); - startDir->setCoords(0.5, 0); - endDir->setCoords(0, 0.5); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); -} - -QCPItemCurve::~QCPItemCurve() -{ -} - -/*! - Sets the pen that will be used to draw the line - - \see setSelectedPen -*/ -void QCPItemCurve::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line when selected - - \see setPen, setSelected -*/ -void QCPItemCurve::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the line ending style of the head. The head corresponds to the \a end position. - - Note that due to the overloaded QCPLineEnding constructor, you may directly specify - a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - - \see setTail -*/ -void QCPItemCurve::setHead(const QCPLineEnding &head) -{ - mHead = head; -} - -/*! - Sets the line ending style of the tail. The tail corresponds to the \a start position. - - Note that due to the overloaded QCPLineEnding constructor, you may directly specify - a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - - \see setHead -*/ -void QCPItemCurve::setTail(const QCPLineEnding &tail) -{ - mTail = tail; -} - -/* inherits documentation from base class */ -double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QPointF startVec(start->pixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); - - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); - - QPolygonF polygon = cubicPath.toSubpathPolygons().first(); - double minDistSqr = std::numeric_limits::max(); - for (int i=1; ipixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); - if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash - return; - - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); - - // paint visible segment, if existent: - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - QRect cubicRect = cubicPath.controlPointRect().toRect(); - if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position - cubicRect.adjust(0, 0, 1, 1); - if (clip.intersects(cubicRect)) - { - painter->setPen(mainPen()); - painter->drawPath(cubicPath); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); - } -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the - item is not selected and mSelectedPen when it is. -*/ -QPen QCPItemCurve::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemRect -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemRect - \brief A rectangle - - \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a topLeft and \a bottomRight, which define the rectangle. -*/ - -/*! - Creates a rectangle item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) -{ - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); -} - -QCPItemRect::~QCPItemRect() -{ -} - -/*! - Sets the pen that will be used to draw the line of the rectangle - - \see setSelectedPen, setBrush -*/ -void QCPItemRect::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line of the rectangle when selected - - \see setPen, setSelected -*/ -void QCPItemRect::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to - Qt::NoBrush. - - \see setSelectedBrush, setPen -*/ -void QCPItemRect::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a - brush to Qt::NoBrush. - - \see setBrush -*/ -void QCPItemRect::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/* inherits documentation from base class */ -double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); -} - -/* inherits documentation from base class */ -void QCPItemRect::draw(QCPPainter *painter) -{ - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF rect = QRectF(p1, p2).normalized(); - double clipPad = mainPen().widthF(); - QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(rect); - } -} - -/* inherits documentation from base class */ -QPointF QCPItemRect::anchorPixelPoint(int anchorId) const -{ - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected - and mSelectedPen when it is. -*/ -QPen QCPItemRect::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \internal - - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item - is not selected and mSelectedBrush when it is. -*/ -QBrush QCPItemRect::mainBrush() const -{ - return mSelected ? mSelectedBrush : mBrush; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemText -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemText - \brief A text label - - \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." - - Its position is defined by the member \a position and the setting of \ref setPositionAlignment. - The latter controls which part of the text rect shall be aligned with \a position. - - The text alignment itself (i.e. left, center, right) can be controlled with \ref - setTextAlignment. - - The text may be rotated around the \a position point with \ref setRotation. -*/ - -/*! - Creates a text item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemText::QCPItemText(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - position(createPosition(QLatin1String("position"))), - topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) -{ - position->setCoords(0, 0); - - setRotation(0); - setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); - setPositionAlignment(Qt::AlignCenter); - setText(QLatin1String("text")); - - setPen(Qt::NoPen); - setSelectedPen(Qt::NoPen); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setColor(Qt::black); - setSelectedColor(Qt::blue); -} - -QCPItemText::~QCPItemText() -{ -} - -/*! - Sets the color of the text. -*/ -void QCPItemText::setColor(const QColor &color) -{ - mColor = color; -} - -/*! - Sets the color of the text that will be used when the item is selected. -*/ -void QCPItemText::setSelectedColor(const QColor &color) -{ - mSelectedColor = color; -} - -/*! - Sets the pen that will be used do draw a rectangular border around the text. To disable the - border, set \a pen to Qt::NoPen. - - \see setSelectedPen, setBrush, setPadding -*/ -void QCPItemText::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used do draw a rectangular border around the text, when the item is - selected. To disable the border, set \a pen to Qt::NoPen. - - \see setPen -*/ -void QCPItemText::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the brush that will be used do fill the background of the text. To disable the - background, set \a brush to Qt::NoBrush. - - \see setSelectedBrush, setPen, setPadding -*/ -void QCPItemText::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the - background, set \a brush to Qt::NoBrush. - - \see setBrush -*/ -void QCPItemText::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/*! - Sets the font of the text. - - \see setSelectedFont, setColor -*/ -void QCPItemText::setFont(const QFont &font) -{ - mFont = font; -} - -/*! - Sets the font of the text that will be used when the item is selected. - - \see setFont -*/ -void QCPItemText::setSelectedFont(const QFont &font) -{ - mSelectedFont = font; -} - -/*! - Sets the text that will be displayed. Multi-line texts are supported by inserting a line break - character, e.g. '\n'. - - \see setFont, setColor, setTextAlignment -*/ -void QCPItemText::setText(const QString &text) -{ - mText = text; -} - -/*! - Sets which point of the text rect shall be aligned with \a position. - - Examples: - \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such - that the top of the text rect will be horizontally centered on \a position. - \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the - bottom left corner of the text rect. - - If you want to control the alignment of (multi-lined) text within the text rect, use \ref - setTextAlignment. -*/ -void QCPItemText::setPositionAlignment(Qt::Alignment alignment) -{ - mPositionAlignment = alignment; -} - -/*! - Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). -*/ -void QCPItemText::setTextAlignment(Qt::Alignment alignment) -{ - mTextAlignment = alignment; -} - -/*! - Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated - around \a position. -*/ -void QCPItemText::setRotation(double degrees) -{ - mRotation = degrees; -} - -/*! - Sets the distance between the border of the text rectangle and the text. The appearance (and - visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. -*/ -void QCPItemText::setPadding(const QMargins &padding) -{ - mPadding = padding; -} - -/* inherits documentation from base class */ -double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - // The rect may be rotated, so we transform the actual clicked pos to the rotated - // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: - QPointF positionPixels(position->pixelPoint()); - QTransform inputTransform; - inputTransform.translate(positionPixels.x(), positionPixels.y()); - inputTransform.rotate(-mRotation); - inputTransform.translate(-positionPixels.x(), -positionPixels.y()); - QPointF rotatedPos = inputTransform.map(pos); - QFontMetrics fontMetrics(mFont); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); - textBoxRect.moveTopLeft(textPos.toPoint()); - - return rectSelectTest(textBoxRect, rotatedPos, true); -} - -/* inherits documentation from base class */ -void QCPItemText::draw(QCPPainter *painter) -{ - QPointF pos(position->pixelPoint()); - QTransform transform = painter->transform(); - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - painter->setFont(mainFont()); - QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); - textBoxRect.moveTopLeft(textPos.toPoint()); - double clipPad = mainPen().widthF(); - QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) - { - painter->setTransform(transform); - if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || - (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(textBoxRect); - } - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(mainColor())); - painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); - } -} - -/* inherits documentation from base class */ -QPointF QCPItemText::anchorPixelPoint(int anchorId) const -{ - // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPoint()); - QTransform transform; - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - QFontMetrics fontMetrics(mainFont()); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textBoxRect.moveTopLeft(textPos.toPoint()); - QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); - - switch (anchorId) - { - case aiTopLeft: return rectPoly.at(0); - case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; - case aiTopRight: return rectPoly.at(1); - case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; - case aiBottomRight: return rectPoly.at(2); - case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; - case aiBottomLeft: return rectPoly.at(3); - case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Returns the point that must be given to the QPainter::drawText function (which expects the top - left point of the text rect), according to the position \a pos, the text bounding box \a rect and - the requested \a positionAlignment. - - For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point - will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally - drawn at that point, the lower left corner of the resulting text rect is at \a pos. -*/ -QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const -{ - if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) - return pos; - - QPointF result = pos; // start at top left - if (positionAlignment.testFlag(Qt::AlignHCenter)) - result.rx() -= rect.width()/2.0; - else if (positionAlignment.testFlag(Qt::AlignRight)) - result.rx() -= rect.width(); - if (positionAlignment.testFlag(Qt::AlignVCenter)) - result.ry() -= rect.height()/2.0; - else if (positionAlignment.testFlag(Qt::AlignBottom)) - result.ry() -= rect.height(); - return result; -} - -/*! \internal - - Returns the font that should be used for drawing text. Returns mFont when the item is not selected - and mSelectedFont when it is. -*/ -QFont QCPItemText::mainFont() const -{ - return mSelected ? mSelectedFont : mFont; -} - -/*! \internal - - Returns the color that should be used for drawing text. Returns mColor when the item is not - selected and mSelectedColor when it is. -*/ -QColor QCPItemText::mainColor() const -{ - return mSelected ? mSelectedColor : mColor; -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected - and mSelectedPen when it is. -*/ -QPen QCPItemText::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \internal - - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item - is not selected and mSelectedBrush when it is. -*/ -QBrush QCPItemText::mainBrush() const -{ - return mSelected ? mSelectedBrush : mBrush; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemEllipse -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemEllipse - \brief An ellipse - - \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. -*/ - -/*! - Creates an ellipse item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), - left(createAnchor(QLatin1String("left"), aiLeft)), - center(createAnchor(QLatin1String("center"), aiCenter)) -{ - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); -} - -QCPItemEllipse::~QCPItemEllipse() -{ -} - -/*! - Sets the pen that will be used to draw the line of the ellipse - - \see setSelectedPen, setBrush -*/ -void QCPItemEllipse::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line of the ellipse when selected - - \see setPen, setSelected -*/ -void QCPItemEllipse::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to - Qt::NoBrush. - - \see setSelectedBrush, setPen -*/ -void QCPItemEllipse::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a - brush to Qt::NoBrush. - - \see setBrush -*/ -void QCPItemEllipse::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/* inherits documentation from base class */ -double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - double result = -1; - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - QPointF center((p1+p2)/2.0); - double a = qAbs(p1.x()-p2.x())/2.0; - double b = qAbs(p1.y()-p2.y())/2.0; - double x = pos.x()-center.x(); - double y = pos.y()-center.y(); - - // distance to border: - double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); - result = qAbs(c-1)*qSqrt(x*x+y*y); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (x*x/(a*a) + y*y/(b*b) <= 1) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; -} - -/* inherits documentation from base class */ -void QCPItemEllipse::draw(QCPPainter *painter) -{ - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF ellipseRect = QRectF(p1, p2).normalized(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); -#ifdef __EXCEPTIONS - try // drawEllipse sometimes throws exceptions if ellipse is too big - { -#endif - painter->drawEllipse(ellipseRect); -#ifdef __EXCEPTIONS - } catch (...) - { - qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; - setVisible(false); - } -#endif - } -} - -/* inherits documentation from base class */ -QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const -{ - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) - { - case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected - and mSelectedPen when it is. -*/ -QPen QCPItemEllipse::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \internal - - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item - is not selected and mSelectedBrush when it is. -*/ -QBrush QCPItemEllipse::mainBrush() const -{ - return mSelected ? mSelectedBrush : mBrush; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemPixmap -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemPixmap - \brief An arbitrary pixmap - - \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will - be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to - fit the rectangle or be drawn aligned to the topLeft position. - - If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown - on the right side of the example image), the pixmap will be flipped in the respective - orientations. -*/ - -/*! - Creates a rectangle item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mScaledPixmapInvalidated(true) -{ - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(Qt::NoPen); - setSelectedPen(QPen(Qt::blue)); - setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation); -} - -QCPItemPixmap::~QCPItemPixmap() -{ -} - -/*! - Sets the pixmap that will be displayed. -*/ -void QCPItemPixmap::setPixmap(const QPixmap &pixmap) -{ - mPixmap = pixmap; - mScaledPixmapInvalidated = true; - if (mPixmap.isNull()) - qDebug() << Q_FUNC_INFO << "pixmap is null"; -} - -/*! - Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a - bottomRight positions. -*/ -void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) -{ - mScaled = scaled; - mAspectRatioMode = aspectRatioMode; - mTransformationMode = transformationMode; - mScaledPixmapInvalidated = true; -} - -/*! - Sets the pen that will be used to draw a border around the pixmap. - - \see setSelectedPen, setBrush -*/ -void QCPItemPixmap::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw a border around the pixmap when selected - - \see setPen, setSelected -*/ -void QCPItemPixmap::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/* inherits documentation from base class */ -double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return rectSelectTest(getFinalRect(), pos, true); -} - -/* inherits documentation from base class */ -void QCPItemPixmap::draw(QCPPainter *painter) -{ - bool flipHorz = false; - bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); - double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); - QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) - { - updateScaledPixmap(rect, flipHorz, flipVert); - painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); - QPen pen = mainPen(); - if (pen.style() != Qt::NoPen) - { - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawRect(rect); - } - } -} - -/* inherits documentation from base class */ -QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const -{ - bool flipHorz; - bool flipVert; - QRect rect = getFinalRect(&flipHorz, &flipVert); - // we actually want denormal rects (negative width/height) here, so restore - // the flipped state: - if (flipHorz) - rect.adjust(rect.width(), 0, -rect.width(), 0); - if (flipVert) - rect.adjust(0, rect.height(), 0, -rect.height()); - - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The - parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped - horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a - bottomRight.) - - This function only creates the scaled pixmap when the buffered pixmap has a different size than - the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does - not cause expensive rescaling every time. - - If scaling is disabled, sets mScaledPixmap to a null QPixmap. -*/ -void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) -{ - if (mPixmap.isNull()) - return; - - if (mScaled) - { - if (finalRect.isNull()) - finalRect = getFinalRect(&flipHorz, &flipVert); - if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()) - { - mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); - if (flipHorz || flipVert) - mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); - } - } else if (!mScaledPixmap.isNull()) - mScaledPixmap = QPixmap(); - mScaledPixmapInvalidated = false; -} - -/*! \internal - - Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions - and scaling settings. - - The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn - flipped horizontally or vertically in the returned rect. (The returned rect itself is always - normalized, i.e. the top left corner of the rect is actually further to the top/left than the - bottom right corner). This is the case when the item position \a topLeft is further to the - bottom/right than \a bottomRight. - - If scaling is disabled, returns a rect with size of the original pixmap and the top left corner - aligned with the item position \a topLeft. The position \a bottomRight is ignored. -*/ -QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const -{ - QRect result; - bool flipHorz = false; - bool flipVert = false; - QPoint p1 = topLeft->pixelPoint().toPoint(); - QPoint p2 = bottomRight->pixelPoint().toPoint(); - if (p1 == p2) - return QRect(p1, QSize(0, 0)); - if (mScaled) - { - QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); - QPoint topLeft = p1; - if (newSize.width() < 0) - { - flipHorz = true; - newSize.rwidth() *= -1; - topLeft.setX(p2.x()); - } - if (newSize.height() < 0) - { - flipVert = true; - newSize.rheight() *= -1; - topLeft.setY(p2.y()); - } - QSize scaledSize = mPixmap.size(); - scaledSize.scale(newSize, mAspectRatioMode); - result = QRect(topLeft, scaledSize); - } else - { - result = QRect(p1, mPixmap.size()); - } - if (flippedHorz) - *flippedHorz = flipHorz; - if (flippedVert) - *flippedVert = flipVert; - return result; -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected - and mSelectedPen when it is. -*/ -QPen QCPItemPixmap::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemTracer -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemTracer - \brief Item that sticks to QCPGraph data points - - \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." - - The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt - the coordinate axes of the graph and update its \a position to be on the graph's data. This means - the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a - QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a - position will have no effect because they will be overriden in the next redraw (this is when the - coordinate update happens). - - If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will - stay at the corresponding end of the graph. - - With \ref setInterpolating you may specify whether the tracer may only stay exactly on data - points or whether it interpolates data points linearly, if given a key that lies between two data - points of the graph. - - The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer - have no own visual appearance (set the style to \ref tsNone), and just connect other item - positions to the tracer \a position (used as an anchor) via \ref - QCPItemPosition::setParentAnchor. - - \note The tracer position is only automatically updated upon redraws. So when the data of the - graph changes and immediately afterwards (without a redraw) the a position coordinates of the - tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref - updatePosition must be called manually, prior to reading the tracer coordinates. -*/ - -/*! - Creates a tracer item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - position(createPosition(QLatin1String("position"))), - mGraph(0) -{ - position->setCoords(0, 0); - - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setStyle(tsCrosshair); - setSize(6); - setInterpolating(false); - setGraphKey(0); -} - -QCPItemTracer::~QCPItemTracer() -{ -} - -/*! - Sets the pen that will be used to draw the line of the tracer - - \see setSelectedPen, setBrush -*/ -void QCPItemTracer::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the line of the tracer when selected - - \see setPen, setSelected -*/ -void QCPItemTracer::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the brush that will be used to draw any fills of the tracer - - \see setSelectedBrush, setPen -*/ -void QCPItemTracer::setBrush(const QBrush &brush) -{ - mBrush = brush; -} - -/*! - Sets the brush that will be used to draw any fills of the tracer, when selected. - - \see setBrush, setSelected -*/ -void QCPItemTracer::setSelectedBrush(const QBrush &brush) -{ - mSelectedBrush = brush; -} - -/*! - Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare - does, \ref tsCrosshair does not). -*/ -void QCPItemTracer::setSize(double size) -{ - mSize = size; -} - -/*! - Sets the style/visual appearance of the tracer. - - If you only want to use the tracer \a position as an anchor for other items, set \a style to - \ref tsNone. -*/ -void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) -{ - mStyle = style; -} - -/*! - Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type - QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. - - To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed - freely like any other item position. This is the state the tracer will assume when its graph gets - deleted while still attached to it. - - \see setGraphKey -*/ -void QCPItemTracer::setGraph(QCPGraph *graph) -{ - if (graph) - { - if (graph->parentPlot() == mParentPlot) - { - position->setType(QCPItemPosition::ptPlotCoords); - position->setAxes(graph->keyAxis(), graph->valueAxis()); - mGraph = graph; - updatePosition(); - } else - qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; - } else - { - mGraph = 0; - } -} - -/*! - Sets the key of the graph's data point the tracer will be positioned at. This is the only free - coordinate of a tracer when attached to a graph. - - Depending on \ref setInterpolating, the tracer will be either positioned on the data point - closest to \a key, or will stay exactly at \a key and interpolate the value linearly. - - \see setGraph, setInterpolating -*/ -void QCPItemTracer::setGraphKey(double key) -{ - mGraphKey = key; -} - -/*! - Sets whether the value of the graph's data points shall be interpolated, when positioning the - tracer. - - If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on - the data point of the graph which is closest to the key, but which is not necessarily exactly - there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and - the appropriate value will be interpolated from the graph's data points linearly. - - \see setGraph, setGraphKey -*/ -void QCPItemTracer::setInterpolating(bool enabled) -{ - mInterpolating = enabled; -} - -/* inherits documentation from base class */ -double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QPointF center(position->pixelPoint()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return -1; - case tsPlus: - { - if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), - distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); - break; - } - case tsCrosshair: - { - return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), - distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); - } - case tsCircle: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - // distance to border: - double centerDist = QVector2D(center-pos).length(); - double circleLine = w; - double result = qAbs(centerDist-circleLine); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (centerDist <= circleLine) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; - } - break; - } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); - } - break; - } - } - return -1; -} - -/* inherits documentation from base class */ -void QCPItemTracer::draw(QCPPainter *painter) -{ - updatePosition(); - if (mStyle == tsNone) - return; - - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - QPointF center(position->pixelPoint()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return; - case tsPlus: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); - painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); - } - break; - } - case tsCrosshair: - { - if (center.y() > clip.top() && center.y() < clip.bottom()) - painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); - if (center.x() > clip.left() && center.x() < clip.right()) - painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); - break; - } - case tsCircle: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawEllipse(center, w, w); - break; - } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); - break; - } - } -} - -/*! - If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a - position to reside on the graph data, depending on the configured key (\ref setGraphKey). - - It is called automatically on every redraw and normally doesn't need to be called manually. One - exception is when you want to read the tracer coordinates via \a position and are not sure that - the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. - In that situation, call this function before accessing \a position, to make sure you don't get - out-of-date coordinates. - - If there is no graph set on this tracer, this function does nothing. -*/ -void QCPItemTracer::updatePosition() -{ - if (mGraph) - { - if (mParentPlot->hasPlottable(mGraph)) - { - if (mGraph->data()->size() > 1) - { - QCPDataMap::const_iterator first = mGraph->data()->constBegin(); - QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; - if (mGraphKey < first.key()) - position->setCoords(first.key(), first.value().value); - else if (mGraphKey > last.key()) - position->setCoords(last.key(), last.value().value); - else - { - QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); - if (it != first) // mGraphKey is somewhere between iterators - { - QCPDataMap::const_iterator prevIt = it-1; - if (mInterpolating) - { - // interpolate between iterators around mGraphKey: - double slope = 0; - if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) - slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); - position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); - } else - { - // find iterator with key closest to mGraphKey: - if (mGraphKey < (prevIt.key()+it.key())*0.5) - it = prevIt; - position->setCoords(it.key(), it.value().value); - } - } else // mGraphKey is exactly on first iterator - position->setCoords(it.key(), it.value().value); - } - } else if (mGraph->data()->size() == 1) - { - QCPDataMap::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it.key(), it.value().value); - } else - qDebug() << Q_FUNC_INFO << "graph has no data"; - } else - qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; - } -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected - and mSelectedPen when it is. -*/ -QPen QCPItemTracer::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \internal - - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item - is not selected and mSelectedBrush when it is. -*/ -QBrush QCPItemTracer::mainBrush() const -{ - return mSelected ? mSelectedBrush : mBrush; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPItemBracket -//////////////////////////////////////////////////////////////////////////////////////////////////// - -/*! \class QCPItemBracket - \brief A bracket for referencing/highlighting certain parts in the plot. - - \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." - - It has two positions, \a left and \a right, which define the span of the bracket. If \a left is - actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the - example image. - - The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket - stretches away from the embraced span, can be controlled with \ref setLength. - - \image html QCPItemBracket-length.png -
Demonstrating the effect of different values for \ref setLength, for styles \ref - bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
- - It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine - or QCPItemCurve) or a text label (QCPItemText), to the bracket. -*/ - -/*! - Creates a bracket item and sets default values. - - The constructed item can be added to the plot with QCustomPlot::addItem. -*/ -QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - left(createPosition(QLatin1String("left"))), - right(createPosition(QLatin1String("right"))), - center(createAnchor(QLatin1String("center"), aiCenter)) -{ - left->setCoords(0, 0); - right->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setLength(8); - setStyle(bsCalligraphic); -} - -QCPItemBracket::~QCPItemBracket() -{ -} - -/*! - Sets the pen that will be used to draw the bracket. - - Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the - stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use - \ref setLength, which has a similar effect. - - \see setSelectedPen -*/ -void QCPItemBracket::setPen(const QPen &pen) -{ - mPen = pen; -} - -/*! - Sets the pen that will be used to draw the bracket when selected - - \see setPen, setSelected -*/ -void QCPItemBracket::setSelectedPen(const QPen &pen) -{ - mSelectedPen = pen; -} - -/*! - Sets the \a length in pixels how far the bracket extends in the direction towards the embraced - span of the bracket (i.e. perpendicular to the left-right-direction) - - \image html QCPItemBracket-length.png -
Demonstrating the effect of different values for \ref setLength, for styles \ref - bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
-*/ -void QCPItemBracket::setLength(double length) -{ - mLength = length; -} - -/*! - Sets the style of the bracket, i.e. the shape/visual appearance. - - \see setPen -*/ -void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) -{ - mStyle = style; -} - -/* inherits documentation from base class */ -double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const -{ - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) - return -1; - - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; - - switch (mStyle) - { - case QCPItemBracket::bsSquare: - case QCPItemBracket::bsRound: - { - double a = distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); - double b = distSqrToLine((centerVec-widthVec+lengthVec).toPointF(), (centerVec-widthVec).toPointF(), pos); - double c = distSqrToLine((centerVec+widthVec+lengthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); - return qSqrt(qMin(qMin(a, b), c)); - } - case QCPItemBracket::bsCurly: - case QCPItemBracket::bsCalligraphic: - { - double a = distSqrToLine((centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); - double b = distSqrToLine((centerVec-widthVec+lengthVec*0.7f).toPointF(), (centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); - double c = distSqrToLine((centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); - double d = distSqrToLine((centerVec+widthVec+lengthVec*0.7f).toPointF(), (centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); - return qSqrt(qMin(qMin(a, b), qMin(c, d))); - } - } - return -1; -} - -/* inherits documentation from base class */ -void QCPItemBracket::draw(QCPPainter *painter) -{ - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) - return; - - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; - - QPolygon boundingPoly; - boundingPoly << leftVec.toPoint() << rightVec.toPoint() - << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (clip.intersects(boundingPoly.boundingRect())) - { - painter->setPen(mainPen()); - switch (mStyle) - { - case bsSquare: - { - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); - painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - break; - } - case bsRound: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - painter->drawPath(path); - break; - } - case bsCurly: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - painter->drawPath(path); - break; - } - case bsCalligraphic: - { - painter->setPen(Qt::NoPen); - painter->setBrush(QBrush(mainPen().color())); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - - path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - - path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); - path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); - - painter->drawPath(path); - break; - } - } - } -} - -/* inherits documentation from base class */ -QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const -{ - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) - return leftVec.toPointF(); - - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; - - switch (anchorId) - { - case aiCenter: - return centerVec.toPointF(); - } - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); -} - -/*! \internal - - Returns the pen that should be used for drawing lines. Returns mPen when the - item is not selected and mSelectedPen when it is. -*/ -QPen QCPItemBracket::mainPen() const -{ - return mSelected ? mSelectedPen : mPen; -} - diff --git a/lib/QCustomPlot/QCustomPlot.h b/lib/QCustomPlot/QCustomPlot.h deleted file mode 100644 index a0de256..0000000 --- a/lib/QCustomPlot/QCustomPlot.h +++ /dev/null @@ -1,3772 +0,0 @@ -/*************************************************************************** -** ** -** QCustomPlot, an easy to use, modern plotting widget for Qt ** -** Copyright (C) 2011-2015 Emanuel Eichhammer ** -** ** -** This program is free software: you can redistribute it and/or modify ** -** it under the terms of the GNU General Public License as published by ** -** the Free Software Foundation, either version 3 of the License, or ** -** (at your option) any later version. ** -** ** -** This program is distributed in the hope that it will be useful, ** -** but WITHOUT ANY WARRANTY; without even the implied warranty of ** -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** -** GNU General Public License for more details. ** -** ** -** You should have received a copy of the GNU General Public License ** -** along with this program. If not, see http://www.gnu.org/licenses/. ** -** ** -**************************************************************************** -** Author: Emanuel Eichhammer ** -** Website/Contact: http://www.qcustomplot.com/ ** -** Date: 22.12.15 ** -** Version: 1.3.2 ** -****************************************************************************/ - -#ifndef QCUSTOMPLOT_H -#define QCUSTOMPLOT_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) -# include -# include -# include -#else -# include -# include -#endif - -class QCPPainter; -class QCustomPlot; -class QCPLayerable; -class QCPLayoutElement; -class QCPLayout; -class QCPAxis; -class QCPAxisRect; -class QCPAxisPainterPrivate; -class QCPAbstractPlottable; -class QCPGraph; -class QCPAbstractItem; -class QCPItemPosition; -class QCPLayer; -class QCPPlotTitle; -class QCPLegend; -class QCPAbstractLegendItem; -class QCPColorMap; -class QCPColorScale; -class QCPBars; - - -/*! \file */ - - -// decl definitions for shared library compilation/usage: -/* LFV - #if defined(QCUSTOMPLOT_COMPILE_LIBRARY) - # define QCP_LIB_DECL Q_DECL_EXPORT - #elif defined(QCUSTOMPLOT_USE_LIBRARY) - # define QCP_LIB_DECL Q_DECL_IMPORT - #else - # define QCP_LIB_DECL - #endif -*/ -#include -#define QCP_LIB_DECL cp_QCustomPlot_EXPORT - -/*! - The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library -*/ -namespace QCP -{ -/*! - Defines the sides of a rectangular entity to which margins can be applied. - - \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins -*/ -enum MarginSide { msLeft = 0x01 ///< 0x01 left margin - ,msRight = 0x02 ///< 0x02 right margin - ,msTop = 0x04 ///< 0x04 top margin - ,msBottom = 0x08 ///< 0x08 bottom margin - ,msAll = 0xFF ///< 0xFF all margins - ,msNone = 0x00 ///< 0x00 no margin - }; -Q_DECLARE_FLAGS(MarginSides, MarginSide) - -/*! - Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is - neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective - element how it is drawn. Typically it provides a \a setAntialiased function for this. - - \c AntialiasedElements is a flag of or-combined elements of this enum type. - - \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements -*/ -enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks - ,aeGrid = 0x0002 ///< 0x0002 Grid lines - ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines - ,aeLegend = 0x0008 ///< 0x0008 Legend box - ,aeLegendItems = 0x0010 ///< 0x0010 Legend items - ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) - ,aeItems = 0x0040 ///< 0x0040 Main lines of items - ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) - ,aeErrorBars = 0x0100 ///< 0x0100 Error bars - ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) - ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen - ,aeAll = 0xFFFF ///< 0xFFFF All elements - ,aeNone = 0x0000 ///< 0x0000 No elements - }; -Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) - -/*! - Defines plotting hints that control various aspects of the quality and speed of plotting. - - \see QCustomPlot::setPlottingHints -*/ -enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set - ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality - ///< especially of the line segment joins. (Only relevant for solid line pens.) - ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. - ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). - ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. - }; -Q_DECLARE_FLAGS(PlottingHints, PlottingHint) - -/*! - Defines the mouse interactions possible with QCustomPlot. - - \c Interactions is a flag of or-combined elements of this enum type. - - \see QCustomPlot::setInteractions -*/ -enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) - ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) - ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking - ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) - ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) - ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) - ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) - ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) - }; -Q_DECLARE_FLAGS(Interactions, Interaction) - -/*! \internal - - Returns whether the specified \a value is considered an invalid data value for plottables (i.e. - is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the - compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. -*/ -inline bool isInvalidData(double value) -{ - return qIsNaN(value) || qIsInf(value); -} - -/*! \internal - \overload - - Checks two arguments instead of one. -*/ -inline bool isInvalidData(double value1, double value2) -{ - return isInvalidData(value1) || isInvalidData(value2); -} - -/*! \internal - - Sets the specified \a side of \a margins to \a value - - \see getMarginValue -*/ -inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) -{ - switch (side) - { - case QCP::msLeft: margins.setLeft(value); break; - case QCP::msRight: margins.setRight(value); break; - case QCP::msTop: margins.setTop(value); break; - case QCP::msBottom: margins.setBottom(value); break; - case QCP::msAll: margins = QMargins(value, value, value, value); break; - default: break; - } -} - -/*! \internal - - Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or - \ref QCP::msAll, returns 0. - - \see setMarginValue -*/ -inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) -{ - switch (side) - { - case QCP::msLeft: return margins.left(); - case QCP::msRight: return margins.right(); - case QCP::msTop: return margins.top(); - case QCP::msBottom: return margins.bottom(); - default: break; - } - return 0; -} - -} // end of namespace QCP - -Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) -Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) -Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) -Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) - - -class QCP_LIB_DECL QCPScatterStyle -{ - Q_GADGET -public: - /*! - Defines the shape used for scatter points. - - On plottables/items that draw scatters, the sizes of these visualizations (with exception of - \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are - drawn with the pen and brush specified with \ref setPen and \ref setBrush. - */ - Q_ENUMS(ScatterShape) - enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) - ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) - ,ssCross ///< \enumimage{ssCross.png} a cross - ,ssPlus ///< \enumimage{ssPlus.png} a plus - ,ssCircle ///< \enumimage{ssCircle.png} a circle - ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) - ,ssSquare ///< \enumimage{ssSquare.png} a square - ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond - ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus - ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline - ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner - ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside - ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside - ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside - ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside - ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines - ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates - ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) - }; - - QCPScatterStyle(); - QCPScatterStyle(ScatterShape shape, double size=6); - QCPScatterStyle(ScatterShape shape, const QColor &color, double size); - QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); - QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); - QCPScatterStyle(const QPixmap &pixmap); - QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); - - // getters: - double size() const { return mSize; } - ScatterShape shape() const { return mShape; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - QPixmap pixmap() const { return mPixmap; } - QPainterPath customPath() const { return mCustomPath; } - - // setters: - void setSize(double size); - void setShape(ScatterShape shape); - void setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setPixmap(const QPixmap &pixmap); - void setCustomPath(const QPainterPath &customPath); - - // non-property methods: - bool isNone() const { return mShape == ssNone; } - bool isPenDefined() const { return mPenDefined; } - void applyTo(QCPPainter *painter, const QPen &defaultPen) const; - void drawShape(QCPPainter *painter, QPointF pos) const; - void drawShape(QCPPainter *painter, double x, double y) const; - -protected: - // property members: - double mSize; - ScatterShape mShape; - QPen mPen; - QBrush mBrush; - QPixmap mPixmap; - QPainterPath mCustomPath; - - // non-property members: - bool mPenDefined; -}; -Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); - - -class QCP_LIB_DECL QCPPainter : public QPainter -{ - Q_GADGET -public: - /*! - Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, - depending on whether they are wanted on the respective output device. - */ - enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices - ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. - ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels - ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) - }; - Q_FLAGS(PainterMode PainterModes) - Q_DECLARE_FLAGS(PainterModes, PainterMode) - - QCPPainter(); - QCPPainter(QPaintDevice *device); - ~QCPPainter(); - - // getters: - bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } - PainterModes modes() const { return mModes; } - - // setters: - void setAntialiasing(bool enabled); - void setMode(PainterMode mode, bool enabled=true); - void setModes(PainterModes modes); - - // methods hiding non-virtual base class functions (QPainter bug workarounds): - bool begin(QPaintDevice *device); - void setPen(const QPen &pen); - void setPen(const QColor &color); - void setPen(Qt::PenStyle penStyle); - void drawLine(const QLineF &line); - void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} - void save(); - void restore(); - - // non-virtual methods: - void makeNonCosmetic(); - -protected: - // property members: - PainterModes mModes; - bool mIsAntialiasing; - - // non-property members: - QStack mAntialiasingStack; -}; -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) - - -class QCP_LIB_DECL QCPLayer : public QObject -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QString name READ name) - Q_PROPERTY(int index READ index) - Q_PROPERTY(QList children READ children) - Q_PROPERTY(bool visible READ visible WRITE setVisible) - /// \endcond -public: - QCPLayer(QCustomPlot* parentPlot, const QString &layerName); - ~QCPLayer(); - - // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } - QString name() const { return mName; } - int index() const { return mIndex; } - QList children() const { return mChildren; } - bool visible() const { return mVisible; } - - // setters: - void setVisible(bool visible); - -protected: - // property members: - QCustomPlot *mParentPlot; - QString mName; - int mIndex; - QList mChildren; - bool mVisible; - - // non-virtual methods: - void addChild(QCPLayerable *layerable, bool prepend); - void removeChild(QCPLayerable *layerable); - -private: - Q_DISABLE_COPY(QCPLayer) - - friend class QCustomPlot; - friend class QCPLayerable; -}; - -class QCP_LIB_DECL QCPLayerable : public QObject -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool visible READ visible WRITE setVisible) - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) - Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) - Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) - /// \endcond -public: - QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); - ~QCPLayerable(); - - // getters: - bool visible() const { return mVisible; } - QCustomPlot *parentPlot() const { return mParentPlot; } - QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } - QCPLayer *layer() const { return mLayer; } - bool antialiased() const { return mAntialiased; } - - // setters: - void setVisible(bool on); - Q_SLOT bool setLayer(QCPLayer *layer); - bool setLayer(const QString &layerName); - void setAntialiased(bool enabled); - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-property methods: - bool realVisibility() const; - -signals: - void layerChanged(QCPLayer *newLayer); - -protected: - // property members: - bool mVisible; - QCustomPlot *mParentPlot; - QPointer mParentLayerable; - QCPLayer *mLayer; - bool mAntialiased; - - // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; - virtual void draw(QCPPainter *painter) = 0; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-property methods: - void initializeParentPlot(QCustomPlot *parentPlot); - void setParentLayerable(QCPLayerable* parentLayerable); - bool moveToLayer(QCPLayer *layer, bool prepend); - void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; - -private: - Q_DISABLE_COPY(QCPLayerable) - - friend class QCustomPlot; - friend class QCPAxisRect; -}; - - -class QCP_LIB_DECL QCPRange -{ -public: - double lower, upper; - - QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) const { return !(*this == other); } - - QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } - QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } - QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } - QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } - friend inline const QCPRange operator+(const QCPRange&, double); - friend inline const QCPRange operator+(double, const QCPRange&); - friend inline const QCPRange operator-(const QCPRange& range, double value); - friend inline const QCPRange operator*(const QCPRange& range, double value); - friend inline const QCPRange operator*(double value, const QCPRange& range); - friend inline const QCPRange operator/(const QCPRange& range, double value); - - double size() const; - double center() const; - void normalize(); - void expand(const QCPRange &otherRange); - QCPRange expanded(const QCPRange &otherRange) const; - QCPRange sanitizedForLogScale() const; - QCPRange sanitizedForLinScale() const; - bool contains(double value) const; - - static bool validRange(double lower, double upper); - static bool validRange(const QCPRange &range); - static const double minRange; //1e-280; - static const double maxRange; //1e280; - -}; -Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); - -/* documentation of inline functions */ - -/*! \fn QCPRange &QCPRange::operator+=(const double& value) - - Adds \a value to both boundaries of the range. -*/ - -/*! \fn QCPRange &QCPRange::operator-=(const double& value) - - Subtracts \a value from both boundaries of the range. -*/ - -/*! \fn QCPRange &QCPRange::operator*=(const double& value) - - Multiplies both boundaries of the range by \a value. -*/ - -/*! \fn QCPRange &QCPRange::operator/=(const double& value) - - Divides both boundaries of the range by \a value. -*/ - -/* end documentation of inline functions */ - -/*! - Adds \a value to both boundaries of the range. -*/ -inline const QCPRange operator+(const QCPRange& range, double value) -{ - QCPRange result(range); - result += value; - return result; -} - -/*! - Adds \a value to both boundaries of the range. -*/ -inline const QCPRange operator+(double value, const QCPRange& range) -{ - QCPRange result(range); - result += value; - return result; -} - -/*! - Subtracts \a value from both boundaries of the range. -*/ -inline const QCPRange operator-(const QCPRange& range, double value) -{ - QCPRange result(range); - result -= value; - return result; -} - -/*! - Multiplies both boundaries of the range by \a value. -*/ -inline const QCPRange operator*(const QCPRange& range, double value) -{ - QCPRange result(range); - result *= value; - return result; -} - -/*! - Multiplies both boundaries of the range by \a value. -*/ -inline const QCPRange operator*(double value, const QCPRange& range) -{ - QCPRange result(range); - result *= value; - return result; -} - -/*! - Divides both boundaries of the range by \a value. -*/ -inline const QCPRange operator/(const QCPRange& range, double value) -{ - QCPRange result(range); - result /= value; - return result; -} - - -class QCP_LIB_DECL QCPMarginGroup : public QObject -{ - Q_OBJECT -public: - QCPMarginGroup(QCustomPlot *parentPlot); - ~QCPMarginGroup(); - - // non-virtual methods: - QList elements(QCP::MarginSide side) const { return mChildren.value(side); } - bool isEmpty() const; - void clear(); - -protected: - // non-property members: - QCustomPlot *mParentPlot; - QHash > mChildren; - - // non-virtual methods: - int commonMargin(QCP::MarginSide side) const; - void addChild(QCP::MarginSide side, QCPLayoutElement *element); - void removeChild(QCP::MarginSide side, QCPLayoutElement *element); - -private: - Q_DISABLE_COPY(QCPMarginGroup) - - friend class QCPLayoutElement; -}; - - -class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLayout* layout READ layout) - Q_PROPERTY(QRect rect READ rect) - Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) - Q_PROPERTY(QMargins margins READ margins WRITE setMargins) - Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) - Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) - Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) - /// \endcond -public: - /*! - Defines the phases of the update process, that happens just before a replot. At each phase, - \ref update is called with the according UpdatePhase value. - */ - enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout - ,upMargins ///< Phase in which the margins are calculated and set - ,upLayout ///< Final phase in which the layout system places the rects of the elements - }; - Q_ENUMS(UpdatePhase) - - explicit QCPLayoutElement(QCustomPlot *parentPlot=0); - virtual ~QCPLayoutElement(); - - // getters: - QCPLayout *layout() const { return mParentLayout; } - QRect rect() const { return mRect; } - QRect outerRect() const { return mOuterRect; } - QMargins margins() const { return mMargins; } - QMargins minimumMargins() const { return mMinimumMargins; } - QCP::MarginSides autoMargins() const { return mAutoMargins; } - QSize minimumSize() const { return mMinimumSize; } - QSize maximumSize() const { return mMaximumSize; } - QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } - QHash marginGroups() const { return mMarginGroups; } - - // setters: - void setOuterRect(const QRect &rect); - void setMargins(const QMargins &margins); - void setMinimumMargins(const QMargins &margins); - void setAutoMargins(QCP::MarginSides sides); - void setMinimumSize(const QSize &size); - void setMinimumSize(int width, int height); - void setMaximumSize(const QSize &size); - void setMaximumSize(int width, int height); - void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); - - // introduced virtual methods: - virtual void update(UpdatePhase phase); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; - virtual QList elements(bool recursive) const; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -protected: - // property members: - QCPLayout *mParentLayout; - QSize mMinimumSize, mMaximumSize; - QRect mRect, mOuterRect; - QMargins mMargins, mMinimumMargins; - QCP::MarginSides mAutoMargins; - QHash mMarginGroups; - - // introduced virtual methods: - virtual int calculateAutoMargin(QCP::MarginSide side); - // events: - virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } - virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - -private: - Q_DISABLE_COPY(QCPLayoutElement) - - friend class QCustomPlot; - friend class QCPLayout; - friend class QCPMarginGroup; -}; - - -class QCP_LIB_DECL QCPLayout : public QCPLayoutElement -{ - Q_OBJECT -public: - explicit QCPLayout(); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; - - // introduced virtual methods: - virtual int elementCount() const = 0; - virtual QCPLayoutElement* elementAt(int index) const = 0; - virtual QCPLayoutElement* takeAt(int index) = 0; - virtual bool take(QCPLayoutElement* element) = 0; - virtual void simplify(); - - // non-virtual methods: - bool removeAt(int index); - bool remove(QCPLayoutElement* element); - void clear(); - -protected: - // introduced virtual methods: - virtual void updateLayout(); - - // non-virtual methods: - void sizeConstraintsChanged() const; - void adoptElement(QCPLayoutElement *el); - void releaseElement(QCPLayoutElement *el); - QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; - -private: - Q_DISABLE_COPY(QCPLayout) - friend class QCPLayoutElement; -}; - - -class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(int rowCount READ rowCount) - Q_PROPERTY(int columnCount READ columnCount) - Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) - Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) - Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) - Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) - /// \endcond -public: - explicit QCPLayoutGrid(); - virtual ~QCPLayoutGrid(); - - // getters: - int rowCount() const; - int columnCount() const; - QList columnStretchFactors() const { return mColumnStretchFactors; } - QList rowStretchFactors() const { return mRowStretchFactors; } - int columnSpacing() const { return mColumnSpacing; } - int rowSpacing() const { return mRowSpacing; } - - // setters: - void setColumnStretchFactor(int column, double factor); - void setColumnStretchFactors(const QList &factors); - void setRowStretchFactor(int row, double factor); - void setRowStretchFactors(const QList &factors); - void setColumnSpacing(int pixels); - void setRowSpacing(int pixels); - - // reimplemented virtual methods: - virtual void updateLayout(); - virtual int elementCount() const; - virtual QCPLayoutElement* elementAt(int index) const; - virtual QCPLayoutElement* takeAt(int index); - virtual bool take(QCPLayoutElement* element); - virtual QList elements(bool recursive) const; - virtual void simplify(); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; - - // non-virtual methods: - QCPLayoutElement *element(int row, int column) const; - bool addElement(int row, int column, QCPLayoutElement *element); - bool hasElement(int row, int column); - void expandTo(int newRowCount, int newColumnCount); - void insertRow(int newIndex); - void insertColumn(int newIndex); - -protected: - // property members: - QList > mElements; - QList mColumnStretchFactors; - QList mRowStretchFactors; - int mColumnSpacing, mRowSpacing; - - // non-virtual methods: - void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; - void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; - -private: - Q_DISABLE_COPY(QCPLayoutGrid) -}; - - -class QCP_LIB_DECL QCPLayoutInset : public QCPLayout -{ - Q_OBJECT -public: - /*! - Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. - */ - enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect - ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment - }; - - explicit QCPLayoutInset(); - virtual ~QCPLayoutInset(); - - // getters: - InsetPlacement insetPlacement(int index) const; - Qt::Alignment insetAlignment(int index) const; - QRectF insetRect(int index) const; - - // setters: - void setInsetPlacement(int index, InsetPlacement placement); - void setInsetAlignment(int index, Qt::Alignment alignment); - void setInsetRect(int index, const QRectF &rect); - - // reimplemented virtual methods: - virtual void updateLayout(); - virtual int elementCount() const; - virtual QCPLayoutElement* elementAt(int index) const; - virtual QCPLayoutElement* takeAt(int index); - virtual bool take(QCPLayoutElement* element); - virtual void simplify() {} - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-virtual methods: - void addElement(QCPLayoutElement *element, Qt::Alignment alignment); - void addElement(QCPLayoutElement *element, const QRectF &rect); - -protected: - // property members: - QList mElements; - QList mInsetPlacement; - QList mInsetAlignment; - QList mInsetRect; - -private: - Q_DISABLE_COPY(QCPLayoutInset) -}; - - -class QCP_LIB_DECL QCPLineEnding -{ - Q_GADGET -public: - /*! - Defines the type of ending decoration for line-like items, e.g. an arrow. - - \image html QCPLineEnding.png - - The width and length of these decorations can be controlled with the functions \ref setWidth - and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only - support a width, the length property is ignored. - - \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding - */ - Q_ENUMS(EndingStyle) - enum EndingStyle { esNone ///< No ending decoration - ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) - ,esSpikeArrow ///< A filled arrow head with an indented back - ,esLineArrow ///< A non-filled arrow head with open back - ,esDisc ///< A filled circle - ,esSquare ///< A filled square - ,esDiamond ///< A filled diamond (45° rotated square) - ,esBar ///< A bar perpendicular to the line - ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) - ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) - }; - - QCPLineEnding(); - QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); - - // getters: - EndingStyle style() const { return mStyle; } - double width() const { return mWidth; } - double length() const { return mLength; } - bool inverted() const { return mInverted; } - - // setters: - void setStyle(EndingStyle style); - void setWidth(double width); - void setLength(double length); - void setInverted(bool inverted); - - // non-property methods: - double boundingDistance() const; - double realLength() const; - void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; - void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; - -protected: - // property members: - EndingStyle mStyle; - double mWidth, mLength; - bool mInverted; -}; -Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); - - -class QCP_LIB_DECL QCPGrid :public QCPLayerable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) - Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) - Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) - Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) - /// \endcond -public: - QCPGrid(QCPAxis *parentAxis); - - // getters: - bool subGridVisible() const { return mSubGridVisible; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen pen() const { return mPen; } - QPen subGridPen() const { return mSubGridPen; } - QPen zeroLinePen() const { return mZeroLinePen; } - - // setters: - void setSubGridVisible(bool visible); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setPen(const QPen &pen); - void setSubGridPen(const QPen &pen); - void setZeroLinePen(const QPen &pen); - -protected: - // property members: - bool mSubGridVisible; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mPen, mSubGridPen, mZeroLinePen; - // non-property members: - QCPAxis *mParentAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - void drawGridLines(QCPPainter *painter) const; - void drawSubGridLines(QCPPainter *painter) const; - - friend class QCPAxis; -}; - - -class QCP_LIB_DECL QCPAxis : public QCPLayerable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(AxisType axisType READ axisType) - Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) - Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) - Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) - Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) - Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) - Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) - Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) - Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) - Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) - Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) - Q_PROPERTY(bool ticks READ ticks WRITE setTicks) - Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) - Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) - Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) - Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) - Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) - Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) - Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) - Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) - Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) - Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) - Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) - Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) - Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) - Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) - Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) - Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) - Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) - Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) - Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) - Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) - Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) - Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) - Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) - Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) - Q_PROPERTY(int padding READ padding WRITE setPadding) - Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) - Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) - Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) - Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) - Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) - Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) - Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) - Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) - Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) - Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) - Q_PROPERTY(QCPGrid* grid READ grid) - /// \endcond -public: - /*! - Defines at which side of the axis rect the axis will appear. This also affects how the tick - marks are drawn, on which side the labels are placed etc. - */ - enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect - ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect - ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect - ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect - }; - Q_FLAGS(AxisType AxisTypes) - Q_DECLARE_FLAGS(AxisTypes, AxisType) - /*! - When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the - coordinate of the tick is interpreted, i.e. translated into a string. - - \see setTickLabelType - */ - enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) - ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) - }; - Q_ENUMS(LabelType) - /*! - Defines on which side of the axis the tick labels (numbers) shall appear. - - \see setTickLabelSide - */ - enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect - ,lsOutside ///< Tick labels will be displayed outside the axis rect - }; - Q_ENUMS(LabelSide) - /*! - Defines the scale of an axis. - \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). - }; - Q_ENUMS(ScaleType) - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_FLAGS(SelectablePart SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPAxis(QCPAxisRect *parent, AxisType type); - virtual ~QCPAxis(); - - // getters: - AxisType axisType() const { return mAxisType; } - QCPAxisRect *axisRect() const { return mAxisRect; } - ScaleType scaleType() const { return mScaleType; } - double scaleLogBase() const { return mScaleLogBase; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - bool autoTicks() const { return mAutoTicks; } - int autoTickCount() const { return mAutoTickCount; } - bool autoTickLabels() const { return mAutoTickLabels; } - bool autoTickStep() const { return mAutoTickStep; } - bool autoSubTicks() const { return mAutoSubTicks; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const; - LabelType tickLabelType() const { return mTickLabelType; } - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const; - LabelSide tickLabelSide() const; - QString dateTimeFormat() const { return mDateTimeFormat; } - Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - double tickStep() const { return mTickStep; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - int subTickCount() const { return mSubTickCount; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - int padding() const { return mPadding; } - int offset() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPLineEnding lowerEnding() const; - QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - - // setters: - Q_SLOT void setScaleType(QCPAxis::ScaleType type); - void setScaleLogBase(double base); - Q_SLOT void setRange(const QCPRange &range); - void setRange(double lower, double upper); - void setRange(double position, double size, Qt::AlignmentFlag alignment); - void setRangeLower(double lower); - void setRangeUpper(double upper); - void setRangeReversed(bool reversed); - void setAutoTicks(bool on); - void setAutoTickCount(int approximateCount); - void setAutoTickLabels(bool on); - void setAutoTickStep(bool on); - void setAutoSubTicks(bool on); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelType(LabelType type); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelSide(LabelSide side); - void setDateTimeFormat(const QString &format); - void setDateTimeSpec(const Qt::TimeSpec &timeSpec); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickStep(double step); - void setTickVector(const QVector &vec); - void setTickVectorLabels(const QVector &vec); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTickCount(int count); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setPadding(int padding); - void setOffset(int offset); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); - void setLowerEnding(const QCPLineEnding &ending); - void setUpperEnding(const QCPLineEnding &ending); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-property methods: - Qt::Orientation orientation() const { return mOrientation; } - void moveRange(double diff); - void scaleRange(double factor, double center); - void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); - void rescale(bool onlyVisiblePlottables=false); - double pixelToCoord(double value) const; - double coordToPixel(double value) const; - SelectablePart getPartAt(const QPointF &pos) const; - QList plottables() const; - QList graphs() const; - QList items() const; - - static AxisType marginSideToAxisType(QCP::MarginSide side); - static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } - static AxisType opposite(AxisType type); - -signals: - void ticksRequest(); - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPAxis::ScaleType scaleType); - void selectionChanged(const QCPAxis::SelectableParts &parts); - void selectableChanged(const QCPAxis::SelectableParts &parts); - -protected: - // property members: - // axis base: - AxisType mAxisType; - QCPAxisRect *mAxisRect; - //int mOffset; // in QCPAxisPainter - int mPadding; - Qt::Orientation mOrientation; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter - // axis label: - //int mLabelPadding; // in QCPAxisPainter - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels, mAutoTickLabels; - //double mTickLabelRotation; // in QCPAxisPainter - LabelType mTickLabelType; - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - QString mDateTimeFormat; - Qt::TimeSpec mDateTimeSpec; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - //bool mNumberMultiplyCross; // QCPAxisPainter - // ticks and subticks: - bool mTicks; - double mTickStep; - int mSubTickCount, mAutoTickCount; - bool mAutoTicks, mAutoTickStep, mAutoSubTicks; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - double mScaleLogBase, mScaleLogBaseLogInv; - - // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; - int mLowestVisibleTick, mHighestVisibleTick; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mCachedMarginValid; - int mCachedMargin; - - // introduced virtual methods: - virtual void setupTickVectors(); - virtual void generateAutoTicks(); - virtual int calculateAutoSubTickCount(double tickStep) const; - virtual int calculateMargin(); - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual QCP::Interaction selectionCategory() const; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - void visibleTickBounds(int &lowIndex, int &highIndex) const; - double baseLog(double value) const; - double basePow(double value) const; - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - -private: - Q_DISABLE_COPY(QCPAxis) - - friend class QCustomPlot; - friend class QCPGrid; - friend class QCPAxisRect; -}; -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) -Q_DECLARE_METATYPE(QCPAxis::SelectablePart) - - -class QCPAxisPainterPrivate -{ -public: - explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); - virtual int size() const; - void clearCache(); - - QRect axisSelectionBox() const { return mAxisSelectionBox; } - QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } - QRect labelSelectionBox() const { return mLabelSelectionBox; } - - // public property members: - QCPAxis::AxisType type; - QPen basePen; - QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters - int labelPadding; // directly accessed by QCPAxis setters/getters - QFont labelFont; - QColor labelColor; - QString label; - int tickLabelPadding; // directly accessed by QCPAxis setters/getters - double tickLabelRotation; // directly accessed by QCPAxis setters/getters - QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters - bool substituteExponent; - bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters - int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters - QPen tickPen, subTickPen; - QFont tickLabelFont; - QColor tickLabelColor; - QRect axisRect, viewportRect; - double offset; // directly accessed by QCPAxis setters/getters - bool abbreviateDecimalPowers; - bool reversedEndings; - - QVector subTickPositions; - QVector tickPositions; - QVector tickLabels; - -protected: - struct CachedLabel - { - QPointF offset; - QPixmap pixmap; - }; - struct TickLabelData - { - QString basePart, expPart; - QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; - QFont baseFont, expFont; - }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - - virtual QByteArray generateLabelParameterHash() const; - - virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); - virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; - virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; - virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; - virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; -}; - - -class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString name READ name WRITE setName) - Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) - Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) - Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) - Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond -public: - QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // getters: - QString name() const { return mName; } - bool antialiasedFill() const { return mAntialiasedFill; } - bool antialiasedScatters() const { return mAntialiasedScatters; } - bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setName(const QString &name); - void setAntialiasedFill(bool enabled); - void setAntialiasedScatters(bool enabled); - void setAntialiasedErrorBars(bool enabled); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setKeyAxis(QCPAxis *axis); - void setValueAxis(QCPAxis *axis); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // introduced virtual methods: - virtual void clearData() = 0; - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; - virtual bool addToLegend(); - virtual bool removeFromLegend() const; - - // non-property methods: - void rescaleAxes(bool onlyEnlarge=false) const; - void rescaleKeyAxis(bool onlyEnlarge=false) const; - void rescaleValueAxis(bool onlyEnlarge=false) const; - -signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - -protected: - /*! - Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. - */ - enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero - ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers - ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero - }; - - // property members: - QString mName; - bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QPointer mKeyAxis, mValueAxis; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 0; - virtual QCP::Interaction selectionCategory() const; - void applyDefaultAntialiasingHint(QCPPainter *painter) const; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // introduced virtual methods: - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; - - // non-virtual methods: - void coordsToPixels(double key, double value, double &x, double &y) const; - const QPointF coordsToPixels(double key, double value) const; - void pixelsToCoords(double x, double y, double &key, double &value) const; - void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; - QPen mainPen() const; - QBrush mainBrush() const; - void applyFillAntialiasingHint(QCPPainter *painter) const; - void applyScattersAntialiasingHint(QCPPainter *painter) const; - void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; - double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; - -private: - Q_DISABLE_COPY(QCPAbstractPlottable) - - friend class QCustomPlot; - friend class QCPAxis; - friend class QCPPlottableLegendItem; -}; - - -class QCP_LIB_DECL QCPItemAnchor -{ -public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); - virtual ~QCPItemAnchor(); - - // getters: - QString name() const { return mName; } - virtual QPointF pixelPoint() const; - -protected: - // property members: - QString mName; - - // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; - int mAnchorId; - QSet mChildrenX, mChildrenY; - - // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return 0; } - - // non-virtual methods: - void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - -private: - Q_DISABLE_COPY(QCPItemAnchor) - - friend class QCPItemPosition; -}; - - - -class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor -{ -public: - /*! - Defines the ways an item position can be specified. Thus it defines what the numbers passed to - \ref setCoords actually mean. - - \see setType - */ - enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. - ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the viewport/widget, etc. - ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. - ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). - }; - - QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); - virtual ~QCPItemPosition(); - - // getters: - PositionType type() const { return typeX(); } - PositionType typeX() const { return mPositionTypeX; } - PositionType typeY() const { return mPositionTypeY; } - QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } - QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } - QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } - double key() const { return mKey; } - double value() const { return mValue; } - QPointF coords() const { return QPointF(mKey, mValue); } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - QCPAxisRect *axisRect() const; - virtual QPointF pixelPoint() const; - - // setters: - void setType(PositionType type); - void setTypeX(PositionType type); - void setTypeY(PositionType type); - bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - void setCoords(double key, double value); - void setCoords(const QPointF &coords); - void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); - void setAxisRect(QCPAxisRect *axisRect); - void setPixelPoint(const QPointF &pixelPoint); - -protected: - // property members: - PositionType mPositionTypeX, mPositionTypeY; - QPointer mKeyAxis, mValueAxis; - QPointer mAxisRect; - double mKey, mValue; - QCPItemAnchor *mParentAnchorX, *mParentAnchorY; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return this; } - -private: - Q_DISABLE_COPY(QCPItemPosition) - -}; - - -class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) - Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond -public: - QCPAbstractItem(QCustomPlot *parentPlot); - virtual ~QCPAbstractItem(); - - // getters: - bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setClipToAxisRect(bool clip); - void setClipAxisRect(QCPAxisRect *rect); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; - - // non-virtual methods: - QList positions() const { return mPositions; } - QList anchors() const { return mAnchors; } - QCPItemPosition *position(const QString &name) const; - QCPItemAnchor *anchor(const QString &name) const; - bool hasAnchor(const QString &name) const; - -signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - -protected: - // property members: - bool mClipToAxisRect; - QPointer mClipAxisRect; - QList mPositions; - QList mAnchors; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter) = 0; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // introduced virtual methods: - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; - double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; - QCPItemPosition *createPosition(const QString &name); - QCPItemAnchor *createAnchor(const QString &name, int anchorId); - -private: - Q_DISABLE_COPY(QCPAbstractItem) - - friend class QCustomPlot; - friend class QCPItemAnchor; -}; - - -class QCP_LIB_DECL QCustomPlot : public QWidget -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) - Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) - Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) - Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) - Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) - /// \endcond -public: - /*! - Defines how a layer should be inserted relative to an other layer. - - \see addLayer, moveLayer - */ - enum LayerInsertMode { limBelow ///< Layer is inserted below other layer - ,limAbove ///< Layer is inserted above other layer - }; - Q_ENUMS(LayerInsertMode) - - /*! - Defines with what timing the QCustomPlot surface is refreshed after a replot. - - \see replot - */ - enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot - ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot - ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. - }; - - explicit QCustomPlot(QWidget *parent = 0); - virtual ~QCustomPlot(); - - // getters: - QRect viewport() const { return mViewport; } - QPixmap background() const { return mBackgroundPixmap; } - bool backgroundScaled() const { return mBackgroundScaled; } - Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } - QCPLayoutGrid *plotLayout() const { return mPlotLayout; } - QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } - QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } - bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } - const QCP::Interactions interactions() const { return mInteractions; } - int selectionTolerance() const { return mSelectionTolerance; } - bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } - QCP::PlottingHints plottingHints() const { return mPlottingHints; } - Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } - - // setters: - void setViewport(const QRect &rect); - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); - void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); - void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); - void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); - void setAutoAddPlottableToLegend(bool on); - void setInteractions(const QCP::Interactions &interactions); - void setInteraction(const QCP::Interaction &interaction, bool enabled=true); - void setSelectionTolerance(int pixels); - void setNoAntialiasingOnDrag(bool enabled); - void setPlottingHints(const QCP::PlottingHints &hints); - void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); - void setMultiSelectModifier(Qt::KeyboardModifier modifier); - - // non-property methods: - // plottable interface: - QCPAbstractPlottable *plottable(int index); - QCPAbstractPlottable *plottable(); - bool addPlottable(QCPAbstractPlottable *plottable); - bool removePlottable(QCPAbstractPlottable *plottable); - bool removePlottable(int index); - int clearPlottables(); - int plottableCount() const; - QList selectedPlottables() const; - QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasPlottable(QCPAbstractPlottable *plottable) const; - - // specialized interface for QCPGraph: - QCPGraph *graph(int index) const; - QCPGraph *graph() const; - QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); - bool removeGraph(QCPGraph *graph); - bool removeGraph(int index); - int clearGraphs(); - int graphCount() const; - QList selectedGraphs() const; - - // item interface: - QCPAbstractItem *item(int index) const; - QCPAbstractItem *item() const; - bool addItem(QCPAbstractItem* item); - bool removeItem(QCPAbstractItem *item); - bool removeItem(int index); - int clearItems(); - int itemCount() const; - QList selectedItems() const; - QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasItem(QCPAbstractItem *item) const; - - // layer interface: - QCPLayer *layer(const QString &name) const; - QCPLayer *layer(int index) const; - QCPLayer *currentLayer() const; - bool setCurrentLayer(const QString &name); - bool setCurrentLayer(QCPLayer *layer); - int layerCount() const; - bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); - bool removeLayer(QCPLayer *layer); - bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); - - // axis rect/layout interface: - int axisRectCount() const; - QCPAxisRect* axisRect(int index=0) const; - QList axisRects() const; - QCPLayoutElement* layoutElementAt(const QPointF &pos) const; - Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); - - QList selectedAxes() const; - QList selectedLegends() const; - Q_SLOT void deselectAll(); - - bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); - bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); - bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); - bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); - bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); - QPixmap toPixmap(int width=0, int height=0, double scale=1.0); - void toPainter(QCPPainter *painter, int width=0, int height=0); - Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); - - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - QCPLegend *legend; - -signals: - void mouseDoubleClick(QMouseEvent *event); - void mousePress(QMouseEvent *event); - void mouseMove(QMouseEvent *event); - void mouseRelease(QMouseEvent *event); - void mouseWheel(QWheelEvent *event); - - void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); - void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); - void itemClick(QCPAbstractItem *item, QMouseEvent *event); - void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); - void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); - void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); - void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); - void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); - void titleClick(QMouseEvent *event, QCPPlotTitle *title); - void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); - - void selectionChangedByUser(); - void beforeReplot(); - void afterReplot(); - -protected: - // property members: - QRect mViewport; - QCPLayoutGrid *mPlotLayout; - bool mAutoAddPlottableToLegend; - QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph - QList mItems; - QList mLayers; - QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; - QCP::Interactions mInteractions; - int mSelectionTolerance; - bool mNoAntialiasingOnDrag; - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; - QCP::PlottingHints mPlottingHints; - Qt::KeyboardModifier mMultiSelectModifier; - - // non-property members: - QPixmap mPaintBuffer; - QPoint mMousePressPos; - QPointer mMouseEventElement; - bool mReplotting; - - // reimplemented virtual methods: - virtual QSize minimumSizeHint() const; - virtual QSize sizeHint() const; - virtual void paintEvent(QPaintEvent *event); - virtual void resizeEvent(QResizeEvent *event); - virtual void mouseDoubleClickEvent(QMouseEvent *event); - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); - - // introduced virtual methods: - virtual void draw(QCPPainter *painter); - virtual void axisRemoved(QCPAxis *axis); - virtual void legendRemoved(QCPLegend *legend); - - // non-virtual methods: - void updateLayerIndices() const; - QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; - void drawBackground(QCPPainter *painter); - - friend class QCPLegend; - friend class QCPAxis; - friend class QCPLayer; - friend class QCPAxisRect; -}; - - -class QCP_LIB_DECL QCPColorGradient -{ - Q_GADGET -public: - /*! - Defines the color spaces in which color interpolation between gradient stops can be performed. - - \see setColorInterpolation - */ - enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated - ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) - }; - Q_ENUMS(ColorInterpolation) - - /*! - Defines the available presets that can be loaded with \ref loadPreset. See the documentation - there for an image of the presets. - */ - enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) - ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) - ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) - ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) - ,gpCandy ///< Blue over pink to white - ,gpGeography ///< Colors suitable to represent different elevations on geographical maps - ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) - ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white - ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values - ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) - ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) - ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) - }; - Q_ENUMS(GradientPreset) - - QCPColorGradient(GradientPreset preset=gpCold); - bool operator==(const QCPColorGradient &other) const; - bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } - - // getters: - int levelCount() const { return mLevelCount; } - QMap colorStops() const { return mColorStops; } - ColorInterpolation colorInterpolation() const { return mColorInterpolation; } - bool periodic() const { return mPeriodic; } - - // setters: - void setLevelCount(int n); - void setColorStops(const QMap &colorStops); - void setColorStopAt(double position, const QColor &color); - void setColorInterpolation(ColorInterpolation interpolation); - void setPeriodic(bool enabled); - - // non-property methods: - void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); - QRgb color(double position, const QCPRange &range, bool logarithmic=false); - void loadPreset(GradientPreset preset); - void clearColorStops(); - QCPColorGradient inverted() const; - -protected: - void updateColorBuffer(); - - // property members: - int mLevelCount; - QMap mColorStops; - ColorInterpolation mColorInterpolation; - bool mPeriodic; - - // non-property members: - QVector mColorBuffer; - bool mColorBufferInvalidated; -}; - - -class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond -public: - explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); - virtual ~QCPAxisRect(); - - // getters: - QPixmap background() const { return mBackgroundPixmap; } - bool backgroundScaled() const { return mBackgroundScaled; } - Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } - Qt::Orientations rangeDrag() const { return mRangeDrag; } - Qt::Orientations rangeZoom() const { return mRangeZoom; } - QCPAxis *rangeDragAxis(Qt::Orientation orientation); - QCPAxis *rangeZoomAxis(Qt::Orientation orientation); - double rangeZoomFactor(Qt::Orientation orientation); - - // setters: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setRangeDrag(Qt::Orientations orientations); - void setRangeZoom(Qt::Orientations orientations); - void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); - void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); - void setRangeZoomFactor(double horizontalFactor, double verticalFactor); - void setRangeZoomFactor(double factor); - - // non-property methods: - int axisCount(QCPAxis::AxisType type) const; - QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; - QList axes(QCPAxis::AxisTypes types) const; - QList axes() const; - QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0); - QList addAxes(QCPAxis::AxisTypes types); - bool removeAxis(QCPAxis *axis); - QCPLayoutInset *insetLayout() const { return mInsetLayout; } - - void setupFullAxesBox(bool connectRanges=false); - QList plottables() const; - QList graphs() const; - QList items() const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPoint center() const { return mRect.center(); } - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; - -protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - Qt::Orientations mRangeDrag, mRangeZoom; - QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; - double mRangeZoomFactorHorz, mRangeZoomFactorVert; - // non-property members: - QCPRange mDragStartHorzRange, mDragStartVertRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - QPoint mDragStart; - bool mDragging; - QHash > mAxes; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual int calculateAutoMargin(QCP::MarginSide side); - // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); - - // non-property methods: - void drawBackground(QCPPainter *painter); - void updateAxesOffset(QCPAxis::AxisType type); - -private: - Q_DISABLE_COPY(QCPAxisRect) - - friend class QCustomPlot; -}; - - -class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) - /// \endcond -public: - explicit QCPAbstractLegendItem(QCPLegend *parent); - - // getters: - QCPLegend *parentLegend() const { return mParentLegend; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - -protected: - // property members: - QCPLegend *mParentLegend; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual QCP::Interaction selectionCategory() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 0; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - -private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - - friend class QCPLegend; -}; - - -class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem -{ - Q_OBJECT -public: - QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); - - // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - -protected: - // property members: - QCPAbstractPlottable *mPlottable; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QSize minimumSizeHint() const; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; -}; - - -class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) - Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) - Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) - Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) - Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - /// \endcond -public: - /*! - Defines the selectable parts of a legend - - \see setSelectedParts, setSelectableParts - */ - enum SelectablePart { spNone = 0x000 ///< 0x000 None - ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) - ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) - }; - Q_FLAGS(SelectablePart SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPLegend(); - virtual ~QCPLegend(); - - // getters: - QPen borderPen() const { return mBorderPen; } - QBrush brush() const { return mBrush; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QSize iconSize() const { return mIconSize; } - int iconTextPadding() const { return mIconTextPadding; } - QPen iconBorderPen() const { return mIconBorderPen; } - SelectableParts selectableParts() const { return mSelectableParts; } - SelectableParts selectedParts() const; - QPen selectedBorderPen() const { return mSelectedBorderPen; } - QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - - // setters: - void setBorderPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setIconSize(const QSize &size); - void setIconSize(int width, int height); - void setIconTextPadding(int padding); - void setIconBorderPen(const QPen &pen); - Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); - void setSelectedBorderPen(const QPen &pen); - void setSelectedIconBorderPen(const QPen &pen); - void setSelectedBrush(const QBrush &brush); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-virtual methods: - QCPAbstractLegendItem *item(int index) const; - QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; - int itemCount() const; - bool hasItem(QCPAbstractLegendItem *item) const; - bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; - bool addItem(QCPAbstractLegendItem *item); - bool removeItem(int index); - bool removeItem(QCPAbstractLegendItem *item); - void clearItems(); - QList selectedItems() const; - -signals: - void selectionChanged(QCPLegend::SelectableParts parts); - void selectableChanged(QCPLegend::SelectableParts parts); - -protected: - // property members: - QPen mBorderPen, mIconBorderPen; - QBrush mBrush; - QFont mFont; - QColor mTextColor; - QSize mIconSize; - int mIconTextPadding; - SelectableParts mSelectedParts, mSelectableParts; - QPen mSelectedBorderPen, mSelectedIconBorderPen; - QBrush mSelectedBrush; - QFont mSelectedFont; - QColor mSelectedTextColor; - - // reimplemented virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - QPen getBorderPen() const; - QBrush getBrush() const; - -private: - Q_DISABLE_COPY(QCPLegend) - - friend class QCustomPlot; - friend class QCPAbstractLegendItem; -}; -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) -Q_DECLARE_METATYPE(QCPLegend::SelectablePart) - - -class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond -public: - explicit QCPPlotTitle(QCustomPlot *parentPlot); - explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); - - // getters: - QString text() const { return mText; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setText(const QString &text); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - -protected: - // property members: - QString mText; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - QRect mTextBoundingRect; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - QFont mainFont() const; - QColor mainTextColor() const; - -private: - Q_DISABLE_COPY(QCPPlotTitle) -}; - - -class QCPColorScaleAxisRectPrivate : public QCPAxisRect -{ - Q_OBJECT -public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); -protected: - QCPColorScale *mParentColorScale; - QImage mGradientImage; - bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale - using QCPAxisRect::calculateAutoMargin; - using QCPAxisRect::mousePressEvent; - using QCPAxisRect::mouseMoveEvent; - using QCPAxisRect::mouseReleaseEvent; - using QCPAxisRect::wheelEvent; - using QCPAxisRect::update; - virtual void draw(QCPPainter *painter); - void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); - friend class QCPColorScale; -}; - - -class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) - Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond -public: - explicit QCPColorScale(QCustomPlot *parentPlot); - virtual ~QCPColorScale(); - - // getters: - QCPAxis *axis() const { return mColorAxis.data(); } - QCPAxis::AxisType type() const { return mType; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - QCPColorGradient gradient() const { return mGradient; } - QString label() const; - int barWidth () const { return mBarWidth; } - bool rangeDrag() const; - bool rangeZoom() const; - - // setters: - void setType(QCPAxis::AxisType type); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setLabel(const QString &str); - void setBarWidth(int width); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - - // non-property methods: - QList colorMaps() const; - void rescaleDataRange(bool onlyVisibleMaps); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - -signals: - void dataRangeChanged(QCPRange newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); - -protected: - // property members: - QCPAxis::AxisType mType; - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorGradient mGradient; - int mBarWidth; - - // non-property members: - QPointer mAxisRect; - QPointer mColorAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); - -private: - Q_DISABLE_COPY(QCPColorScale) - - friend class QCPColorScaleAxisRectPrivate; -}; - - -/*! \file */ - - - -class QCP_LIB_DECL QCPData -{ -public: - QCPData(); - QCPData(double key, double value); - double key, value; - double keyErrorPlus, keyErrorMinus; - double valueErrorPlus, valueErrorMinus; -}; -Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); - -/*! \typedef QCPDataMap - Container for storing \ref QCPData items in a sorted fashion. The key of the map - is the key member of the QCPData instance. - - This is the container in which QCPGraph holds its data. - \see QCPData, QCPGraph::setData -*/ -typedef QMap QCPDataMap; -typedef QMapIterator QCPDataMapIterator; -typedef QMutableMapIterator QCPDataMutableMapIterator; - - -class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) - Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) - Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) - Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) - Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) - Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) - Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) - Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) - /// \endcond -public: - /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the - current pen of the graph (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point - ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point - ,lsStepCenter ///< line is drawn as steps where the step is in between two data points - ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line - }; - Q_ENUMS(LineStyle) - /*! - Defines what kind of error bars are drawn for each data point - */ - enum ErrorType { etNone ///< No error bars are shown - ,etKey ///< Error bars for the key dimension of the data point are shown - ,etValue ///< Error bars for the value dimension of the data point are shown - ,etBoth ///< Error bars for both key and value dimensions of the data point are shown - }; - Q_ENUMS(ErrorType) - - explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPGraph(); - - // getters: - QCPDataMap *data() const { return mData; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - ErrorType errorType() const { return mErrorType; } - QPen errorPen() const { return mErrorPen; } - double errorBarSize() const { return mErrorBarSize; } - bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } - QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } - bool adaptiveSampling() const { return mAdaptiveSampling; } - - // setters: - void setData(QCPDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &value); - void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); - void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); - void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); - void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); - void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); - void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); - void setLineStyle(LineStyle ls); - void setScatterStyle(const QCPScatterStyle &style); - void setErrorType(ErrorType errorType); - void setErrorPen(const QPen &pen); - void setErrorBarSize(double size); - void setErrorBarSkipSymbol(bool enabled); - void setChannelFillGraph(QCPGraph *targetGraph); - void setAdaptiveSampling(bool enabled); - - // non-property methods: - void addData(const QCPDataMap &dataMap); - void addData(const QCPData &data); - void addData(double key, double value); - void addData(const QVector &keys, const QVector &values); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); - - // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - using QCPAbstractPlottable::rescaleAxes; - using QCPAbstractPlottable::rescaleKeyAxis; - using QCPAbstractPlottable::rescaleValueAxis; - void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface - void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface - void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface - -protected: - // property members: - QCPDataMap *mData; - QPen mErrorPen; - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - ErrorType mErrorType; - double mErrorBarSize; - bool mErrorBarSkipSymbol; - QPointer mChannelFillGraph; - bool mAdaptiveSampling; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface - - // introduced virtual methods: - virtual void drawFill(QCPPainter *painter, QVector *lineData) const; - virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; - virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; - virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; - - // non-virtual methods: - void getPreparedData(QVector *lineData, QVector *scatterData) const; - void getPlotData(QVector *lineData, QVector *scatterData) const; - void getScatterPlotData(QVector *scatterData) const; - void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; - void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; - void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; - void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; - int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; - void addFillBasePoints(QVector *lineData) const; - void removeFillBasePoints(QVector *lineData) const; - QPointF lowerFillBasePoint(double lowerKey) const; - QPointF upperFillBasePoint(double upperKey) const; - const QPolygonF getChannelFillPolygon(const QVector *lineData) const; - int findIndexBelowX(const QVector *data, double x) const; - int findIndexAboveX(const QVector *data, double x) const; - int findIndexBelowY(const QVector *data, double y) const; - int findIndexAboveY(const QVector *data, double y) const; - double pointDistance(const QPointF &pixelPoint) const; - - friend class QCustomPlot; - friend class QCPLegend; -}; - - -/*! \file */ - - - -class QCP_LIB_DECL QCPCurveData -{ -public: - QCPCurveData(); - QCPCurveData(double t, double key, double value); - double t, key, value; -}; -Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); - -/*! \typedef QCPCurveDataMap - Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map - is the t member of the QCPCurveData instance. - - This is the container in which QCPCurve holds its data. - \see QCPCurveData, QCPCurve::setData -*/ - -typedef QMap QCPCurveDataMap; -typedef QMapIterator QCPCurveDataMapIterator; -typedef QMutableMapIterator QCPCurveDataMutableMapIterator; - - -class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) - Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) - /// \endcond -public: - /*! - Defines how the curve's line is represented visually in the plot. The line is drawn with the - current pen of the curve (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) - ,lsLine ///< Data points are connected with a straight line - }; - explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPCurve(); - - // getters: - QCPCurveDataMap *data() const { return mData; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - LineStyle lineStyle() const { return mLineStyle; } - - // setters: - void setData(QCPCurveDataMap *data, bool copy=false); - void setData(const QVector &t, const QVector &key, const QVector &value); - void setData(const QVector &key, const QVector &value); - void setScatterStyle(const QCPScatterStyle &style); - void setLineStyle(LineStyle style); - - // non-property methods: - void addData(const QCPCurveDataMap &dataMap); - void addData(const QCPCurveData &data); - void addData(double t, double key, double value); - void addData(double key, double value); - void addData(const QVector &ts, const QVector &keys, const QVector &values); - void removeDataBefore(double t); - void removeDataAfter(double t); - void removeData(double fromt, double tot); - void removeData(double t); - - // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -protected: - // property members: - QCPCurveDataMap *mData; - QCPScatterStyle mScatterStyle; - LineStyle mLineStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - - // introduced virtual methods: - virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; - - // non-virtual methods: - void getCurveData(QVector *lineData) const; - int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const; - QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; - QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; - bool mayTraverse(int prevRegion, int currentRegion) const; - bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const; - void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const; - double pointDistance(const QPointF &pixelPoint) const; - - friend class QCustomPlot; - friend class QCPLegend; -}; - - -/*! \file */ - - - -class QCP_LIB_DECL QCPBarsGroup : public QObject -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) - Q_PROPERTY(double spacing READ spacing WRITE setSpacing) - /// \endcond -public: - /*! - Defines the ways the spacing between bars in the group can be specified. Thus it defines what - the number passed to \ref setSpacing actually means. - - \see setSpacingType, setSpacing - */ - enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels - ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size - ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range - }; - QCPBarsGroup(QCustomPlot *parentPlot); - ~QCPBarsGroup(); - - // getters: - SpacingType spacingType() const { return mSpacingType; } - double spacing() const { return mSpacing; } - - // setters: - void setSpacingType(SpacingType spacingType); - void setSpacing(double spacing); - - // non-virtual methods: - QList bars() const { return mBars; } - QCPBars* bars(int index) const; - int size() const { return mBars.size(); } - bool isEmpty() const { return mBars.isEmpty(); } - void clear(); - bool contains(QCPBars *bars) const { return mBars.contains(bars); } - void append(QCPBars *bars); - void insert(int i, QCPBars *bars); - void remove(QCPBars *bars); - -protected: - // non-property members: - QCustomPlot *mParentPlot; - SpacingType mSpacingType; - double mSpacing; - QList mBars; - - // non-virtual methods: - void registerBars(QCPBars *bars); - void unregisterBars(QCPBars *bars); - - // virtual methods: - double keyPixelOffset(const QCPBars *bars, double keyCoord); - double getPixelSpacing(const QCPBars *bars, double keyCoord); - -private: - Q_DISABLE_COPY(QCPBarsGroup) - - friend class QCPBars; -}; - - -class QCP_LIB_DECL QCPBarData -{ -public: - QCPBarData(); - QCPBarData(double key, double value); - double key, value; -}; -Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); - -/*! \typedef QCPBarDataMap - Container for storing \ref QCPBarData items in a sorted fashion. The key of the map - is the key member of the QCPBarData instance. - - This is the container in which QCPBars holds its data. - \see QCPBarData, QCPBars::setData -*/ -typedef QMap QCPBarDataMap; -typedef QMapIterator QCPBarDataMapIterator; -typedef QMutableMapIterator QCPBarDataMutableMapIterator; - - -class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double width READ width WRITE setWidth) - Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) - Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) - Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) - Q_PROPERTY(QCPBars* barBelow READ barBelow) - Q_PROPERTY(QCPBars* barAbove READ barAbove) - /// \endcond -public: - /*! - Defines the ways the width of the bar can be specified. Thus it defines what the number passed - to \ref setWidth actually means. - - \see setWidthType, setWidth - */ - enum WidthType { wtAbsolute ///< Bar width is in absolute pixels - ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size - ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range - }; - Q_ENUMS(WidthType) - - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPBars(); - - // getters: - double width() const { return mWidth; } - WidthType widthType() const { return mWidthType; } - QCPBarsGroup *barsGroup() const { return mBarsGroup; } - double baseValue() const { return mBaseValue; } - QCPBars *barBelow() const { return mBarBelow.data(); } - QCPBars *barAbove() const { return mBarAbove.data(); } - QCPBarDataMap *data() const { return mData; } - - // setters: - void setWidth(double width); - void setWidthType(WidthType widthType); - void setBarsGroup(QCPBarsGroup *barsGroup); - void setBaseValue(double baseValue); - void setData(QCPBarDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &value); - - // non-property methods: - void moveBelow(QCPBars *bars); - void moveAbove(QCPBars *bars); - void addData(const QCPBarDataMap &dataMap); - void addData(const QCPBarData &data); - void addData(double key, double value); - void addData(const QVector &keys, const QVector &values); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); - - // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -protected: - // property members: - QCPBarDataMap *mData; - double mWidth; - WidthType mWidthType; - QCPBarsGroup *mBarsGroup; - double mBaseValue; - QPointer mBarBelow, mBarAbove; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - - // non-virtual methods: - void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; - QPolygonF getBarPolygon(double key, double value) const; - void getPixelWidth(double key, double &lower, double &upper) const; - double getStackedBaseValue(double key, bool positive) const; - static void connectBars(QCPBars* lower, QCPBars* upper); - - friend class QCustomPlot; - friend class QCPLegend; - friend class QCPBarsGroup; -}; - - -/*! \file */ - - - -class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double key READ key WRITE setKey) - Q_PROPERTY(double minimum READ minimum WRITE setMinimum) - Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) - Q_PROPERTY(double median READ median WRITE setMedian) - Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) - Q_PROPERTY(double maximum READ maximum WRITE setMaximum) - Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) - Q_PROPERTY(double width READ width WRITE setWidth) - Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) - Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) - Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) - Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) - Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) - /// \endcond -public: - explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // getters: - double key() const { return mKey; } - double minimum() const { return mMinimum; } - double lowerQuartile() const { return mLowerQuartile; } - double median() const { return mMedian; } - double upperQuartile() const { return mUpperQuartile; } - double maximum() const { return mMaximum; } - QVector outliers() const { return mOutliers; } - double width() const { return mWidth; } - double whiskerWidth() const { return mWhiskerWidth; } - QPen whiskerPen() const { return mWhiskerPen; } - QPen whiskerBarPen() const { return mWhiskerBarPen; } - QPen medianPen() const { return mMedianPen; } - QCPScatterStyle outlierStyle() const { return mOutlierStyle; } - - // setters: - void setKey(double key); - void setMinimum(double value); - void setLowerQuartile(double value); - void setMedian(double value); - void setUpperQuartile(double value); - void setMaximum(double value); - void setOutliers(const QVector &values); - void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); - void setWidth(double width); - void setWhiskerWidth(double width); - void setWhiskerPen(const QPen &pen); - void setWhiskerBarPen(const QPen &pen); - void setMedianPen(const QPen &pen); - void setOutlierStyle(const QCPScatterStyle &style); - - // non-property methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -protected: - // property members: - QVector mOutliers; - double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; - double mWidth; - double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; - QCPScatterStyle mOutlierStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - - // introduced virtual methods: - virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; - virtual void drawMedian(QCPPainter *painter) const; - virtual void drawWhiskers(QCPPainter *painter) const; - virtual void drawOutliers(QCPPainter *painter) const; - - friend class QCustomPlot; - friend class QCPLegend; -}; - - -class QCP_LIB_DECL QCPColorMapData -{ -public: - QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); - ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - - // getters: - int keySize() const { return mKeySize; } - int valueSize() const { return mValueSize; } - QCPRange keyRange() const { return mKeyRange; } - QCPRange valueRange() const { return mValueRange; } - QCPRange dataBounds() const { return mDataBounds; } - double data(double key, double value); - double cell(int keyIndex, int valueIndex); - - // setters: - void setSize(int keySize, int valueSize); - void setKeySize(int keySize); - void setValueSize(int valueSize); - void setRange(const QCPRange &keyRange, const QCPRange &valueRange); - void setKeyRange(const QCPRange &keyRange); - void setValueRange(const QCPRange &valueRange); - void setData(double key, double value, double z); - void setCell(int keyIndex, int valueIndex, double z); - - // non-property methods: - void recalculateDataBounds(); - void clear(); - void fill(double z); - bool isEmpty() const { return mIsEmpty; } - void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; - void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; - -protected: - // property members: - int mKeySize, mValueSize; - QCPRange mKeyRange, mValueRange; - bool mIsEmpty; - // non-property members: - double *mData; - QCPRange mDataBounds; - bool mDataModified; - - friend class QCPColorMap; -}; - - -class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) - Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) - Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) - /// \endcond -public: - explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPColorMap(); - - // getters: - QCPColorMapData *data() const { return mMapData; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - bool interpolate() const { return mInterpolate; } - bool tightBoundary() const { return mTightBoundary; } - QCPColorGradient gradient() const { return mGradient; } - QCPColorScale *colorScale() const { return mColorScale.data(); } - - // setters: - void setData(QCPColorMapData *data, bool copy=false); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setInterpolate(bool enabled); - void setTightBoundary(bool enabled); - void setColorScale(QCPColorScale *colorScale); - - // non-property methods: - void rescaleDataRange(bool recalculateDataBounds=false); - Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); - - // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -signals: - void dataRangeChanged(QCPRange newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); - -protected: - // property members: - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorMapData *mMapData; - QCPColorGradient mGradient; - bool mInterpolate; - bool mTightBoundary; - QPointer mColorScale; - // non-property members: - QImage mMapImage, mUndersampledMapImage; - QPixmap mLegendIcon; - bool mMapImageInvalidated; - - // introduced virtual methods: - virtual void updateMapImage(); - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - - friend class QCustomPlot; - friend class QCPLegend; -}; - - -/*! \file */ - - - -class QCP_LIB_DECL QCPFinancialData -{ -public: - QCPFinancialData(); - QCPFinancialData(double key, double open, double high, double low, double close); - double key, open, high, low, close; -}; -Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE); - -/*! \typedef QCPFinancialDataMap - Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map - is the key member of the QCPFinancialData instance. - - This is the container in which QCPFinancial holds its data. - \see QCPFinancial, QCPFinancial::setData -*/ -typedef QMap QCPFinancialDataMap; -typedef QMapIterator QCPFinancialDataMapIterator; -typedef QMutableMapIterator QCPFinancialDataMutableMapIterator; - - -class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) - Q_PROPERTY(double width READ width WRITE setWidth) - Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) - Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) - Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) - Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) - Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) - /// \endcond -public: - /*! - Defines the possible representations of OHLC data in the plot. - - \see setChartStyle - */ - enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation - ,csCandlestick ///< Candlestick representation - }; - Q_ENUMS(ChartStyle) - - explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPFinancial(); - - // getters: - QCPFinancialDataMap *data() const { return mData; } - ChartStyle chartStyle() const { return mChartStyle; } - double width() const { return mWidth; } - bool twoColored() const { return mTwoColored; } - QBrush brushPositive() const { return mBrushPositive; } - QBrush brushNegative() const { return mBrushNegative; } - QPen penPositive() const { return mPenPositive; } - QPen penNegative() const { return mPenNegative; } - - - // setters: - void setData(QCPFinancialDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); - void setChartStyle(ChartStyle style); - void setWidth(double width); - void setTwoColored(bool twoColored); - void setBrushPositive(const QBrush &brush); - void setBrushNegative(const QBrush &brush); - void setPenPositive(const QPen &pen); - void setPenNegative(const QPen &pen); - - // non-property methods: - void addData(const QCPFinancialDataMap &dataMap); - void addData(const QCPFinancialData &data); - void addData(double key, double open, double high, double low, double close); - void addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); - - // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // static methods: - static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - -protected: - // property members: - QCPFinancialDataMap *mData; - ChartStyle mChartStyle; - double mWidth; - bool mTwoColored; - QBrush mBrushPositive, mBrushNegative; - QPen mPenPositive, mPenNegative; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - - // non-virtual methods: - void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); - void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); - double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; - double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; - void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const; - - friend class QCustomPlot; - friend class QCPLegend; -}; - - -class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond -public: - QCPItemStraightLine(QCustomPlot *parentPlot); - virtual ~QCPItemStraightLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const point1; - QCPItemPosition * const point2; - -protected: - // property members: - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; - QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; - QPen mainPen() const; -}; - - -class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond -public: - QCPItemLine(QCustomPlot *parentPlot); - virtual ~QCPItemLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const start; - QCPItemPosition * const end; - -protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; - QPen mainPen() const; -}; - - -class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond -public: - QCPItemCurve(QCustomPlot *parentPlot); - virtual ~QCPItemCurve(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const start; - QCPItemPosition * const startDir; - QCPItemPosition * const endDir; - QCPItemPosition * const end; - -protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - QPen mainPen() const; -}; - - -class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - /// \endcond -public: - QCPItemRect(QCustomPlot *parentPlot); - virtual ~QCPItemRect(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - -protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; -}; - - -class QCP_LIB_DECL QCPItemText : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QColor color READ color WRITE setColor) - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) - Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) - Q_PROPERTY(double rotation READ rotation WRITE setRotation) - Q_PROPERTY(QMargins padding READ padding WRITE setPadding) - /// \endcond -public: - QCPItemText(QCustomPlot *parentPlot); - virtual ~QCPItemText(); - - // getters: - QColor color() const { return mColor; } - QColor selectedColor() const { return mSelectedColor; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont font() const { return mFont; } - QFont selectedFont() const { return mSelectedFont; } - QString text() const { return mText; } - Qt::Alignment positionAlignment() const { return mPositionAlignment; } - Qt::Alignment textAlignment() const { return mTextAlignment; } - double rotation() const { return mRotation; } - QMargins padding() const { return mPadding; } - - // setters; - void setColor(const QColor &color); - void setSelectedColor(const QColor &color); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setFont(const QFont &font); - void setSelectedFont(const QFont &font); - void setText(const QString &text); - void setPositionAlignment(Qt::Alignment alignment); - void setTextAlignment(Qt::Alignment alignment); - void setRotation(double degrees); - void setPadding(const QMargins &padding); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const position; - QCPItemAnchor * const topLeft; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRight; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - -protected: - enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QColor mColor, mSelectedColor; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QFont mFont, mSelectedFont; - QString mText; - Qt::Alignment mPositionAlignment; - Qt::Alignment mTextAlignment; - double mRotation; - QMargins mPadding; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; - QFont mainFont() const; - QColor mainColor() const; - QPen mainPen() const; - QBrush mainBrush() const; -}; - - -class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - /// \endcond -public: - QCPItemEllipse(QCustomPlot *parentPlot); - virtual ~QCPItemEllipse(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const topLeftRim; - QCPItemAnchor * const top; - QCPItemAnchor * const topRightRim; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRightRim; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeftRim; - QCPItemAnchor * const left; - QCPItemAnchor * const center; - -protected: - enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; -}; - - -class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool scaled READ scaled WRITE setScaled) - Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) - Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond -public: - QCPItemPixmap(QCustomPlot *parentPlot); - virtual ~QCPItemPixmap(); - - // getters: - QPixmap pixmap() const { return mPixmap; } - bool scaled() const { return mScaled; } - Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } - Qt::TransformationMode transformationMode() const { return mTransformationMode; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPixmap(const QPixmap &pixmap); - void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - -protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPixmap mPixmap; - QPixmap mScaledPixmap; - bool mScaled; - bool mScaledPixmapInvalidated; - Qt::AspectRatioMode mAspectRatioMode; - Qt::TransformationMode mTransformationMode; - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); - QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; - QPen mainPen() const; -}; - - -class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(double size READ size WRITE setSize) - Q_PROPERTY(TracerStyle style READ style WRITE setStyle) - Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) - Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) - Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) - /// \endcond -public: - /*! - The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - - \see setStyle - */ - enum TracerStyle { tsNone ///< The tracer is not visible - ,tsPlus ///< A plus shaped crosshair with limited size - ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect - ,tsCircle ///< A circle - ,tsSquare ///< A square - }; - Q_ENUMS(TracerStyle) - - QCPItemTracer(QCustomPlot *parentPlot); - virtual ~QCPItemTracer(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - double size() const { return mSize; } - TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } - double graphKey() const { return mGraphKey; } - bool interpolating() const { return mInterpolating; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setSize(double size); - void setStyle(TracerStyle style); - void setGraph(QCPGraph *graph); - void setGraphKey(double key); - void setInterpolating(bool enabled); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-virtual methods: - void updatePosition(); - - QCPItemPosition * const position; - -protected: - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - double mSize; - TracerStyle mStyle; - QCPGraph *mGraph; - double mGraphKey; - bool mInterpolating; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; -}; - - -class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem -{ - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(double length READ length WRITE setLength) - Q_PROPERTY(BracketStyle style READ style WRITE setStyle) - /// \endcond -public: - enum BracketStyle { bsSquare ///< A brace with angled edges - ,bsRound ///< A brace with round edges - ,bsCurly ///< A curly brace - ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression - }; - - QCPItemBracket(QCustomPlot *parentPlot); - virtual ~QCPItemBracket(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - double length() const { return mLength; } - BracketStyle style() const { return mStyle; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setLength(double length); - void setStyle(BracketStyle style); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const left; - QCPItemPosition * const right; - QCPItemAnchor * const center; - -protected: - // property members: - enum AnchorIndex {aiCenter}; - QPen mPen, mSelectedPen; - double mLength; - BracketStyle mStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; -}; - -#endif // QCUSTOMPLOT_H - diff --git a/lib/QCustomPlot/changelog.txt b/lib/QCustomPlot/changelog.txt deleted file mode 100644 index 15096be..0000000 --- a/lib/QCustomPlot/changelog.txt +++ /dev/null @@ -1,432 +0,0 @@ -#### Version 1.3.2 released on 22.12.15 #### - - Bugfixes [Backported from 2.0.0 branch]: - - Fixed possible crash when having a QCPGraph with scatters only and a non-transparent main/fill brush of the graph - - Fixed QCPItemPixmap not updating internally cached scaled pixmap if new pixmap set with same scaled dimensions - - When using log axis scale and zooming out as far as possible (~1e-280..1e280), axis doesn't end up in (via mouse) unrecoverable range with strange axis ticks anymore - - Axis tick label algorithm for beautifully typeset powers now checks whether "e" in tick label is actually part of a number before converting the exponent to superscript - - Fixed QCustomPlot::moveLayer performing incorrect move and possible crash in certain situations - - Fixed possible crash on QCustomPlot destruction due to wrong QObject-hierarchy. Only occurs if a QCPAxisRect is removed from the normal QCustomPlot destruction hierarchy by taking it out of its layout - - Fixed possible freeze when data values become infinity after coord-to-pixel transformation (e.g. maximally zoomed out log axis), and line style is not solid (e.g. dashed) or phFastPolylines is disabled - - Other [Backported from 2.0.0 branch]: - - A few documentation fixes/improvements - - Qt5.5 compatibility (If you use PDF export, test your outputs, as output dimensions might change when switching Qt versions -- QCP does not try to emulate previous Qt version behaviour here) - - QCP now includes instead of just because some users had problems with the latter. Please report if you now experience issues due to the new include. - -#### Version 1.3.1 released on 25.04.15 #### - - Bugfixes: - - Fixed bug that prevented automatic axis rescaling when some graphs/curves had only NaN data points - - Improved QCPItemBracket selection boundaries, especially bsCurly and bsCalligraphic - - Fixed bug of axis rect and colorscale background shifted downward by one logical pixel (visible in scaled png and pdf export) - - Replot upon mouse release is now only performed if a selection change has actually happened (improves responsivity on particularly complex plots) - - Fixed bug that allowed scatter-only graphs to be selected by clicking the non-existent line between scatters - - Fixed crash when trying to select a scatter-only QCPGraph whose only points in the visible key range are at identical key coordinates and vertically off-screen, with adaptive sampling enabled - - Fixed pdf export of QCPColorMap with enabled interpolation (didn't appear interpolated in pdf) - - Reduced QCPColorMap jitter of internal cell boundaries for small sized maps when viewed with high zoom, by applying oversampling factors dependant on map size - - Fixed bug of QCPColorMap::fill() not causing the buffered internal image map to be updated, and thus the change didn't become visible immediately - - Axis labels with size set in pixels (setPixelSize) instead of points now correctly calculate the exponent's font size if beautifully typeset powers are enabled - - Fixed QCPColorMap appearing at the wrong position for logarithmic axes and color map spanning larger ranges - - Other: - - Pdf export used to embed entire QCPColorMaps, potentially leading to large files. Now only the visible portion of the map is embedded in the pdf - - Many documentation fixes and extensions, style modernization - - Reduced documentation file size (and thus full package size) by automatically reducing image palettes during package build - - Fixed MSVC warning message (at warning level 4) due to temporary QLists in some foreach statements - -#### Version 1.3.0 released on 27.12.14 #### - - Added features: - - New plottable class QCPFinancial allows display of candlestick/ohlc data - - New class QCPBarsGroup allows horizontal grouping of multiple QCPBars plottables - - Added QCPBars feature allowing non-zero base values (see property QCPBars::setBaseValue) - - Added QCPBars width type, for more flexible bar widths (see property QCPBars::setWidthType) - - New QCPCurve optimization algorithm, fixes bug which caused line flicker at deep zoom into curve segment - - Item positions can now have different position types and anchors for their x and y coordinates (QCPItemPosition::setTypeX/Y, setParentAnchorX/Y) - - QCPGraph and QCPCurve can now display gaps in their lines, when inserting quiet NaNs as values (std::numeric_limits::quiet_NaN()) - - QCPAxis now supports placing the tick labels inside the axis rect, for particularly space saving plots (QCPAxis::setTickLabelSide) - Added features after beta: - - Made code compatible with QT_NO_CAST_FROM_ASCII, QT_NO_CAST_TO_ASCII - - Added compatibility with QT_NO_KEYWORDS after sending code files through a simple reg-ex script - - Added possibility to inject own QCPAxis(-subclasses) via second, optional QCPAxisRect::addAxis parameter - - Added parameter to QCPItemPixmap::setScaled to specify transformation mode - - Bugfixes: - - Fixed bug in QCPCurve rendering of very zoomed-in curves (via new optimization algorithm) - - Fixed conflict with MSVC-specific keyword "interface" in text-document-integration example - - Fixed QCPScatterStyle bug ignoring the specified pen in the custom scatter shape constructor - - Fixed bug (possible crash) during QCustomPlot teardown, when a QCPLegend that has no parent layout (i.e. was removed from layout manually) gets deleted - Bugfixes after beta: - - Fixed bug of QCPColorMap/QCPColorGradient colors being off by one color sampling step (only noticeable in special cases) - - Fixed bug of QCPGraph adaptive sampling on vertical key axis, causing staggered look - - Fixed low (float) precision in QCPCurve optimization algorithm, by not using QVector2D anymore - - Other: - - Qt 5.3 and Qt 5.4 compatibility - -#### Version 1.2.1 released on 07.04.14 #### - - Bugfixes: - - Fixed regression which garbled date-time tick labels on axes, if setTickLabelType is ltDateTime and setNumberFormat contains the "b" option - -#### Version 1.2.0 released on 14.03.14 #### - - Added features: - - Adaptive Sampling for QCPGraph greatly improves performance for high data densities (see QCPGraph::setAdaptiveSampling) - - QCPColorMap plottable with QCPColorScale layout element allows plotting of 2D color maps - - QCustomPlot::savePdf now has additional optional parameters pdfCreator and pdfTitle to set according PDF metadata fields - - QCustomPlot::replot now allows specifying whether the widget update is immediate (repaint) or queued (update) - - QCPRange operators +, -, *, / with double operand for range shifting and scaling, and ==, != for range comparison - - Layers now have a visibility property (QCPLayer::setVisible) - - static functions QCPAxis::opposite and QCPAxis::orientation now offer more convenience when handling axis types - - added notification signals for selectability change (selectableChanged) on all objects that have a selected/selectable property - - added notification signal for QCPAxis scaleType property - - added notification signal QCPLayerable::layerChanged - - Bugfixes: - - Fixed assert halt, when QCPAxis auto tick labels not disabled but nevertheless a custom non-number tick label ending in "e" given - - Fixed painting glitches when QCustomPlot resized inside a QMdiArea or under certain conditions inside a QLayout - - If changing QCPAxis::scaleType and thus causing range sanitizing and a range modification, rangeChanged wouldn't be emitted - - Fixed documentation bug that caused indentation to be lost in code examples - Bugfixes after beta: - - Fixed bug that caused crash if clicked-on legend item is removed in mousePressEvent. - - On some systems, font size defaults to -1, which used to cause a debug output in QCPAxisPainterPrivate::TickLabelDataQCP. Now it's checked before setting values based on the default font size. - - When using multiple axes on one side, setting one to invisible didn't properly compress the freed space. - - Fixed bug that allowed selection of plottables when clicking in the bottom or top margin of a QCPAxisRect (outside the inner rect) - - Other: - - In method QCPAbstractPlottable::getKeyRange/getValueRange, renamed parameter "validRange" to "foundRange", to better reflect its meaning (and contrast it from QCPRange::validRange) - - QCPAxis low-level axis painting methods exported to QCPAxisPainterPrivate - -#### Version 1.1.1 released on 09.12.13 #### - - Bugfixes: - - Fixed bug causing legends blocking input events from reaching underlying axis rect even if legend is invisible - - Added missing Q_PROPERTY for QCPAxis::setDateTimeSpec - - Fixed behaviour of QCPAxisRect::setupFullAxesBox (now transfers more properties from bottom/left to top/right axes and sets visibility of bottom/left axes to true) - - Made sure PDF export doesn't default to grayscale output on some systems - - Other: - - Plotting hint QCP::phForceRepaint is now enabled on all systems (and not only on windows) by default - - Documentation improvements - -#### Version 1.1.0 released on 04.11.13 #### - - Added features: - - Added QCPRange::expand and QCPRange::expanded - - Added QCPAxis::rescale to rescale axis to all associated plottables - - Added QCPAxis::setDateTimeSpec/dateTimeSpec to allow axis labels either in UTC or local time - - QCPAxis now additionally emits a rangeChanged signal overload that provides the old range as second parameter - - Bugfixes: - - Fixed QCustomPlot::rescaleAxes not rescaling properly if first plottable has an empty range - - QCPGraph::rescaleAxes/rescaleKeyAxis/rescaleValueAxis are no longer virtual (never were in base class, was a mistake) - - Fixed bugs in QCPAxis::items and QCPAxisRect::items not properly returning associated items and potentially stalling - - Other: - - Internal change from QWeakPointer to QPointer, thus got rid of deprecated Qt functionality - - Qt5.1 and Qt5.2 (beta1) compatibility - - Release packages now extract to single subdirectory and don't place multiple files in current working directory - -#### Version 1.0.1 released on 05.09.13 #### - - Bugfixes: - - using define flag QCUSTOMPLOT_CHECK_DATA caused debug output when data was correct, instead of invalid (fixed QCP::isInvalidData) - - documentation images are now properly shown when viewed with Qt Assistant - - fixed various documentation mistakes - - Other: - - Adapted documentation style sheet to better match Qt5 documentation - -#### Version 1.0.0 released on 01.08.13 #### - - Quick Summary: - - Layout system for multiple axis rects in one plot - - Multiple axes per side - - Qt5 compatibility - - More flexible and consistent scatter configuration with QCPScatterStyle - - Various interface cleanups/refactoring - - Pixmap-cached axis labels for improved replot performance - - Changes that break backward compatibility: - - QCustomPlot::axisRect() changed meaning due to the extensive changes to how axes and axis rects are handled - it now returns a pointer to a QCPAxisRect and takes an integer index as parameter. - - QCPAxis constructor changed to now take QCPAxisRect* as parent - - setAutoMargin, setMarginLeft/Right/Top/Bottom removed due to the axis rect changes (see QCPAxisRect::setMargins/setAutoMargins) - - setAxisRect removed due to the axis rect changes - - setAxisBackground(-Scaled/-ScaledMode) now moved to QCPAxisRect as setBackground(-Scaled/ScaledMode) (access via QCustomPlot::axisRects()) - - QCPLegend now is a QCPLayoutElement - - QCPAbstractPlottable::drawLegendIcon parameter "rect" changed from QRect to QRectF - - QCPAbstractLegendItem::draw second parameter removed (position/size now handled via QCPLayoutElement base class) - - removed QCPLegend::setMargin/setMarginLeft/Right/Top/Bottom (now inherits the capability from QCPLayoutElement::setMargins) - - removed QCPLegend::setMinimumSize (now inherits the capability from QCPLayoutElement::setMinimumSize) - - removed enum QCPLegend::PositionStyle, QCPLegend::positionStyle/setPositionStyle/position/setPosition (replaced by capabilities of QCPLayoutInset) - - QCPLegend transformed to work with new layout system (almost everything changed) - - removed entire title interface: QCustomPlot::setTitle/setTitleFont/setTitleColor/setTitleSelected/setTitleSelectedFont/setTitleSelectedColor and - the QCustomPlot::iSelectTitle interaction flag (all functionality is now given by the layout element "QCPPlotTitle" which can be added to the plot layout) - - selectTest functions now take two additional parameters: bool onlySelectable and QVariant *details=0 - - selectTest functions now ignores visibility of objects and (if parameter onlySelectable is true) does not anymore ignore selectability of the object - - moved QCustomPlot::Interaction/Interactions to QCP namespace as QCP::Interaction/Interactions - - moved QCustomPlot::setupFullAxesBox() to QCPAxisRect::setupFullAxesBox. Now also accepts parameter to decide whether to connect opposite axis ranges - - moved range dragging/zooming interface from QCustomPlot to QCPAxisRect (setRangeDrag, setRangeZoom, setRangeDragAxes, setRangeZoomAxes,...) - - rangeDrag/Zoom is now set to Qt::Horizontal|Qt::Vertical instead of 0 by default, on the other hand, iRangeDrag/Zoom is unset in interactions by - default (this makes enabling dragging/zooming easier by just adding the interaction flags) - - QCPScatterStyle takes over everything related to handling scatters in all plottables - - removed setScatterPen/Size on QCPGraph and QCPCurve, removed setOutlierPen/Size on QCPStatisticalBox (now handled via QCPScatterStyle) - - modified setScatterStyle on QCPGraph and QCPCurve, and setOutlierStyle on QCPStatisticalBox, to take QCPScatterStyle - - axis grid and subgrid are now reachable via the QCPGrid *QCPAxis::grid() method. (e.g. instead of xAxis->setGrid(true), write xAxis->grid()->setVisible(true)) - - Added features: - - Axis tick labels are now pixmap-cached, thus increasing replot performance (in usual setups by about 24%). See plotting hint phCacheLabels which is set by default - - Advanced layout system, including the classes QCPLayoutElement, QCPLayout, QCPLayoutGrid, QCPLayoutInset, QCPAxisRect - - QCustomPlot::axisRects() returns all the axis rects in the QCustomPlot. - - QCustomPlot::plotLayout() returns the top level layout (initially a QCPLayoutGrid with one QCPAxisRect inside) - - QCPAxis now may have an offset to the axis rect (setOffset) - - Multiple axes per QCPAxisRect side are now supported (see QCPAxisRect::addAxis) - - QCustomPlot::toPixmap renders the plot into a pixmap and returns it - - When setting tick label rotation to +90 or -90 degrees on a vertical axis, the labels are now centered vertically on the tick height - (This allows space saving vertical tick labels by having the text direction parallel to the axis) - - Substantially increased replot performance when using very large manual tick vectors (> 10000 ticks) via QCPAxis::setTickVector - - QCPAxis and QCPAxisRect now allow easy access to all plottables(), graphs() and items() that are associated with them - - Added QCustomPlot::hasItem method for consistency with plottable interface, hasPlottable - - Added QCPAxisRect::setMinimumMargins as replacement for hardcoded minimum axis margin (15 px) when auto margin is enabled - - Added Flags type QCPAxis::AxisTypes (from QCPAxis::AxisType), used in QCPAxisRect interface - - Automatic margin calculation can now be enabled/disabled on a per-side basis, see QCPAxisRect::setAutoMargins - - QCPAxisRect margins of multiple axis rects can be coupled via QCPMarginGroup - - Added new default layers "background" and "legend" (QCPAxisRect draws its background on the "background" layer, QCPLegend is on the "legend" layer by default) - - Custom scatter style via QCP::ssCustom and respective setCustomScatter functions that take a QPainterPath - - Filled scatters via QCPScatterStyle::setBrush - Added features after beta: - - Added QCustomPlot::toPainter method, to allow rendering with existing painter - - QCPItemEllipse now provides a center anchor - - Bugfixes: - - Fixed compile error on ARM - - Wrong legend icons were displayed if using pixmaps for scatters that are smaller than the legend icon rect - - Fixed clipping inaccuracy for rotated tick labels (were hidden too early, because the non-rotated bounding box was used) - - Fixed bug that caused wrong clipping of axis ticks and subticks when the ticks were given manually by QCPAxis::setTickVector - - Fixed Qt5 crash when dragging graph out of view (iterator out of bounds in QCPGraph::getVisibleDataBounds) - - Fixed QCPItemText not scaling properly when using scaled raster export - Bugfixes after beta: - - Fixed bug that clipped the rightmost pixel column of tick labels when caching activated (only visible on windows for superscript exponents) - - Restored compatibility to Qt4.6 - - Restored support for -no-RTTI compilation - - Empty manual tick labels are handled more gracefully (no QPainter qDebug messages anymore) - - Fixed type ambiguity in QCPLineEnding::draw causing compile error on ARM - - Fixed bug of grid layouts not propagating the minimum size from their child elements to the parent layout correctly - - Fixed bug of child elements (e.g. axis rects) of inset layouts not properly receiving mouse events - - Other: - - Opened up non-amalgamated project structure to public via git repository - -#### Version released on 09.06.12 #### - - Quick Summary: - - Items (arrows, text,...) - - Layers (easier control over rendering order) - - New antialiasing system (Each objects controls own antialiasing with setAntialiased) - - Performance Improvements - - improved pixel-precise drawing - - easier shared library creation/usage - - Changes that (might) break backward compatibility: - - enum QCPGraph::ScatterSymbol was moved to QCP namespace (now QCP::ScatterSymbol). - This replace should fix your code: "QCPGraph::ss" -> "QCP::ss" - - enum QCustomPlot::AntialiasedElement and flag QCustomPlot::AntialiasedElements was moved to QCP namespace - This replace should fix your code: "QCustomPlot::ae" -> "QCP::ae" - - the meaning of QCustomPlot::setAntialiasedElements has changed slightly: It is now an override to force elements to be antialiased. If you want to force - elements to not be drawn antialiased, use the new setNotAntialiasedElements. If an element is mentioned in neither of those functions, it now controls - its antialiasing itself via its "setAntialiased" function(s). (e.g. QCPAxis::setAntialiased(bool), QCPAbstractPlottable::setAntialiased(bool), - QCPAbstractPlottable::setAntialiasedScatters(bool), etc.) - - QCPAxis::setTickVector and QCPAxis::setTickVectorLabels no longer take a pointer but a const reference of the respective QVector as parameter. - (handing over a pointer didn't give any noticeable performance benefits but was inconsistent with the rest of the interface) - - Equally QCPAxis::tickVector and QCPAxis::tickVectorLabels don't return by pointer but by value now - - QCustomPlot::savePngScaled was removed, its purpose is now included as optional parameter "scale" of savePng. - - If you have derived from QCPAbstractPlottable: all selectTest functions now consistently take the argument "const QPointF &pos" which is the test point in pixel coordinates. - (the argument there was "double key, double value" in plot coordinates, before). - - QCPAbstractPlottable, QCPAxis and QCPLegend now inherit from QCPLayerable - - If you have derived from QCPAbstractPlottable: the draw method signature has changed from "draw (..) const" to "draw (..)", i.e. the method - is not const anymore. This allows the draw function of your plottable to perform buffering/caching operations, if necessary. - - Added features: - - Item system: QCPAbstractItem, QCPItemAnchor, QCPItemPosition, QCPLineEnding. Allows placing of lines, arrows, text, pixmaps etc. - - New Items: QCPItemStraightLine, QCPItemLine, QCPItemCurve, QCPItemEllipse, QCPItemRect, QCPItemPixmap, QCPItemText, QCPItemBracket, QCPItemTracer - - QCustomPlot::addItem/itemCount/item/removeItem/selectedItems - - signals QCustomPlot::itemClicked/itemDoubleClicked - - the QCustomPlot interactions property now includes iSelectItems (for selection of QCPAbstractItem) - - QCPLineEnding. Represents the different styles a line/curve can end (e.g. different arrows, circle, square, bar, etc.), see e.g. QCPItemCurve::setHead - - Layer system: QCPLayerable, QCPLayer. Allows more sophisticated control over drawing order and a kind of grouping. - - QCPAbstractPlottable, QCPAbstractItem, QCPAxis, QCPGrid, QCPLegend are layerables and derive from QCPLayerable - - QCustomPlot::addLayer/moveLayer/removeLayer/setCurrentLayer/layer/currentLayer/layerCount - - Initially there are three layers: "grid", "main", and "axes". The "main" layer is initially empty and set as current layer, so new plottables/items are put there. - - QCustomPlot::viewport now makes the previously inaccessible viewport rect read-only-accessible (needed that for item-interface) - - PNG export now allows transparent background by calling QCustomPlot::setColor(Qt::transparent) before savePng - - QCPStatisticalBox outlier symbols may now be all scatter symbols, not only hardcoded circles. - - perfect precision of scatter symbol/error bar drawing and clipping in both antialiased and non-antialiased mode, by introducing QCPPainter - that works around some QPainter bugs/inconveniences. Further, more complex symbols like ssCrossSquare used to look crooked, now they look good. - - new antialiasing control system: Each drawing element now has its own "setAntialiased" function to control whether it is drawn antialiased. - - QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements can be used to override the individual settings. - - Subclasses of QCPAbstractPlottable can now use the convenience functions like applyFillAntialiasingHint or applyScattersAntialiasingHint to - easily make their drawing code comply with the overall antialiasing system. - - QCustomPlot::setNoAntialiasingOnDrag allows greatly improved performance and responsiveness by temporarily disabling all antialiasing while - the user is dragging axis ranges - - QCPGraph can now show scatter symbols at data points and hide its line (see QCPGraph::setScatterStyle, setScatterSize, setScatterPixmap, setLineStyle) - - Grid drawing code was sourced out from QCPAxis to QCPGrid. QCPGrid is mainly an internal class and every QCPAxis owns one. The grid interface still - works through QCPAxis and hasn't changed. The separation allows the grid to be drawn on a different layer as the axes, such that e.g. a graph can - be above the grid but below the axes. - - QCustomPlot::hasPlottable(plottable), returns whether the QCustomPlot contains the plottable - - QCustomPlot::setPlottingHint/setPlottingHints, plotting hints control details about the plotting quality/speed - - export to jpg and bmp added (QCustomPlot::saveJpg/saveBmp), as well as control over compression quality for png and jpg - - multi-select-modifier may now be specified with QCustomPlot::setMultiSelectModifier and is not fixed to Ctrl anymore - - Bugfixes: - - fixed QCustomPlot ignores replot after it had size (0,0) even if size becomes valid again - - on Windows, a repaint used to be delayed during dragging/zooming of a complex plot, until the drag operation was done. - This was fixed, i.e. repaints are forced after a replot() call. See QCP::phForceRepaint and setPlottingHints. - - when using the raster paintengine and exporting to scaled PNG, pen widths are now scaled correctly (QPainter bug workaround via QCPPainter) - - PDF export now respects QCustomPlot background color (QCustomPlot::setColor), also Qt::transparent - - fixed a bug on QCPBars and QCPStatisticalBox where auto-rescaling of axis would fail when all data is very small (< 1e-11) - - fixed mouse event propagation bug that prevented range dragging from working on KDE (GNU/Linux) - - fixed a compiler warning on 64-bit systems due to pointer cast to int instead of quintptr in a qDebug output - - Other: - - Added support for easier shared library creation (including examples for compiling and using QCustomPlot as shared library) - - QCustomPlot now has the Qt::WA_OpaquePaintEvent widget attribute (gives slightly improved performance). - - QCP::aeGraphs (enum QCP::AntialiasedElement, previously QCustomPlot::aeGraphs) has been marked deprecated since version 02.02.12 and - was now removed. Use QCP::aePlottables instead. - - optional performance-quality-tradeoff for solid graph lines (see QCustomPlot::setPlottingHints). - - marked data classes and QCPRange as Q_MOVABLE_TYPE - - replaced usage of own macro FUNCNAME with Qt macro Q_FUNC_INFO - - QCustomPlot now returns a minimum size hint of 50*50 - -#### Version released on 31.03.12 #### - - Changes that (might) break backward compatibility: - - QCPAbstractLegendItem now inherits from QObject - - mousePress, mouseMove and mouseRelease signals are now emitted before and not after any QCustomPlot processing (range dragging, selecting, etc.) - - Added features: - - Interaction system: now allows selecting of objects like plottables, axes, legend and plot title, see QCustomPlot::setInteractions documentation - - Interaction system for plottables: - - setSelectable, setSelected, setSelectedPen, setSelectedBrush, selectTest on QCPAbstractPlottable and all derived plottables - - setSelectionTolerance on QCustomPlot - - selectedPlottables and selectedGraphs on QCustomPlot (returns the list of currently selected plottables/graphs) - - Interaction system for axes: - - setSelectable, setSelected, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedLabelFont, setSelectedTickLabelFont, - setSelectedLabelColor, setSelectedTickLabelColor, selectTest on QCPAxis - - selectedAxes on QCustomPlot (returns a list of the axes that currently have selected parts) - - Interaction system for legend: - - setSelectable, setSelected, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont, setSelectedTextColor, selectedItems on QCPLegend - - setSelectedFont, setSelectedTextColor, setSelectable, setSelected on QCPAbstractLegendItem - - selectedLegends on QCustomPlot - - Interaction system for title: - - setSelectedTitleFont, setSelectedTitleColor, setTitleSelected on QCustomPlot - - new signals in accordance with the interaction system: - - selectionChangedByUser on QCustomPlot - - selectionChanged on QCPAbstractPlottable - - selectionChanged on QCPAxis - - selectionChanged on QCPLegend and QCPAbstractLegendItem - - plottableClick, legendClick, axisClick, titleClick, plottableDoubleClick, legendDoubleClick, axisDoubleClick, titleDoubleClick on QCustomPlot - - QCustomPlot::deselectAll (deselects everything, i.e. axes and plottables) - - QCPAbstractPlottable::pixelsToCoords (inverse function to the already existing coordsToPixels function) - - QCPRange::contains(double value) - - QCPAxis::setLabelColor and setTickLabelColor - - QCustomPlot::setTitleColor - - QCustomPlot now emits beforeReplot and afterReplot signals. Note that it is safe to make two customPlots mutually call eachothers replot functions - in one of these slots, it will not cause an infinite loop. (usefull for synchronizing axes ranges between two customPlots, because setRange alone doesn't replot) - - If the Qt version is 4.7 or greater, the tick label strings in date-time-mode now support sub-second accuracy (e.g. with format like "hh:mm:ss.zzz"). - - Bugfixes: - - tick labels/margins should no longer oscillate by one pixel when dragging range or replotting repeatedly while changing e.g. data. This - was caused by a bug in Qt's QFontMetrics::boundingRect function when the font has an integer point size (probably some rounding problem). - The fix hence consists of creating a temporary font (only for bounding-box calculation) which is 0.05pt larger and thus avoiding the - jittering rounding outcome. - - tick label, axis label and plot title colors used to be undefined. This was fixed by providing explicit color properties. - - Other: - - fixed some glitches in the documentation - - QCustomPlot::replot and QCustomPlot::rescaleAxes are now slots - -#### Version released on 02.02.12 #### - - Changes that break backward compatibility: - - renamed all secondary classes from QCustomPlot[...] to QCP[...]: - QCustomPlotAxis -> QCPAxis - QCustomPlotGraph -> QCPGraph - QCustomPlotRange -> QCPRange - QCustomPlotData -> QCPData - QCustomPlotDataMap -> QCPDataMap - QCustomPlotLegend -> QCPLegend - QCustomPlotDataMapIterator -> QCPDataMapIterator - QCustomPlotDataMutableMapIterator -> QCPDataMutableMapIterator - A simple search and replace on all code files should make your code run again, e.g. consider the regex "QCustomPlot(?=[AGRDL])" -> "QCP". - Make sure not to just replace "QCustomPlot" with "QCP" because the main class QCustomPlot hasn't changed to QCP. - This change was necessary because class names became unhandy, pardon my bad naming decision in the beginning. - - QCPAxis::tickLength() and QCPAxis::subTickLength() now each split into two functions for inward and outward ticks (tickLengthIn/tickLengthOut). - - QCPLegend now uses QCPAbstractLegendItem to carry item data (before, the legend was passed QCPGraphs directly) - - QCustomPlot::addGraph() now doesn't return the index of the created graph anymore, but a pointer to the created QCPGraph. - - QCustomPlot::setAutoAddGraphToLegend is replaced by setAutoAddPlottableToLegend - - Added features: - - Reversed axis range with QCPAxis::setRangeReversed(bool) - - Tick labels are now only drawn if not clipped by the viewport (widget border) on the sides (e.g. left and right on a horizontal axis). - - Zerolines. Like grid lines only with a separate pen (QCPAxis::setZeroLinePen), at tick position zero. - - Outward ticks. QCPAxis::setTickLength/setSubTickLength now accepts two arguments for inward and outward tick length. This doesn't break - backward compatibility because the second argument (outward) has default value zero and thereby a call with one argument hasn't changed its meaning. - - QCPGraph now inherits from QCPAbstractPlottable - - QCustomPlot::addPlottable/plottable/removePlottable/clearPlottables added to interface with the new QCPAbstractPlottable-based system. The simpler interface - which only acts on QCPGraphs (addGraph, graph, removeGraph, etc.) was adapted internally and is kept for backward compatibility and ease of use. - - QCPLegend items for plottables (e.g. graphs) can automatically wrap their texts to fit the widths, see QCPLegend::setMinimumSize and QCPPlottableLegendItem::setTextWrap. - - QCustomPlot::rescaleAxes. Adapts axis ranges to show all plottables/graphs, by calling QCPAbstractPlottable::rescaleAxes on all plottables in the plot. - - QCPCurve. For plotting of parametric curves. - - QCPBars. For plotting of bar charts. - - QCPStatisticalBox. For statistical box plots. - - Bugfixes: - - Fixed QCustomPlot::removeGraph(int) not being able to remove graph index 0 - - made QCustomPlot::replot() abort painting when painter initialization fails (e.g. because width/height of QCustomPlot is zero) - - The distance of the axis label from the axis ignored the tick label padding, this could have caused overlapping axis labels and tick labels - - fixed memory leak in QCustomPlot (dtor didn't delete legend) - - fixed bug that prevented QCPAxis::setRangeLower/Upper from setting the value to exactly 0. - - Other: - - Changed default error bar handle size (QCustomPlotGraph::setErrorBarSize) from 4 to 6. - - Removed QCustomPlotDataFetcher. Was deprecated and not used class. - - Extended documentation, especially class descriptions. - -#### Version released on 15.01.12 #### - - Changes that (might) break backward compatibility: - - QCustomPlotGraph now inherits from QObject - - Added features: - - Added axis background pixmap (QCustomPlot::setAxisBackground, setAxisBackgroundScaled, setAxisBackgroundScaledMode) - - Added width and height parameter on PDF export function QCustomPlot::savePdf(). This now allows PDF export to - have arbitrary dimensions, independent of the current geometry of the QCustomPlot. - - Added overload of QCustomPlot::removeGraph that takes QCustomPlotGraph* as parameter, instead the index of the graph - - Added all enums to the Qt meta system via Q_ENUMS(). The enums can now be transformed - to QString values easily with the Qt meta system, which makes saving state e.g. as XML - significantly nicer. - - added typedef QMapIterator QCustomPlotDataMapIterator - and typedef QMutableMapIterator QCustomPlotDataMutableMapIterator - for improved information hiding, when using iterators outside QCustomPlot code - - Bugfixes: - - Fixed savePngScaled. Axis/label drawing functions used to reset the painter transform - and thereby break savePngScaled. Now they buffer the current transform and restore it afterwards. - - Fixed some glitches in the doxygen comments (affects documentation only) - - Other: - - Changed the default tickLabelPadding of top axis from 3 to 6 pixels. Looks better. - - Changed the default QCustomPlot::setAntialiasedElements setting: Graph fills are now antialiased - by default. That's a bit slower, but makes fill borders look better. - -#### Version released on 19.11.11 #### - - Changes that break backward compatibility: - - QCustomPlotAxis: tickFont and setTickFont renamed to tickLabelFont and setTickLabelFont (for naming consistency) - - Other: - - QCustomPlotAxis: Added rotated tick labels, see setTickLabelRotation - diff --git a/lib/cpBaseQtApplication/Blocker.cxx b/lib/cpBaseQtApplication/Blocker.cxx deleted file mode 100644 index 634f25b..0000000 --- a/lib/cpBaseQtApplication/Blocker.cxx +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Blocker:: -Blocker( ) - : QObject( ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Blocker:: -~Blocker( ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Blocker:: -block( ) -{ - QApplication* app = - dynamic_cast< QApplication* >( QApplication::instance( ) ); - if( app != NULL ) - { - app->setOverrideCursor( Qt::WaitCursor ); - app->installEventFilter( this ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Blocker:: -unblock( ) -{ - QApplication* app = - dynamic_cast< QApplication* >( QApplication::instance( ) ); - if( app != NULL ) - { - while( app->overrideCursor( ) ) - app->restoreOverrideCursor( ); - app->removeEventFilter( this ); - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Blocker:: -eventFilter( QObject* obj, QEvent* event ) -{ - return( true ); // -> Block all events - /* NOTE: this should be the correct implementation: - switch( event->type( ) ) - { - //list event you want to prevent here ... - case QEvent::KeyPress: - case QEvent::KeyRelease: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonPress: - case QEvent::MouseButtonDblClick: - //... - return( true ); - } // hctiws - return( this->QObject::eventFilter( obj, event ) ); - */ -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Blocker.h b/lib/cpBaseQtApplication/Blocker.h deleted file mode 100644 index 6e7abf8..0000000 --- a/lib/cpBaseQtApplication/Blocker.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __cpBaseQtApplication__Blocker__h__ -#define __cpBaseQtApplication__Blocker__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpBaseQtApplication -{ - /** - */ - class cpBaseQtApplication_EXPORT Blocker - : public QObject - { - public: - Blocker( ); - virtual ~Blocker( ); - - void block( ); - void unblock( ); - - protected: - virtual bool eventFilter( QObject* obj, QEvent* event ); - }; - -} // ecapseman - -#endif // __cpBaseQtApplication__Blocker__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/MainHelper.h b/lib/cpBaseQtApplication/MainHelper.h deleted file mode 100644 index d850b25..0000000 --- a/lib/cpBaseQtApplication/MainHelper.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef __cpBaseQtApplication__MainHelper__h__ -#define __cpBaseQtApplication__MainHelper__h__ - -#include -#include - -// ------------------------------------------------------------------------- -#define cpBaseQtApplication_Main( _window_class_ ) \ - int main( int argc, char* argv[] ) \ - { \ - QApplication a( argc, argv ); \ - _window_class_ w( argc, argv ); \ - w.show( ); \ - return( a.exec( ) ); \ - } - -// ------------------------------------------------------------------------- -#include - -#ifdef cpPlugins_OS_Windows - -# include -# include -# include -# include - -// ------------------------------------------------------------------------- -namespace cpBaseQtApplication -{ - /** - */ - class Win32CommandLineConverter - { - private: - std::unique_ptr< char*[ ] > argv_; - std::vector< std::unique_ptr< char[ ] > > storage_; - - public: - Win32CommandLineConverter( ) - { - LPWSTR cmd_line = GetCommandLineW( ); - int argc; - LPWSTR* w_argv = CommandLineToArgvW( cmd_line, &argc ); - argv_ = std::unique_ptr< char*[ ] >( new char*[ argc ] ); - storage_.reserve( argc ); - for( int i = 0; i < argc; ++i ) - { - storage_.push_back( ConvertWArg( w_argv[ i ] ) ); - argv_[ i ] = storage_.back( ).get( ); - - } // rof - LocalFree( w_argv ); - } - int argc( ) const - { - return( static_cast< int >(storage_.size( ) ) ); - } - char** argv( ) const - { - return( argv_.get( ) ); - } - static std::unique_ptr< char[ ] > ConvertWArg( LPWSTR w_arg ) - { - int size = WideCharToMultiByte( - CP_UTF8, 0, w_arg, -1, nullptr, 0, nullptr, nullptr - ); - std::unique_ptr< char[ ] > ret( new char[ size ] ); - WideCharToMultiByte( - CP_UTF8, 0, w_arg, -1, ret.get( ), size, nullptr, nullptr - ); - return( ret ); - } - }; - -} // ecapseman - -// ------------------------------------------------------------------------- -# define cpBaseQtApplication_MainComplement \ - int CALLBACK WinMain( HINSTANCE i, HINSTANCE p, LPSTR c, int s ) \ - { \ - cpBaseQtApplication::Win32CommandLineConverter cmd_line; \ - return( main( cmd_line.argc( ), cmd_line.argv( ) ) ); \ - } -#else // cpPlugins_OS_Windows -# define cpBaseQtApplication_MainComplement -#endif // cpPlugins_OS_Windows - -#endif // __cpBaseQtApplication__MainHelper__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/MainWindow.cxx b/lib/cpBaseQtApplication/MainWindow.cxx deleted file mode 100644 index 668eb3b..0000000 --- a/lib/cpBaseQtApplication/MainWindow.cxx +++ /dev/null @@ -1,309 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::MainWindow:: -MainWindow( int argc, char* argv[], QWidget* parent ) - : Superclass( parent ), - m_LastSaveFileName( "" ), - m_BaseWindowTitle( "cpBaseQtApplication" ), - m_Canvas( NULL ), - m_Navigator( NULL ), - m_Viewer( NULL ) -{ - this->m_RunPath = QDir( "." ).canonicalPath( ).toStdString( ); - this->m_Loader.GuessEnvironment( this->m_RunPath ); - this->m_Loader.SaveEnvironment( this->m_RunPath ); - this->_clearWorkspace( ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::MainWindow:: -~MainWindow( ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::MainWindow:: -TWorkspace* cpBaseQtApplication::MainWindow:: -workspace( ) -{ - return( this->m_Workspace ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::MainWindow:: -TWorkspace* cpBaseQtApplication::MainWindow:: -workspace( ) const -{ - return( this->m_Workspace ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Canvas* -cpBaseQtApplication::MainWindow:: -canvas( ) -{ - return( this->m_Canvas ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::Canvas* -cpBaseQtApplication::MainWindow:: -canvas( ) const -{ - return( this->m_Canvas ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -setCanvas( cpBaseQtApplication::Pipeline::Canvas* c ) -{ - this->m_Canvas = c; - if( this->m_Canvas != NULL ) - this->m_Canvas->setWorkspace( this->m_Workspace ); - -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Plugins::Navigator* -cpBaseQtApplication::MainWindow:: -navigator( ) -{ - return( this->m_Navigator ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Plugins::Navigator* -cpBaseQtApplication::MainWindow:: -navigator( ) const -{ - return( this->m_Navigator ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -setNavigator( cpBaseQtApplication::Plugins::Navigator* n ) -{ - this->m_Navigator = n; -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::ActorsWidgetInterface* -cpBaseQtApplication::MainWindow:: -viewer( ) -{ - return( this->m_Viewer ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::QT::ActorsWidgetInterface* -cpBaseQtApplication::MainWindow:: -viewer( ) const -{ - return( this->m_Viewer ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -setViewer( cpExtensions::QT::ActorsWidgetInterface* v ) -{ - this->m_Viewer = v; - if( this->m_Viewer != NULL ) - { - auto interactors = this->m_Viewer->GetInteractors( ); - for( auto i : interactors ) - this->m_Workspace->AddInteractor( i ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadPlugins( const std::string& filename ) -{ - try - { - this->m_Loader.Register( filename ); - if( this->m_Navigator != NULL ) - this->m_Navigator->Update( ); - } - catch( std::exception& err ) - { - QMessageBox::critical( - this, - "Error loading plugins path", - err.what( ) - ); - - } // yrt -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadPlugins( ) -{ - QFileDialog dlg( this ); - dlg.setFileMode( QFileDialog::ExistingFiles ); - - std::stringstream filter; - std::string suffix = std::string( cpPlugins_LIB_EXT ); - filter << "Plugins file (*" << cpPlugins_LIB_EXT << ");;All files (*)"; - dlg.setNameFilter( filter.str( ).c_str( ) ); - dlg.setDefaultSuffix( suffix.c_str( ) ); - if( !( dlg.exec( ) ) ) - return; - QStringList names = dlg.selectedFiles( ); - for( auto qIt = names.begin( ); qIt != names.end( ); ++qIt ) - this->_loadPlugins( qIt->toStdString( ) ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadPluginsFromPath( const std::string& path ) -{ - try - { - this->m_Loader.RegisterFromDirectory( path ); - this->m_Loader.SaveEnvironment( this->m_RunPath ); - if( this->m_Navigator != NULL ) - this->m_Navigator->Update( ); - } - catch( std::exception& err ) - { - QMessageBox::critical( - this, - "Error loading plugins path", - err.what( ) - ); - - } // yrt -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadPluginsFromPath( ) -{ - QFileDialog d( this ); - d.setFileMode( QFileDialog::DirectoryOnly ); - if( !( d.exec( ) ) ) - return; - this->_loadPluginsFromPath( d.selectedFiles( ).begin( )->toStdString( ) ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_clearWorkspace( ) -{ - this->setWindowTitle( this->m_BaseWindowTitle.c_str( ) ); - this->m_Workspace = TWorkspace::New( ); - if( this->m_Canvas != NULL ) - { - this->m_Canvas->clear( ); - this->m_Canvas->setWorkspace( this->m_Workspace ); - - } // fi - if( this->m_Viewer != NULL ) - { - // TODO: this->m_Viewer->clear( ); - auto interactors = this->m_Viewer->GetInteractors( ); - for( auto i : interactors ) - this->m_Workspace->AddInteractor( i ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_saveWorkspace( const std::string& fname ) -{ - this->m_LastSaveFileName = fname; - this->m_Workspace->Save( this->m_LastSaveFileName ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_saveWorkspace( ) -{ - if( this->m_LastSaveFileName == "" ) - { - QFileDialog dlg( this ); - dlg.setFileMode( QFileDialog::AnyFile ); - dlg.setDirectory( "." ); - dlg.setAcceptMode( QFileDialog::AcceptSave ); - dlg.setNameFilter( - QFileDialog::tr( "Workspace file (*.wxml);;All files (*)" ) - ); - dlg.setDefaultSuffix( QFileDialog::tr( "wxml" ) ); - dlg.setWindowTitle( "Saving workspace" ); - if( dlg.exec( ) ) - this->_saveWorkspace( dlg.selectedFiles( ).begin( )->toStdString( ) ); - } - else - this->_saveWorkspace( this->m_LastSaveFileName ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadWorkspace( const std::string& fname ) -{ - try - { - this->_clearWorkspace( ); - this->m_Workspace->Load( fname ); - this->m_LastSaveFileName = ""; - if( this->m_Canvas != NULL ) - this->m_Canvas->setWorkspace( this->m_Workspace ); - } - catch( std::exception& err ) - { - QMessageBox::critical( - this, - QMessageBox::tr( "Error loading workspace" ), - QMessageBox::tr( err.what( ) ) - ); - - } // yrt -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_loadWorkspace( ) -{ - QFileDialog dlg( this ); - dlg.setFileMode( QFileDialog::ExistingFile ); - dlg.setDirectory( "." ); - dlg.setNameFilter( - QFileDialog::tr( "Workspace file (*.wxml);;All files (*)" ) - ); - dlg.setDefaultSuffix( QFileDialog::tr( "wxml" ) ); - if( !( dlg.exec( ) ) ) - return; - this->_loadWorkspace( dlg.selectedFiles( ).begin( )->toStdString( ) ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::MainWindow:: -_actorsProperties( ) -{ - auto data = - dynamic_cast< cpExtensions::QT::ActorsWidgetInterface* >( - this->m_Viewer - ); - if( data != NULL ) - { - auto dlg = new cpExtensions::QT::ConfigurationChooser( this ); - dlg->setData( data ); - dlg->exec( ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/MainWindow.h b/lib/cpBaseQtApplication/MainWindow.h deleted file mode 100644 index 2e967d9..0000000 --- a/lib/cpBaseQtApplication/MainWindow.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef __cpBaseQtApplication__MainWindow__h__ -#define __cpBaseQtApplication__MainWindow__h__ - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -#define cpBaseQtApplication_ConnectAction( _act_, _slt_ ) \ - this->connect( \ - this->m_UI->_act_, SIGNAL( triggered( ) ), this, SLOT( _slt_( ) ) \ - ) - -// ------------------------------------------------------------------------- -#define cpBaseQtApplication_Execute( _cmd_ ) \ - { \ - this->m_Blocker.block( ); \ - try \ - { \ - _cmd_; \ - this->m_Blocker.unblock( ); \ - } \ - catch( std::exception& err ) \ - { \ - this->m_Blocker.unblock( ); \ - QMessageBox::critical( \ - this, \ - QMessageBox::tr( "Error executing filter" ), \ - QMessageBox::tr( err.what( ) ) \ - ); \ - } \ - catch( ... ) \ - { \ - this->m_Blocker.unblock( ); \ - QMessageBox::critical( \ - this, \ - QMessageBox::tr( "Error executing filter" ), \ - QMessageBox::tr( "Unknown error" ) \ - ); \ - } \ - this->m_Blocker.unblock( ); \ - } - -// ------------------------------------------------------------------------- -namespace cpExtensions { namespace QT { class ActorsWidgetInterface; } } - -// ------------------------------------------------------------------------- -namespace cpBaseQtApplication -{ - namespace Pipeline { class Canvas; } - namespace Plugins { class Navigator; } - - /** - */ - class cpBaseQtApplication_EXPORT MainWindow - : public QMainWindow - { - Q_OBJECT; - - public: - typedef MainWindow Self; - typedef QMainWindow Superclass; - - typedef cpPlugins::Interface::Loader TLoader; - typedef cpPlugins::Interface::Workspace TWorkspace; - - public: - explicit MainWindow( - int argc, char* argv[], - QWidget* parent = NULL - ); - virtual ~MainWindow( ); - - TWorkspace* workspace( ); - const TWorkspace* workspace( ) const; - - Pipeline::Canvas* canvas( ); - const Pipeline::Canvas* canvas( ) const; - void setCanvas( Pipeline::Canvas* c ); - - Plugins::Navigator* navigator( ); - const Plugins::Navigator* navigator( ) const; - void setNavigator( Plugins::Navigator* n ); - - cpExtensions::QT::ActorsWidgetInterface* viewer( ); - const cpExtensions::QT::ActorsWidgetInterface* viewer( ) const; - void setViewer( cpExtensions::QT::ActorsWidgetInterface* v ); - - protected: - template< class _TViewer > - _TViewer* _configureViewer( QWidget* w ) - { - _TViewer* v = dynamic_cast< _TViewer* >( w ); - if( v == NULL ) - v = new _TViewer( ); - return( v ); - } - - protected slots: - void _loadPlugins( const std::string& filename ); - void _loadPlugins( ); - void _loadPluginsFromPath( const std::string& path ); - void _loadPluginsFromPath( ); - - void _clearWorkspace( ); - - void _saveWorkspace( const std::string& fname ); - void _saveWorkspace( ); - - void _loadWorkspace( const std::string& fname ); - void _loadWorkspace( ); - - void _actorsProperties( ); - - protected: - Blocker m_Blocker; - std::string m_RunPath; - TLoader m_Loader; - std::string m_LastSaveFileName; - TWorkspace::Pointer m_Workspace; - - std::string m_BaseWindowTitle; - - Pipeline::Canvas* m_Canvas; - Plugins::Navigator* m_Navigator; - cpExtensions::QT::ActorsWidgetInterface* m_Viewer; - }; - -} // ecapseman - -#endif // __cpBaseQtApplication__MainWindow__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Block.cxx b/lib/cpBaseQtApplication/Pipeline/Block.cxx deleted file mode 100644 index 3d235aa..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Block.cxx +++ /dev/null @@ -1,418 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -QColor cpBaseQtApplication::Pipeline::Block:: -SelectedAndUpdated = Qt::green; -QColor cpBaseQtApplication::Pipeline::Block:: -NotSelectedAndUpdated = Qt::blue; -QColor cpBaseQtApplication::Pipeline::Block:: -SelectedAndNotUpdated = Qt::yellow; -QColor cpBaseQtApplication::Pipeline::Block:: -NotSelectedAndNotUpdated = Qt::lightGray; - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block::_TFilterObserver:: -Execute( const itk::Object* c, const itk::EventObject& e ) -{ - typedef cpPlugins::Pipeline::Events::Modified _TModified; - const _TModified* mod_evt = dynamic_cast< const _TModified* >( &e ); - if( mod_evt != NULL ) - { - std::stringstream str; - str - << "(" << mod_evt->Time << "/" - << double( mod_evt->Span ) / double( 1000 ) << "s)"; - this->ObservedBlock->setInfoPort( str.str( ).c_str( ) ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Block:: -Block( - TFilter* filter, - QGraphicsItem* parent, QGraphicsScene* scene - ) - : Superclass( parent, scene ), - m_HorzMargin( 20 ), - m_VertMargin( 5 ), - m_NamePort( NULL ), - m_InfoPort( NULL ), - m_Filter( filter ) -{ - QPainterPath p; - p.addRoundedRect( -50, -15, 100, 30, 5, 5 ); - - this->setPath( p ); - this->setPen( QPen( Qt::darkGreen ) ); - this->setBrush( Qt::green ); - this->setFlag( QGraphicsItem::ItemIsMovable ); - this->setFlag( QGraphicsItem::ItemIsSelectable ); - - this->m_Width = this->m_HorzMargin; - this->m_Height = this->m_VertMargin; - - // Configure names - this->setNamePort( filter->GetName( ) ); - this->setInfoPort( "(-/-)" ); - this->_setTypeInfo( - ( - std::string( this->m_Filter->GetClassCategory( ) ) + - std::string( "::" ) + - std::string( this->m_Filter->GetClassName( ) ) - ).c_str( ) - ); - - // Add input ports - auto inputs = this->m_Filter->GetInputsNames( ); - for( auto iIt = inputs.begin( ); iIt != inputs.end( ); ++iIt ) - { - this->addInputPort( - iIt->c_str( ), - this->m_Filter->IsInputMultiple( iIt->c_str( ) ) - ); - - } // rof - - // Add output ports - auto outputs = this->m_Filter->GetOutputsNames( ); - for( auto oIt = outputs.begin( ); oIt != outputs.end( ); ++oIt ) - this->addOutputPort( oIt->c_str( ) ); - - // Add obvserver - this->m_FilterObserver = _TFilterObserver::New( ); - this->m_FilterObserver->ObservedBlock = this; - this->m_FilterObserverId = - this->m_Filter->AddObserver( - cpPlugins::Pipeline::Events::Modified( ), this->m_FilterObserver - ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Block:: -~Block( ) -{ - this->m_Filter->RemoveObserver( this->m_FilterObserverId ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Block:: -TFilter* cpBaseQtApplication::Pipeline::Block:: -filter( ) -{ - return( this->m_Filter ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::Block:: -TFilter* cpBaseQtApplication::Pipeline::Block:: -filter( ) const -{ - return( this->m_Filter ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -setNamePort( const QString& txt ) -{ - if( this->m_NamePort == NULL ) - this->m_NamePort = new NamePort( this ); - this->m_NamePort->setName( txt ); - this->_configPort( this->m_NamePort ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -setInfoPort( const QString& txt ) -{ - if( this->m_InfoPort == NULL ) - this->m_InfoPort = new InfoPort( this ); - this->m_InfoPort->setName( txt ); - this->_configPort( this->m_InfoPort ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InputPort* -cpBaseQtApplication::Pipeline::Block:: -addInputPort( const QString& txt, bool multiple ) -{ - InputPort* ip = new InputPort( this, multiple ); - ip->setExtendedName( "" ); - ip->setName( txt ); - this->m_InputPorts[ txt.toStdString( ) ] = ip; - this->_configPort( ip ); - return( ip ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::OutputPort* -cpBaseQtApplication::Pipeline::Block:: -addOutputPort( const QString& txt ) -{ - OutputPort* op = new OutputPort( this ); - op->setExtendedName( "" ); - op->setName( txt ); - this->m_OutputPorts[ txt.toStdString( ) ] = op; - this->_configPort( op ); - return( op ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InputPort* -cpBaseQtApplication::Pipeline::Block:: -inputPort( const QString& txt ) -{ - auto i = this->m_InputPorts.find( txt.toStdString( ) ); - if( i != this->m_InputPorts.end( ) ) - return( i->second ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::OutputPort* -cpBaseQtApplication::Pipeline::Block:: -outputPort( const QString& txt ) -{ - auto o = this->m_OutputPorts.find( txt.toStdString( ) ); - if( o != this->m_OutputPorts.end( ) ) - return( o->second ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -QString cpBaseQtApplication::Pipeline::Block:: -namePort( ) const -{ - return( this->m_NamePort->name( ) ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::InputPort* -cpBaseQtApplication::Pipeline::Block:: -inputPort( const QString& txt ) const -{ - auto i = this->m_InputPorts.find( txt.toStdString( ) ); - if( i != this->m_InputPorts.end( ) ) - return( i->second ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::OutputPort* -cpBaseQtApplication::Pipeline::Block:: -outputPort( const QString& txt ) const -{ - auto o = this->m_OutputPorts.find( txt.toStdString( ) ); - if( o != this->m_OutputPorts.end( ) ) - return( o->second ); - else - return( NULL ); -} - - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::Block:: -connectOutputPortSlot( QObject* receiver, const char* slot ) -{ - bool ok = true; - for( auto p : this->m_OutputPorts ) - ok &= QObject::connect( - p.second, SIGNAL( viewData( const std::string&, bool ) ), - receiver, slot - ); - return( ok ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -setPos( const QPointF& pos ) -{ - this->m_Filter->SetViewCoords( pos.x( ), pos.y( ) ); - this->Superclass::setPos( pos ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -setPos( qreal x, qreal y ) -{ - this->m_Filter->SetViewCoords( x, y ); - this->Superclass::setPos( x, y ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -paint( - QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget - ) -{ - Q_UNUSED( option ); - Q_UNUSED( widget ); - - if( this->isSelected( ) ) - { - painter->setPen( QPen( Qt::darkYellow ) ); - painter->setBrush( Qt::yellow ); - } - else - { - painter->setPen( QPen( Qt::darkGreen ) ); - painter->setBrush( Qt::green ); - - } // fi - painter->drawPath( this->path( ) ); -} - -// ------------------------------------------------------------------------- -QVariant cpBaseQtApplication::Pipeline::Block:: -itemChange( GraphicsItemChange change, const QVariant& value ) -{ - return( value ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -_setTypeInfo( const QString& txt ) -{ - this->setToolTip( txt ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -_configPort( Port* port ) -{ - port->setBlock( this ); - - QFontMetrics fm( this->scene( )->font( ) ); - this->m_Width = 0; - foreach( QGraphicsItem* i, this->children( ) ) - { - Port* p = dynamic_cast< Port* >( i ); - if( p == NULL ) - continue; - int w = fm.width( p->name( ) ) + ( 4 * p->radius( ) ); - if( w > this->m_Width - this->m_HorzMargin ) - this->m_Width = w + this->m_HorzMargin; - - } // rof - int h = fm.height( ); - this->m_Height = this->m_InputPorts.size( ) + this->m_OutputPorts.size( ); - this->m_Height += 4; - this->m_Height *= h; - - QPainterPath pth; - pth.addRoundedRect( - -this->m_Width / 2, - -this->m_Height / 2, - this->m_Width, - this->m_Height, 5, 5 - ); - this->setPath( pth ); - - int y = -this->m_Height / 2 + this->m_VertMargin + port->radius( ); - foreach( QGraphicsItem* i, this->children( ) ) - { - Port* p = dynamic_cast< Port* >( i ); - if( p == NULL ) - continue; - - if( - dynamic_cast< NamePort* >( i ) != NULL || - dynamic_cast< InfoPort* >( i ) != NULL - ) - { - i->setPos( -this->m_Width / 2 + port->radius( ), y ); - y += h >> 1; - } - else if( dynamic_cast< InputPort* >( i ) != NULL ) - i->setPos( -this->m_Width / 2 - 2 * port->radius( ), y ); - else if( dynamic_cast< OutputPort* >( i ) != NULL ) - i->setPos( this->m_Width / 2, y ); - y += h; - - } // rof -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -mouseReleaseEvent( QGraphicsSceneMouseEvent* evt ) -{ - if( this->m_Filter.IsNotNull( ) ) - this->m_Filter->SetViewCoords( - this->scenePos( ).x( ), - this->scenePos( ).y( ) - ); - this->Superclass::mouseReleaseEvent( evt ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Block:: -contextMenuEvent( QGraphicsSceneContextMenuEvent* evt ) -{ - QMenu menu; - QAction* configureAction = menu.addAction( "Configure" ); - QAction* updateAction = menu.addAction( "Update" ); - auto widget = - dynamic_cast< cpPlugins::Pipeline::Widget* >( - this->m_Filter.GetPointer( ) - ); - QAction* enableAction = NULL; - if( widget != NULL ) - enableAction = - menu.addAction( ( widget->GetEnabled( ) )? "Disable": "Enable" ); - - QAction* selectedAction = menu.exec( evt->screenPos( ) ); - if( selectedAction == configureAction ) - { - auto dlg = this->m_Filter->CreateQDialog( ); - if( dlg != NULL ) - dlg->exec( ); - } - else if( selectedAction == enableAction ) - { - if( widget != NULL ) - widget->SetEnabled( !( widget->GetEnabled( ) ) ); - } - else if( selectedAction == updateAction ) - { - cpBaseQtApplication::Blocker blocker; - blocker.block( ); - try - { - this->m_Filter->Update( ); - blocker.unblock( ); - } - catch( std::exception& err ) - { - blocker.unblock( ); - QMessageBox::critical( - NULL, - QMessageBox::tr( "Error updating filter" ), - QMessageBox::tr( err.what( ) ) - ); - - } // yrt - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Block.h b/lib/cpBaseQtApplication/Pipeline/Block.h deleted file mode 100644 index eaa6bf0..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Block.h +++ /dev/null @@ -1,120 +0,0 @@ -#ifndef __cpBaseQtApplication__Pipeline__Block__h__ -#define __cpBaseQtApplication__Pipeline__Block__h__ - -#include -#include -#include -#include - -namespace cpBaseQtApplication -{ - namespace Pipeline - { - class Port; - class NamePort; - class InfoPort; - class InputPort; - class OutputPort; - - /** - */ - class cpBaseQtApplication_EXPORT Block - : public QGraphicsPathItem - { - public: - typedef Block Self; - typedef QGraphicsPathItem Superclass; - typedef cpPlugins::Pipeline::ProcessObject TFilter; - - protected: - /** - */ - class _TFilterObserver - : public itk::Command - { - public: - typedef itk::SmartPointer< _TFilterObserver > Pointer; - typedef itk::SmartPointer< const _TFilterObserver > ConstPointer; - itkNewMacro( _TFilterObserver ); - public: - void Execute( itk::Object* c, const itk::EventObject& e ) override - { this->Execute( const_cast< const itk::Object* >( c ), e ); } - void Execute( const itk::Object* c, const itk::EventObject& e ) override; - public: - Block* ObservedBlock; - }; - - public: - enum { Type = QGraphicsItem::UserType + 6 }; - - Block( - TFilter* filter, - QGraphicsItem* parent = NULL, QGraphicsScene* scene = NULL - ); - virtual ~Block( ); - - TFilter* filter( ); - const TFilter* filter( ) const; - - void setNamePort( const QString& txt ); - void setInfoPort( const QString& txt ); - InputPort* addInputPort( const QString& txt, bool multiple ); - OutputPort* addOutputPort( const QString& txt ); - - InputPort* inputPort( const QString& txt ); - OutputPort* outputPort( const QString& txt ); - - QString namePort( ) const; - const InputPort* inputPort( const QString& txt ) const; - const OutputPort* outputPort( const QString& txt ) const; - - bool connectOutputPortSlot( QObject* receiver, const char* slot ); - - inline int type( ) const - { return( this->Type ); } - - virtual void setPos( const QPointF& pos ); - virtual void setPos( qreal x, qreal y ); - - virtual void paint( - QPainter* painter, - const QStyleOptionGraphicsItem* option, - QWidget* widget - ); - - protected: - QVariant itemChange( GraphicsItemChange change, const QVariant& value ); - void _setTypeInfo( const QString& txt ); - void _configPort( Port* port ); - - virtual void mouseReleaseEvent( QGraphicsSceneMouseEvent* evt ); - virtual void contextMenuEvent( QGraphicsSceneContextMenuEvent* evt ); - - private: - int m_HorzMargin; - int m_VertMargin; - int m_Width; - int m_Height; - - NamePort* m_NamePort; - InfoPort* m_InfoPort; - std::map< std::string, InputPort* > m_InputPorts; - std::map< std::string, OutputPort* > m_OutputPorts; - - TFilter::Pointer m_Filter; - _TFilterObserver::Pointer m_FilterObserver; - unsigned long m_FilterObserverId; - - static QColor SelectedAndUpdated; - static QColor NotSelectedAndUpdated; - static QColor SelectedAndNotUpdated; - static QColor NotSelectedAndNotUpdated; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Pipeline__Block__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Canvas.cxx b/lib/cpBaseQtApplication/Pipeline/Canvas.cxx deleted file mode 100644 index 8457187..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Canvas.cxx +++ /dev/null @@ -1,452 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Canvas:: -Canvas( QWidget* parent ) - : Superclass( parent ), - m_Workspace( NULL ), - m_ActualConnection( NULL ), - m_OutputPortReceiver( NULL ), - m_OutputPortSlot( "" ) -{ - this->m_Scene = new QGraphicsScene( this ); - this->setScene( this->m_Scene ); - this->setRenderHint( QPainter::Antialiasing ); - this->setAcceptDrops( true ); - - this->m_EventFilter = new EventFilter( this ); - this->m_EventFilter->setCanvas( this ); - this->m_EventFilter->install( this->m_Scene ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Canvas:: -~Canvas( ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -clear( ) -{ - qDeleteAll( this->m_Scene->items( ) ); - this->m_Blocks.clear( ); - this->m_ActualConnection = NULL; -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Canvas:: -TWorkspace* cpBaseQtApplication::Pipeline::Canvas:: -workspace( ) -{ - return( this->m_Workspace ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::Canvas:: -TWorkspace* cpBaseQtApplication::Pipeline::Canvas:: -workspace( ) const -{ - return( this->m_Workspace ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -setWorkspace( TWorkspace* ws ) -{ - if( this->m_Workspace != ws ) - { - this->clear( ); - this->m_Workspace = ws; - - } // fi - this->_redrawWorkspace( ); -} - -// ------------------------------------------------------------------------- -std::string cpBaseQtApplication::Pipeline::Canvas:: -addFilter( const std::string& cat, const std::string& fil, const QPointF& pos ) -{ - auto filter = this->m_Workspace->CreateFilter( cat, fil ); - Block* b = new Block( filter, NULL, this->m_Scene ); - b->setPos( pos ); - if( this->m_OutputPortReceiver != NULL ) - b->connectOutputPortSlot( - this->m_OutputPortReceiver, this->m_OutputPortSlot.c_str( ) - ); - std::string name = filter->GetName( ); - this->m_Blocks[ name ] = b; - return( name ); -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::Canvas:: -connectOutputPortSlot( QObject* receiver, const char* slot ) -{ - this->m_OutputPortReceiver = receiver; - this->m_OutputPortSlot = slot; - bool ok = true; - for( auto b : this->m_Blocks ) - ok &= b.second->connectOutputPortSlot( receiver, slot ); - return( ok ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -rename( QGraphicsItem* item ) -{ - if( this->m_Workspace == NULL ) - return; - - Block* b = dynamic_cast< Block* >( item ); - if( b != NULL ) - { - std::string old_n = b->filter( )->GetName( ); - bool ok; - std::string new_n = - QInputDialog::getText( - dynamic_cast< QWidget* >( this->parent( ) ), - "Change filter name", - "Filter name:", - QLineEdit::Normal, - old_n.c_str( ), - &ok - ).toStdString( ); - if( ok && new_n != "" && old_n != new_n ) - { - if( this->m_Workspace->RenameFilter( old_n, new_n ) ) - { - auto bIt = this->m_Blocks.find( old_n ); - this->m_Blocks[ new_n ] = bIt->second; - bIt->second->setNamePort( new_n.c_str( ) ); - this->m_Blocks.erase( bIt ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -exposePort( QGraphicsItem* item ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -moveConnection( const QPointF& pnt ) -{ - if( this->m_ActualConnection != NULL ) - { - if( this->m_ActualConnection->port1( ) == NULL ) - this->m_ActualConnection->setPos1( pnt ); - else if( this->m_ActualConnection->port2( ) == NULL ) - this->m_ActualConnection->setPos2( pnt ); - this->m_ActualConnection->updatePath( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -grab( const QPointF& pnt ) -{ - QGraphicsItem* item = this->m_Scene->itemAt( pnt ); - OutputPort* oport = dynamic_cast< OutputPort* >( item ); - if( oport != NULL ) - { - // Start new connection - this->m_ActualConnection = new Connection( 0, this->m_Scene ); - this->m_ActualConnection->setPort1( oport ); - this->m_ActualConnection->setPos1( oport->scenePos( ) ); - this->m_ActualConnection->setPos2( pnt ); - this->m_ActualConnection->updatePosFromPorts( ); - this->m_ActualConnection->updatePath( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -release( const QPointF& pnt ) -{ - if( this->m_ActualConnection == NULL || this->m_Workspace == NULL ) - return; - - QGraphicsItem* item = this->m_Scene->itemAt( pnt ); - InputPort* iport = dynamic_cast< InputPort* >( item ); - OutputPort* oport = - dynamic_cast< OutputPort* >( this->m_ActualConnection->port1( ) ); - if( iport != NULL && oport != NULL ) - { - Block* iblock = iport->block( ); - Block* oblock = oport->block( ); - std::string ofil = oblock->namePort( ).toStdString( ); - std::string dfil = iblock->namePort( ).toStdString( ); - std::string oname = oport->name( ).toStdString( ); - std::string dname = iport->name( ).toStdString( ); - try - { - if( this->m_Workspace->Connect( ofil, oname, dfil, dname ) ) - { - this->m_ActualConnection->setPos2( iport->scenePos( ) ); - this->m_ActualConnection->setPort2( iport ); - this->m_ActualConnection->updatePosFromPorts( ); - this->m_ActualConnection->updatePath( ); - } - else - delete this->m_ActualConnection; - } - catch( std::exception& err ) - { - delete this->m_ActualConnection; - QMessageBox::critical( - NULL, - QMessageBox::tr( "Error connecting ports" ), - QMessageBox::tr( err.what( ) ) - ); - - } // yrt - this->m_ActualConnection = NULL; - } - else - { - delete this->m_ActualConnection; - this->m_ActualConnection = NULL; - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -keyPressEvent( QKeyEvent* event ) -{ - static const int del_key = 16777223; - if( this->m_Workspace == NULL ) - return; - - switch( event->key( ) ) - { - case del_key: - { - // Get items to delete - auto _items = this->items( ); - auto i = _items.begin( ); - std::set< Block* > blocks_to_delete; - std::set< Connection* > connections_to_delete; - while( i != _items.end( ) ) - { - if( ( *i )->isSelected( ) ) - { - Block* b = dynamic_cast< Block* >( *i ); - Connection* c = dynamic_cast< Connection* >( *i ); - if( b != NULL ) - { - blocks_to_delete.insert( b ); - auto inputs = b->filter( )->GetInputsNames( ); - for( auto inIt : inputs ) - { - InputPort* p = b->inputPort( inIt.c_str( ) ); - for( unsigned int j = 0; j < p->numberOfConnections( ); ++j ) - connections_to_delete.insert( p->connection( j ) ); - - } // rof - auto outputs = b->filter( )->GetOutputsNames( ); - for( auto outIt : outputs ) - { - OutputPort* p = b->outputPort( outIt.c_str( ) ); - auto& conns = p->connections( ); - for( unsigned int j = 0; j < conns.size( ); ++j ) - connections_to_delete.insert( conns[ j ] ); - - } // rof - } - else if( c != NULL ) - connections_to_delete.insert( c ); - - } // fi - i++; - - } // elihw - - // Delete connections - for( auto conn : connections_to_delete ) - { - OutputPort* oport = conn->port1( ); - InputPort* iport = conn->port2( ); - Block* oblock = oport->block( ); - Block* iblock = iport->block( ); - if( - this->m_Workspace->Disconnect( - oblock->namePort( ).toStdString( ), - oport->name( ).toStdString( ), - iblock->namePort( ).toStdString( ), - iport->name( ).toStdString( ) - ) - ) - delete conn; - - } // rof - - // Delete blocks - for( auto block : blocks_to_delete ) - if( - this->m_Workspace->RemoveFilter( block->namePort( ).toStdString( ) ) - ) - delete block; - } - break; - default: - break; - } // hctiws -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -wheelEvent( QWheelEvent* event ) -{ - this->_scaleView( - std::pow( double( 2 ), event->delta( ) / double( 240 ) ) - ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -dragEnterEvent( QDragEnterEvent* event ) -{ - const QMimeData* mime = event->mimeData( ); - if( mime->hasFormat( "application/x-qabstractitemmodeldatalist" ) ) - event->acceptProposedAction( ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -dragLeaveEvent( QDragLeaveEvent* event ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -dragMoveEvent( QDragMoveEvent* event ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -dropEvent( QDropEvent* event ) -{ - if( this->m_Workspace == NULL ) - return; - const QMimeData* mime = event->mimeData( ); - if( !( mime->hasFormat( "application/x-qabstractitemmodeldatalist" ) ) ) - return; - event->acceptProposedAction( ); - auto tree = dynamic_cast< QTreeWidget* >( event->source( ) ); - if( tree == NULL ) - return; - - QPointF p = this->mapToScene( event->pos( ) ); - QList< QTreeWidgetItem* > items = tree->selectedItems( ); - for( auto iIt = items.begin( ); iIt != items.end( ); ++iIt ) - { - auto parent = ( *iIt )->parent( ); - if( parent != NULL ) - this->addFilter( - parent->text( 0 ).toStdString( ), - ( *iIt )->text( 0 ).toStdString( ), - p - ); - - } // rof -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -_scaleView( qreal scaleFactor ) -{ - qreal factor = this->transform( ). - scale( scaleFactor, scaleFactor ). - mapRect( QRectF( 0, 0, 1, 1 ) ). - width( ); - if( factor < qreal( 0.07 ) || factor > qreal( 100 ) ) - return; - this->scale( scaleFactor, scaleFactor ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Canvas:: -_redrawWorkspace( ) -{ - // Get filters names - if( this->m_Workspace == NULL ) - return; - auto fnames = this->m_Workspace->GetFiltersNames( ); - - // Create blocks - for( auto fname : fnames ) - { - auto filter = this->m_Workspace->GetFilter( fname ); - Block* b = new Block( filter, NULL, this->m_Scene ); - b->setPos( filter->GetViewX( ), filter->GetViewY( ) ); - if( this->m_OutputPortReceiver != NULL ) - b->connectOutputPortSlot( - this->m_OutputPortReceiver, this->m_OutputPortSlot.c_str( ) - ); - this->m_Blocks[ filter->GetName( ) ] = b; - - } // rof - - // Create connections - for( auto b : this->m_Blocks ) - { - auto filter = b.second->filter( ); - auto inputs = filter->GetInputsNames( ); - for( auto in : inputs ) - { - for( unsigned int id = 0; id < filter->GetInputSize( in ); ++id ) - { - auto inData = filter->GetInput( in, id ); - if( inData != NULL ) - { - auto src = inData->GetSource( ); - auto outputs = src->GetOutputsNames( ); - std::string outName = ""; - for( auto out : outputs ) - if( src->GetOutput( out ) == inData ) - outName = out; - auto c = this->m_Blocks.find( src->GetName( ) ); - auto b_src = c->second; - auto b_des = b.second; - auto oport = b_src->outputPort( outName.c_str( ) ); - auto iport = b_des->inputPort( in.c_str( ) ); - - auto conn = new Connection( 0, this->m_Scene ); - conn->setPort1( oport ); - conn->setPort2( iport ); - conn->setPos1( oport->scenePos( ) ); - conn->setPos2( iport->scenePos( ) ); - conn->updatePosFromPorts( ); - conn->updatePath( ); - - } // fi - - } // rof - - } // rof - - } // rof -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Canvas.h b/lib/cpBaseQtApplication/Pipeline/Canvas.h deleted file mode 100644 index bdd487c..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Canvas.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef __cpBaseQtApplication__Pipeline__Canvas__h__ -#define __cpBaseQtApplication__Pipeline__Canvas__h__ - -#include -#include -#include - -class QGraphicsScene; - -namespace cpBaseQtApplication -{ - namespace Pipeline - { - // Some other forward declarations - class EventFilter; - class Block; - class Connection; - - /** - */ - class cpBaseQtApplication_EXPORT Canvas - : public QGraphicsView - { - Q_OBJECT; - - public: - typedef Canvas Self; - typedef QGraphicsView Superclass; - typedef cpPlugins::Interface::Workspace TWorkspace; - - public: - Canvas( QWidget* parent = 0 ); - virtual ~Canvas( ); - - void clear( ); - - TWorkspace* workspace( ); - const TWorkspace* workspace( ) const; - void setWorkspace( TWorkspace* ws ); - - std::string addFilter( - const std::string& cat, const std::string& fil, - const QPointF& pos = QPointF( 0, 0 ) - ); - bool connectOutputPortSlot( QObject* receiver, const char* slot ); - - void rename( QGraphicsItem* item ); - void exposePort( QGraphicsItem* item ); - void moveConnection( const QPointF& pnt ); - void grab( const QPointF& pnt ); - void release( const QPointF& pnt ); - - protected: - void keyPressEvent( QKeyEvent* event ); - void wheelEvent( QWheelEvent* event ); - - void dragEnterEvent( QDragEnterEvent* event ); - void dragLeaveEvent( QDragLeaveEvent* event ); - void dragMoveEvent( QDragMoveEvent* event ); - void dropEvent( QDropEvent* event ); - - void _scaleView( qreal scaleFactor ); - void _redrawWorkspace( ); - - protected: - QGraphicsScene* m_Scene; - EventFilter* m_EventFilter; - TWorkspace* m_Workspace; - std::map< std::string, Block* > m_Blocks; - - Connection* m_ActualConnection; - - QObject* m_OutputPortReceiver; - std::string m_OutputPortSlot; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Pipeline__Canvas__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Connection.cxx b/lib/cpBaseQtApplication/Pipeline/Connection.cxx deleted file mode 100644 index 28bd39c..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Connection.cxx +++ /dev/null @@ -1,135 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Connection:: -Connection( QGraphicsItem* parent, QGraphicsScene* scene ) - : Superclass( parent, scene ) -{ - this->setPen( QPen( Qt::black, 2 ) ); - this->setBrush( Qt::NoBrush ); - this->setZValue( -1 ); - this->m_Port1 = NULL; - this->m_Port2 = NULL; - this->setFlag( QGraphicsItem::ItemIsSelectable ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Connection:: -~Connection( ) -{ - if( this->m_Port1 != NULL ) - this->m_Port1->removeConnection( this ); - if( this->m_Port2 != NULL ) - this->m_Port2->removeConnection( this ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -setPos1( const QPointF& p ) -{ - this->m_Pos1 = p; -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -setPos2( const QPointF& p ) -{ - this->m_Pos2 = p; -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -setPort1( OutputPort* p ) -{ - if( p != NULL ) - { - p->connections( ).push_back( this ); - this->m_Port1 = p; - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -setPort2( InputPort* p ) -{ - if( p != NULL ) - { - p->setConnection( this ); - this->m_Port2 = p; - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -updatePosFromPorts( ) -{ - if( this->m_Port1 != NULL ) - this->m_Pos1 = - this->m_Port1->scenePos( ) + - QPointF( this->m_Port1->radius( ), this->m_Port1->radius( ) ); - if( this->m_Port2 != NULL ) - this->m_Pos2 = - this->m_Port2->scenePos( ) + - QPointF( this->m_Port2->radius( ), this->m_Port2->radius( ) ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -updatePath( ) -{ - QPainterPath p; - p.moveTo( this->m_Pos1 ); - - qreal dx = this->m_Pos2.x( ) - this->m_Pos1.x( ); - qreal dy = this->m_Pos2.y( ) - this->m_Pos1.y( ); - QPointF c1( this->m_Pos1.x( ) + dx * 0.25, this->m_Pos1.y( ) + dy * 0.1 ); - QPointF c2( this->m_Pos1.x( ) + dx * 0.75, this->m_Pos1.y( ) + dy * 0.9 ); - p.cubicTo( c1, c2, this->m_Pos2 ); - - this->setPath( p ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::OutputPort* -cpBaseQtApplication::Pipeline::Connection:: -port1( ) const -{ - return( this->m_Port1 ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InputPort* -cpBaseQtApplication::Pipeline::Connection:: -port2( ) const -{ - return( this->m_Port2 ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Connection:: -paint( - QPainter* painter, - const QStyleOptionGraphicsItem* option, - QWidget* widget - ) -{ - Q_UNUSED( option ); - Q_UNUSED( widget ); - - if( this->isSelected( ) ) - painter->setPen( QPen( Qt::red, 5 ) ); - else - painter->setPen( QPen( Qt::black, 2 ) ); - this->setBrush( Qt::NoBrush ); - painter->drawPath( this->path( ) ); -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Connection.h b/lib/cpBaseQtApplication/Pipeline/Connection.h deleted file mode 100644 index ecfc8d2..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Connection.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef __cpBaseQtApplication__Pipeline__Connection__h__ -#define __cpBaseQtApplication__Pipeline__Connection__h__ - -#include -#include - -namespace cpBaseQtApplication -{ - namespace Pipeline - { - class InputPort; - class OutputPort; - - /** - */ - class cpBaseQtApplication_EXPORT Connection - : public QGraphicsPathItem - { - public: - typedef Connection Self; - typedef QGraphicsPathItem Superclass; - - public: - enum { Type = QGraphicsItem::UserType + 5 }; - - Connection( QGraphicsItem* parent = 0, QGraphicsScene* scene = 0 ); - virtual ~Connection( ); - - void setPos1( const QPointF& p ); - void setPos2( const QPointF& p ); - void setPort1( OutputPort* p ); - void setPort2( InputPort* p ); - void updatePosFromPorts( ); - void updatePath( ); - OutputPort* port1( ) const; - InputPort* port2( ) const; - - inline int type( ) const - { return( this->Type ); } - - virtual void paint( - QPainter* painter, - const QStyleOptionGraphicsItem* option, - QWidget* widget - ); - - private: - QPointF m_Pos1; - QPointF m_Pos2; - OutputPort* m_Port1; - InputPort* m_Port2; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Pipeline__Connection__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/EventFilter.cxx b/lib/cpBaseQtApplication/Pipeline/EventFilter.cxx deleted file mode 100644 index 5149c60..0000000 --- a/lib/cpBaseQtApplication/Pipeline/EventFilter.cxx +++ /dev/null @@ -1,227 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -#define cpBaseQtApplicationPipelineEventFilterCbckSWITCH( E, e ) \ - case QEvent::GraphicsScene##E: \ - { \ - QGraphicsScene##E##Event* evt = \ - dynamic_cast< QGraphicsScene##E##Event* >( e ); \ - if( evt != NULL ) \ - this->_##E##_cbk( evt ); \ - } \ - break; - -// ------------------------------------------------------------------------- -#define cpBaseQtApplicationPipelineEventFilterCallbackCODE( E ) \ - void cpBaseQtApplication::Pipeline::EventFilter:: \ - _##E##_cbk( QGraphicsScene##E##Event* evt ) - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::EventFilter:: -EventFilter( QObject* parent ) - : Superclass( parent ), - m_Scene( NULL ), - m_Canvas( NULL ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::EventFilter:: -~EventFilter( ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Canvas* -cpBaseQtApplication::Pipeline::EventFilter:: -canvas( ) -{ - return( this->m_Canvas ); -} - -// ------------------------------------------------------------------------- -const cpBaseQtApplication::Pipeline::Canvas* -cpBaseQtApplication::Pipeline::EventFilter:: -canvas( ) const -{ - return( this->m_Canvas ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::EventFilter:: -setCanvas( cpBaseQtApplication::Pipeline::Canvas* c ) -{ - this->m_Canvas = c; -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::EventFilter:: -install( QGraphicsScene* s ) -{ - s->installEventFilter( this ); - this->m_Scene = s; -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::EventFilter:: -eventFilter( QObject* o, QEvent* e ) -{ - // Event type - switch( int( e->type( ) ) ) - { - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( ContextMenu, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( DragEnter, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( DragLeave, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( DragMove, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( Drop, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( Help, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( HoverEnter, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( HoverLeave, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( HoverMove, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( MouseDoubleClick, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( MouseMove, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( MousePress, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( MouseRelease, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( Move, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( Resize, e ); - cpBaseQtApplicationPipelineEventFilterCbckSWITCH( Wheel, e ); - default: - break; - } // hctiws - return( this->Superclass::eventFilter( o, e ) ); -} - -// ------------------------------------------------------------------------- -QGraphicsItem* cpBaseQtApplication::Pipeline::EventFilter:: -itemAt( const QPointF& pos ) -{ - QList< QGraphicsItem* > items = - this->m_Scene->items( QRectF( pos - QPointF( 1, 1 ), QSize( 3, 3 ) ) ); - QGraphicsItem* ret = NULL; - foreach( QGraphicsItem* item, items ) - if( item->type( ) > QGraphicsItem::UserType ) - ret = item; - return( ret ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( ContextMenu ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( DragEnter ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( DragLeave ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( DragMove ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( Drop ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( Help ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( HoverEnter ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( HoverLeave ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( HoverMove ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( MouseDoubleClick ) -{ - // Get clicked item - QGraphicsItem* item = this->itemAt( evt->scenePos( ) ); - if( item == NULL ) - return; - - if( evt->button( ) == Qt::LeftButton ) - { - if( evt->modifiers( ) == Qt::NoModifier ) - this->m_Canvas->rename( item ); - else if( evt->modifiers( ) == Qt::ControlModifier ) - this->m_Canvas->exposePort( item ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( MouseMove ) -{ - this->m_Canvas->moveConnection( evt->scenePos( ) ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( MousePress ) -{ - switch( evt->button( ) ) - { - case Qt::LeftButton: this->m_Canvas->grab( evt->scenePos( ) ); break; - default: break; - } // hctiws -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( MouseRelease ) -{ - switch( evt->button( ) ) - { - case Qt::LeftButton: this->m_Canvas->release( evt->scenePos( ) ); break; - default: break; - } // hctiws -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( Move ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( Resize ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplicationPipelineEventFilterCallbackCODE( Wheel ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/EventFilter.h b/lib/cpBaseQtApplication/Pipeline/EventFilter.h deleted file mode 100644 index 0243b7c..0000000 --- a/lib/cpBaseQtApplication/Pipeline/EventFilter.h +++ /dev/null @@ -1,96 +0,0 @@ -#ifndef __cpBaseQtApplication__Pipeline__EventFilter__h__ -#define __cpBaseQtApplication__Pipeline__EventFilter__h__ - -#include -#include -#include - -class QGraphicsScene; -class QGraphicsSceneMouseEvent; -class QGraphicsItem; -class QGraphicsSceneContextMenuEvent; -class QGraphicsSceneDragDropEvent; -class QGraphicsSceneHelpEvent; -class QGraphicsSceneHoverEvent; -class QGraphicsSceneMouseEvent; -class QGraphicsSceneMoveEvent; -class QGraphicsSceneResizeEvent; -class QGraphicsSceneWheelEvent; - -// ------------------------------------------------------------------------- -#define cpBaseQtApplicationPipelineEventFilterCallbackDCL( E ) \ - void _##E##_cbk( QGraphicsScene##E##Event* e ); - -namespace cpBaseQtApplication -{ - namespace Pipeline - { - class Canvas; - - /** - */ - class cpBaseQtApplication_EXPORT EventFilter - : public QObject - { - Q_OBJECT; - - public: - typedef EventFilter Self; - typedef QObject Superclass; - - public: - explicit EventFilter( QObject* parent = 0 ); - virtual ~EventFilter( ); - - Canvas* canvas( ); - const Canvas* canvas( ) const; - void setCanvas( Canvas* c ); - - void install( QGraphicsScene* s ); - bool eventFilter( QObject* o, QEvent* e ); - - private: - QGraphicsItem* itemAt( const QPointF& pos ); - - protected: - typedef QGraphicsSceneDragDropEvent QGraphicsSceneDragEnterEvent; - typedef QGraphicsSceneDragDropEvent QGraphicsSceneDragLeaveEvent; - typedef QGraphicsSceneDragDropEvent QGraphicsSceneDragMoveEvent; - typedef QGraphicsSceneDragDropEvent QGraphicsSceneDropEvent; - typedef QGraphicsSceneHoverEvent QGraphicsSceneHoverEnterEvent; - typedef QGraphicsSceneHoverEvent QGraphicsSceneHoverMoveEvent; - typedef QGraphicsSceneHoverEvent QGraphicsSceneHoverLeaveEvent; - typedef QGraphicsSceneMouseEvent QGraphicsSceneMouseDoubleClickEvent; - typedef QGraphicsSceneMouseEvent QGraphicsSceneMouseMoveEvent; - typedef QGraphicsSceneMouseEvent QGraphicsSceneMousePressEvent; - typedef QGraphicsSceneMouseEvent QGraphicsSceneMouseReleaseEvent; - - cpBaseQtApplicationPipelineEventFilterCallbackDCL( ContextMenu ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( DragEnter ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( DragLeave ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( DragMove ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( Drop ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( Help ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( HoverEnter ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( HoverLeave ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( HoverMove ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( MouseDoubleClick ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( MouseMove ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( MousePress ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( MouseRelease ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( Move ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( Resize ); - cpBaseQtApplicationPipelineEventFilterCallbackDCL( Wheel ); - - private: - QGraphicsScene* m_Scene; - Canvas* m_Canvas; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Pipeline__EventFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Port.cxx b/lib/cpBaseQtApplication/Pipeline/Port.cxx deleted file mode 100644 index f5b0b01..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Port.cxx +++ /dev/null @@ -1,358 +0,0 @@ -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Port:: -Port( QGraphicsItem* parent, QGraphicsScene* scene ) - : QObject( ), - Superclass( parent, scene ), - m_Radius( 5 ), - m_Margin( 2 ) -{ - this->m_Label = new QGraphicsTextItem( this ); - this->m_ExtendedLabel = new QGraphicsTextItem( this ); - this->setExtend( false ); - - QPainterPath p; - p.addEllipse( 0, 0, 2 * this->m_Radius, 2 * this->m_Radius ); - - this->setPath( p ); - this->setPen( QPen( Qt::darkRed ) ); - this->setBrush( Qt::red ); - this->setFlag( QGraphicsItem::ItemSendsScenePositionChanges ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::Port:: -~Port( ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Port:: -setBlock( Block* b ) -{ - this->m_Block = b; -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Port:: -setName( const QString& n ) -{ - this->m_Label->setPlainText( n ); - this->_updateLabels( ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Port:: -setExtendedName( const QString& n ) -{ - this->m_ExtendedLabel->setPlainText( n ); - this->_updateLabels( ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Port:: -setExtend( bool extend ) -{ - // Do nothing! - this->m_IsExtended = false; - this->m_ExtendedLabel->setVisible( false ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::Port:: -paint( - QPainter* painter, - const QStyleOptionGraphicsItem* option, - QWidget* widget - ) -{ - Q_UNUSED( option ); - Q_UNUSED( widget ); - - if( this->isExtended( ) ) - { - painter->setPen( QPen( Qt::darkBlue ) ); - painter->setBrush( Qt::blue ); - } - else - { - painter->setPen( QPen( Qt::darkRed ) ); - painter->setBrush( Qt::red ); - - } // fi - painter->drawPath( this->path( ) ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::NamePort:: -NamePort( QGraphicsItem* parent, QGraphicsScene* scene ) - : Superclass( parent, scene ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::NamePort:: -~NamePort( ) -{ -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::NamePort:: -isConnected( Port* other ) -{ - return( false ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::NamePort:: -_updateLabels( ) -{ - QFont font( this->scene( )->font( ) ); - font.setBold( true ); - this->m_Label->setFont( font ); - this->m_ExtendedLabel->setFont( font ); - this->setPath( QPainterPath( ) ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InfoPort:: -InfoPort( QGraphicsItem* parent, QGraphicsScene* scene ) - : Superclass( parent, scene ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InfoPort:: -~InfoPort( ) -{ -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::InfoPort:: -isConnected( Port* other ) -{ - return( false ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::InfoPort:: -_updateLabels( ) -{ - QFont font( this->scene( )->font( ) ); - font.setBold( false ); - this->m_Label->setFont( font ); - this->m_ExtendedLabel->setFont( font ); - this->setPath( QPainterPath( ) ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InputPort:: -InputPort( QGraphicsItem* parent, bool multiple, QGraphicsScene* scene ) - : Superclass( parent, scene ), - m_IsMultiple( multiple ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::InputPort:: -~InputPort( ) -{ - this->m_Connection.clear( ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::InputPort:: -_updateLabels( ) -{ - QFontMetrics fm( this->scene( )->font( ) ); - this->m_Label->setPos( this->m_Radius * 2, -fm.height( ) / 2 ); - this->m_ExtendedLabel->setPos( - -fm.width( this->extendedName( ) ) - this->m_Radius * 2, - -fm.height( ) / 2 - ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::InputPort:: -setExtend( bool extend ) -{ - if( this->m_Connection.size( ) == 0 ) - { - this->m_IsExtended = extend; - this->m_ExtendedLabel->setVisible( extend ); - } - else - this->Superclass::setExtend( false ); -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::InputPort:: -isConnected( Port* other ) -{ - bool conn = false; - auto i = this->m_Connection.begin( ); - for( ; i != this->m_Connection.end( ); ++i ) - conn |= ( ( *i )->port1( ) == other && ( *i )->port2( ) == this ); - return( conn ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::InputPort:: -setConnection( Connection* c ) -{ - if( this->m_IsMultiple || this->m_Connection.size( ) == 0 ) - this->m_Connection.push_back( c ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::InputPort:: -removeConnection( Connection* c ) -{ - auto i = std::find( - this->m_Connection.begin( ), - this->m_Connection.end( ), - c - ); - if( i != this->m_Connection.end( ) ) - { - *i = NULL; - this->m_Connection.erase( i ); - - } // fi -} - -// ------------------------------------------------------------------------- -QVariant cpBaseQtApplication::Pipeline::InputPort:: -itemChange( GraphicsItemChange change, const QVariant& value ) -{ - if( change == ItemScenePositionHasChanged ) - { - for( - auto i = this->m_Connection.begin( ); - i != this->m_Connection.end( ); - ++i - ) - { - ( *i )->updatePosFromPorts( ); - ( *i )->updatePath( ); - - } // fi - - } // fi - return( value ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::OutputPort:: -OutputPort( QGraphicsItem* parent, QGraphicsScene* scene ) - : Superclass( parent, scene ) -{ -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Pipeline::OutputPort:: -~OutputPort( ) -{ - foreach( Connection* conn, this->m_Connections ) - delete conn; -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::OutputPort:: -_updateLabels( ) -{ - QFontMetrics fm( this->scene( )->font( ) ); - this->m_Label->setPos( - -fm.width( this->name( ) ) - this->m_Radius * 2, -fm.height( ) / 2 - ); - this->m_ExtendedLabel->setPos( this->m_Radius * 2, -fm.height( ) / 2 ); - -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::OutputPort:: -removeConnection( Connection* c ) -{ - auto i = std::find( - this->m_Connections.begin( ), - this->m_Connections.end( ), - c - ); - if( i != this->m_Connections.end( ) ) - { - *i = NULL; - this->m_Connections.erase( i ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::OutputPort:: -setExtend( bool extend ) -{ - this->m_IsExtended = extend; - this->m_ExtendedLabel->setVisible( extend ); -} - -// ------------------------------------------------------------------------- -bool cpBaseQtApplication::Pipeline::OutputPort:: -isConnected( Port* other ) -{ - auto i = this->m_Connections.begin( ); - bool conn = false; - for( ; i != this->m_Connections.end( ) && !conn; ++i ) - conn |= ( ( *i )->port1( ) == this && ( *i )->port2( ) == other ); - return( conn ); -} - -// ------------------------------------------------------------------------- -QVariant cpBaseQtApplication::Pipeline::OutputPort:: -itemChange( GraphicsItemChange change, const QVariant& value ) -{ - if( change == ItemScenePositionHasChanged ) - { - foreach( Connection* conn, this->m_Connections ) - { - conn->updatePosFromPorts( ); - conn->updatePath( ); - - } // rof - - } // fi - return( value ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Pipeline::OutputPort:: -contextMenuEvent( QGraphicsSceneContextMenuEvent* evt ) -{ - if( this->m_Block == NULL ) - return; - - QMenu menu; - QAction* showAction = menu.addAction( "Show" ); - QAction* hideAction = menu.addAction( "Hide" ); - QAction* selectedAction = menu.exec( evt->screenPos( ) ); - - if( selectedAction == showAction || selectedAction == hideAction ) - { - std::stringstream str; - str - << this->name( ).toStdString( ) << "@" - << this->m_Block->filter( )->GetName( ); - emit viewData( str.str( ), ( selectedAction == showAction ) ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Pipeline/Port.h b/lib/cpBaseQtApplication/Pipeline/Port.h deleted file mode 100644 index 0622925..0000000 --- a/lib/cpBaseQtApplication/Pipeline/Port.h +++ /dev/null @@ -1,216 +0,0 @@ -#ifndef __cpBaseQtApplication__Pipeline__Port__h__ -#define __cpBaseQtApplication__Pipeline__Port__h__ - -#include -#include - -namespace cpBaseQtApplication -{ - namespace Pipeline - { - class Block; - class Connection; - - /** - */ - class cpBaseQtApplication_EXPORT Port - : public QObject, - public QGraphicsPathItem - { - Q_OBJECT; - public: - typedef Port Self; - typedef QGraphicsPathItem Superclass; - - enum { Type = QGraphicsItem::UserType + 1 }; - - public: - Port( QGraphicsItem* parent = NULL, QGraphicsScene* scene = NULL ); - virtual ~Port( ); - - void setBlock( Block* b ); - inline Block* block( ) const - { return( this->m_Block ); } - - virtual void setName( const QString& n ); - virtual void setExtendedName( const QString& n ); - inline QString name( ) const - { return( this->m_Label->toPlainText( ) ); } - inline QString extendedName( ) const - { return( this->m_ExtendedLabel->toPlainText( ) ); } - - inline int radius( ) const - { return( this->m_Radius ); } - - inline bool isExtended( ) const - { return( this->m_IsExtended ); } - virtual void setExtend( bool extend ); - - virtual bool isConnected( Port* other ) = 0; - inline int type( ) const - { return( this->Type ); } - - virtual void paint( - QPainter* painter, - const QStyleOptionGraphicsItem* option, - QWidget* widget - ); - - protected: - virtual void _updateLabels( ) { } - - protected: - Block* m_Block; - - int m_Radius; - int m_Margin; - bool m_IsExtended; - - QGraphicsTextItem* m_Label; - QGraphicsTextItem* m_ExtendedLabel; - }; - - /** - */ - class cpBaseQtApplication_EXPORT NamePort - : public Port - { - Q_OBJECT; - public: - typedef NamePort Self; - typedef Port Superclass; - - enum { Type = Superclass::Type + 1 }; - - public: - NamePort( QGraphicsItem* parent = NULL, QGraphicsScene* scene = NULL ); - virtual ~NamePort( ); - - virtual bool isConnected( Port* other ); - inline int type( ) const - { return( this->Type ); } - - protected: - virtual void _updateLabels( ); - }; - - /** - */ - class cpBaseQtApplication_EXPORT InfoPort - : public Port - { - Q_OBJECT; - public: - typedef InfoPort Self; - typedef Port Superclass; - - enum { Type = Superclass::Type + 2 }; - - public: - InfoPort( QGraphicsItem* parent = NULL, QGraphicsScene* scene = NULL ); - virtual ~InfoPort( ); - - virtual bool isConnected( Port* other ); - inline int type( ) const - { return( this->Type ); } - - protected: - virtual void _updateLabels( ); - }; - - /** - */ - class cpBaseQtApplication_EXPORT InputPort - : public Port - { - Q_OBJECT; - public: - typedef InputPort Self; - typedef Port Superclass; - - enum { Type = Superclass::Type + 3 }; - - public: - InputPort( - QGraphicsItem* parent, - bool multiple, - QGraphicsScene* scene = NULL - ); - virtual ~InputPort( ); - - virtual void setExtend( bool extend ); - - virtual bool isConnected( Port* other ); - inline int type( ) const - { return( this->Type ); } - - void setConnection( Connection* c ); - void removeConnection( Connection* c ); - inline unsigned int numberOfConnections( ) const - { return( this->m_Connection.size( ) ); } - inline Connection* connection( unsigned int i ) - { return( this->m_Connection[ i ] ); } - inline const Connection* connection( unsigned int i ) const - { return( this->m_Connection[ i ] ); } - inline bool hasConnection( ) const - { return( this->m_Connection.size( ) > 0 ); } - inline bool isMultiple( ) const - { return( this->m_IsMultiple ); } - - protected: - QVariant itemChange( GraphicsItemChange change, const QVariant& value ); - virtual void _updateLabels( ); - - protected: - std::vector< Connection* > m_Connection; - bool m_IsMultiple; - }; - - /** - */ - class cpBaseQtApplication_EXPORT OutputPort - : public Port - { - Q_OBJECT; - public: - typedef OutputPort Self; - typedef Port Superclass; - - enum { Type = Superclass::Type + 4 }; - - public: - OutputPort( QGraphicsItem* parent = NULL, QGraphicsScene* scene = NULL ); - virtual ~OutputPort( ); - - void removeConnection( Connection* c ); - virtual void setExtend( bool extend ); - - virtual bool isConnected( Port* other ); - inline int type( ) const - { return( this->Type ); } - - inline std::vector< Connection* >& connections( ) - { return( this->m_Connections ); } - inline const std::vector< Connection* >& connections( ) const - { return( this->m_Connections ); } - - signals: - void viewData( const std::string& name, bool show ); - - protected: - QVariant itemChange( GraphicsItemChange change, const QVariant& value ); - virtual void _updateLabels( ); - - virtual void contextMenuEvent( QGraphicsSceneContextMenuEvent* evt ); - - protected: - std::vector< Connection* > m_Connections; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Pipeline__Port__h__ - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Plugins/Navigator.cxx b/lib/cpBaseQtApplication/Plugins/Navigator.cxx deleted file mode 100644 index 8fa3048..0000000 --- a/lib/cpBaseQtApplication/Plugins/Navigator.cxx +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Plugins::Navigator:: -Navigator( QWidget* parent ) - : Superclass( parent ) -{ - this->setDragEnabled( true ); - this->setDragDropMode( QAbstractItemView::DragOnly ); - this->setAlternatingRowColors( true ); - this->_Clear( ); -} - -// ------------------------------------------------------------------------- -cpBaseQtApplication::Plugins::Navigator:: -~Navigator( ) -{ -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Plugins::Navigator:: -Update( ) -{ - this->_Clear( ); - this->_Update( ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Plugins::Navigator:: -_Clear( ) -{ - this->clear( ); - this->setColumnCount( 1 ); - QString header_txt = "Loaded plugins"; - if( QTreeWidgetItem* header = this->headerItem( ) ) - header->setText( 0, header_txt ); - else - this->setHeaderLabel( header_txt ); -} - -// ------------------------------------------------------------------------- -void cpBaseQtApplication::Plugins::Navigator:: -_Update( ) -{ - typedef cpPlugins::Interface::Loader _TLoader; - _TLoader loader; - - // Iterate over categories and filters - auto filters = loader.GetFilters( ); - for( auto catIt : filters ) - { - const char* c_cat = catIt.first.c_str( ); - - // Create or get category - QList< QTreeWidgetItem* > cat_items = - this->findItems( c_cat, Qt::MatchExactly | Qt::MatchRecursive ); - QTreeWidgetItem* cat = NULL; - if( cat_items.size( ) == 0 ) - { - cat = new QTreeWidgetItem( - ( QTreeWidgetItem* )( NULL ), QStringList( c_cat ) - ); - this->addTopLevelItem( cat ); - } - else - cat = cat_items[ 0 ]; - - for( auto filIt : catIt.second ) - { - const char* c_fil = filIt.c_str( ); - QList< QTreeWidgetItem* > filter_items = - this->findItems( c_fil, Qt::MatchExactly | Qt::MatchRecursive ); - auto i = filter_items.begin( ); - auto found_i = filter_items.end( ); - for( ; i != filter_items.end( ); ++i ) - if( ( *i )->parent( ) == cat ) - found_i = i; - - // Add filter - if( found_i == filter_items.end( ) ) - QTreeWidgetItem* filter = new QTreeWidgetItem( - cat, QStringList( c_fil ) - ); - - } // rof - - } // rof - this->expandAll( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpBaseQtApplication/Plugins/Navigator.h b/lib/cpBaseQtApplication/Plugins/Navigator.h deleted file mode 100644 index a4a745a..0000000 --- a/lib/cpBaseQtApplication/Plugins/Navigator.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __cpBaseQtApplication__Plugins__Navigator__h__ -#define __cpBaseQtApplication__Plugins__Navigator__h__ - -#include -#include - -namespace cpBaseQtApplication -{ - namespace Plugins - { - /** - */ - class cpBaseQtApplication_EXPORT Navigator - : public QTreeWidget - { - Q_OBJECT; - - public: - typedef Navigator Self; - typedef QTreeWidget Superclass; - - public: - explicit Navigator( QWidget* parent = NULL ); - virtual ~Navigator( ); - - void Update( ); - - protected: - void _Clear( ); - void _Update( ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpBaseQtApplication__Plugins__Navigator__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/BezierCurveFunction.h b/lib/cpExtensions/Algorithms/BezierCurveFunction.h deleted file mode 100644 index 65c3af8..0000000 --- a/lib/cpExtensions/Algorithms/BezierCurveFunction.h +++ /dev/null @@ -1,77 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__H__ -#define __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__H__ - -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - * Uses the De Casteljau's algorithm. - */ - template< class V > - class BezierCurveFunction - : public itk::FunctionBase< typename V::ValueType, V > - { - public: - typedef BezierCurveFunction Self; - typedef itk::FunctionBase< typename V::ValueType, V > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef V TVector; - typedef typename V::ValueType TScalar; - - typedef - itk::Matrix< TScalar, TVector::Dimension, TVector::Dimension > - TFrame; - typedef std::vector< TVector > TVectorsContainer; - - public: - itkNewMacro( Self ); - itkTypeMacro( BezierCurveFunction, itkFunctionBase ); - - public: - virtual void AddPoint( const TVector& v ); - virtual unsigned int GetNumberOfPoints( ) const; - - virtual TVector Evaluate( const TScalar& u ) const cpExtensions_OVERRIDE; - virtual TFrame EvaluateFrenetFrame( const TScalar& u ) const; - virtual TScalar EvaluateLength( ) const; - - protected: - BezierCurveFunction( ); - virtual ~BezierCurveFunction( ) { } - - void _UpdateDerivative( ) const; - - private: - // Purposely not implemented - BezierCurveFunction( const Self& other ); - Self& operator=( const Self& other ); - - protected: - TVectorsContainer m_Vectors; - mutable Pointer m_Derivative; - mutable bool m_DerivativeUpdated; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/BezierCurveFunction.hxx b/lib/cpExtensions/Algorithms/BezierCurveFunction.hxx deleted file mode 100644 index 684360f..0000000 --- a/lib/cpExtensions/Algorithms/BezierCurveFunction.hxx +++ /dev/null @@ -1,155 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__HXX__ - -// ------------------------------------------------------------------------- -template< class V > -void cpExtensions::Algorithms::BezierCurveFunction< V >:: -AddPoint( const TVector& v ) -{ - this->m_Vectors.push_back( v ); - this->m_DerivativeUpdated = false; - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class V > -unsigned int cpExtensions::Algorithms::BezierCurveFunction< V >:: -GetNumberOfPoints( ) const -{ - return( this->m_Vectors.size( ) ); -} - -// ------------------------------------------------------------------------- -template< class V > -typename cpExtensions::Algorithms::BezierCurveFunction< V >:: -TVector cpExtensions::Algorithms::BezierCurveFunction< V >:: -Evaluate( const TScalar& u ) const -{ - TVectorsContainer Q = this->m_Vectors; - unsigned int n = Q.size( ); - TScalar _1u = TScalar( 1 ) - u; - - for( unsigned int k = 1; k < n; k++ ) - { - // CM Fixed a bug appearing under Windows : changed the stopping - // condition from <= to <. Otherwise, on the last step, an element out - // of the range of vector Q is accessed (Q[ i + 1 ])... - for( unsigned int i = 0; i < n - k; i++ ) - Q[ i ] = ( Q[ i ] * _1u ) + ( Q[ i + 1 ] * u ); - - } // rof - return( Q[ 0 ] ); -} - -// ------------------------------------------------------------------------- -template< class V > -typename cpExtensions::Algorithms::BezierCurveFunction< V >:: -TFrame cpExtensions::Algorithms::BezierCurveFunction< V >:: -EvaluateFrenetFrame( const TScalar& u ) const -{ - TFrame fr; - fr.Fill( TScalar( 0 ) ); - if( TVector::Dimension == 2 ) - { - this->_UpdateDerivative( ); - this->m_Derivative->_UpdateDerivative( ); - - TVector vT = this->m_Derivative->Evaluate( u ); - TScalar nvT = vT.GetNorm( ); - if( TScalar( 0 ) < nvT ) - vT /= nvT; - - fr[ 0 ][ 0 ] = vT[ 0 ]; - fr[ 1 ][ 0 ] = vT[ 1 ]; - - fr[ 0 ][ 1 ] = -vT[ 1 ]; - fr[ 1 ][ 1 ] = vT[ 0 ]; - } - else if( TVector::Dimension == 3 ) - { - this->_UpdateDerivative( ); - this->m_Derivative->_UpdateDerivative( ); - TVector vT = this->m_Derivative->Evaluate( u ); - TScalar nvT = vT.GetNorm( ); - if( nvT > TScalar( 0 ) ) - { - vT /= nvT; - TVector vN = this->m_Derivative->m_Derivative->Evaluate( u ); - TScalar nvN = vN.GetNorm( ); - if( nvT > TScalar( 0 ) ) - { - vN /= nvN; - TVector vB; - vB[ 0 ] = ( vT[ 1 ] * vN[ 2 ] ) - ( vT[ 2 ] * vN[ 1 ] ); - vB[ 1 ] = ( vT[ 2 ] * vN[ 0 ] ) - ( vT[ 0 ] * vN[ 2 ] ); - vB[ 2 ] = ( vT[ 0 ] * vN[ 1 ] ) - ( vT[ 1 ] * vN[ 0 ] ); - - for( unsigned int d = 0; d < 3; d++ ) - { - fr[ d ][ 0 ] = vT[ d ]; - fr[ d ][ 1 ] = vN[ d ]; - fr[ d ][ 2 ] = vB[ d ]; - - } // rof - } - else - std::cerr << "ERROR normal" << std::endl; - } - else - std::cerr << "ERROR tangent" << std::endl; - - } // fi - return( fr ); -} - -// ------------------------------------------------------------------------- -template< class V > -typename cpExtensions::Algorithms::BezierCurveFunction< V >:: -TScalar cpExtensions::Algorithms::BezierCurveFunction< V >:: -EvaluateLength( ) const -{ - unsigned int n = this->GetNumberOfPoints( ) << 1; - TScalar d = TScalar( 0 ); - TVector v0 = this->Evaluate( 0 ); - for( unsigned int i = 1; i < n; i++ ) - { - TVector v1 = this->Evaluate( TScalar( i ) / TScalar( n - 1 ) ); - d += ( v1 - v0 ).GetNorm( ); - v0 = v1; - - } // rof - return( d ); -} - -// ------------------------------------------------------------------------- -template< class V > -cpExtensions::Algorithms::BezierCurveFunction< V >:: -BezierCurveFunction( ) - : Superclass( ), - m_DerivativeUpdated( false ) -{ -} - -// ------------------------------------------------------------------------- -template< class V > -void cpExtensions::Algorithms::BezierCurveFunction< V >:: -_UpdateDerivative( ) const -{ - if( this->m_DerivativeUpdated ) - return; - - this->m_Derivative = Self::New( ); - unsigned int n = this->m_Vectors.size( ) - 1; - for( unsigned int i = 0; i < n; i++ ) - this->m_Derivative->AddPoint( - TScalar( n ) * ( this->m_Vectors[ i + 1 ] - this->m_Vectors[ i ] ) - ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__BEZIERCURVEFUNCTION__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/CPRImageFilter.h b/lib/cpExtensions/Algorithms/CPRImageFilter.h deleted file mode 100644 index ed13da3..0000000 --- a/lib/cpExtensions/Algorithms/CPRImageFilter.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef __cpExtensions__Algorithms__CPRImageFilter__h__ -#define __cpExtensions__Algorithms__CPRImageFilter__h__ - -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TImage, class _TCurve > - class CPRImageFilter - : public itk::ImageToImageFilter< _TImage, _TImage > - { - public: - typedef CPRImageFilter Self; - typedef itk::ImageToImageFilter< _TImage, _TImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TImage TImage; - typedef _TCurve TCurve; - typedef typename TCurve::TScalar TScalar; - - typedef IsoImageSlicer< TImage, TScalar > TSlicer; - typedef typename TSlicer::TInterpolateFunction TInterpolateFunction; - typedef typename TSlicer::TSliceImage TSliceImage; - - typedef itk::JoinSeriesImageFilter< TSliceImage, TImage > TJoinFilter; - - public: - itkNewMacro( Self ); - itkTypeMacro( CPRImageFilter, itk::ImageToImageFilter ); - - itkGetConstMacro( SliceRadius, double ); - itkGetObjectMacro( Interpolator, TInterpolateFunction ); - - itkSetMacro( SliceRadius, double ); - itkSetObjectMacro( Interpolator, TInterpolateFunction ); - - public: - _TCurve* GetCurve( ); - const _TCurve* GetCurve( ) const; - void SetCurve( _TCurve* curve ); - - protected: - CPRImageFilter( ); - virtual ~CPRImageFilter( ); - - virtual void GenerateOutputInformation( ) cpExtensions_OVERRIDE; - virtual void GenerateInputRequestedRegion( ) cpExtensions_OVERRIDE; - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - protected: - double m_SliceRadius; - typename TInterpolateFunction::Pointer m_Interpolator; - - std::vector< typename TSlicer::Pointer > m_Slicers; - typename TJoinFilter::Pointer m_Join; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__CPRImageFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/CPRImageFilter.hxx b/lib/cpExtensions/Algorithms/CPRImageFilter.hxx deleted file mode 100644 index de76e7f..0000000 --- a/lib/cpExtensions/Algorithms/CPRImageFilter.hxx +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef __cpExtensions__Algorithms__CPRImageFilter__hxx__ -#define __cpExtensions__Algorithms__CPRImageFilter__hxx__ - -#include - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -_TCurve* cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -GetCurve( ) -{ - return( - dynamic_cast< _TCurve* >( this->itk::ProcessObject::GetInput( 1 ) ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -const _TCurve* cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -GetCurve( ) const -{ - return( - dynamic_cast< const _TCurve* >( this->itk::ProcessObject::GetInput( 1 ) ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -void cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -SetCurve( _TCurve* curve ) -{ - this->itk::ProcessObject::SetNthInput( 1, curve ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -CPRImageFilter( ) - : Superclass( ), - m_SliceRadius( 0 ) -{ - this->Superclass::SetNumberOfRequiredInputs( 2 ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -~CPRImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -void cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -GenerateOutputInformation( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -void cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -GenerateInputRequestedRegion( ) -{ - TImage* input = const_cast< TImage* >( this->GetInput( ) ); - if( input != NULL ) - input->SetRequestedRegionToLargestPossibleRegion( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TCurve > -void cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve >:: -GenerateData( ) -{ - typedef itk::MinimumMaximumImageCalculator< _TImage > _TMinMax; - - auto input = this->GetInput( ); - auto curve = this->GetCurve( ); - auto output = this->GetOutput( ); - - // Compute image intensity range - typename _TMinMax::Pointer minmax = _TMinMax::New( ); - minmax->SetImage( input ); - minmax->Compute( ); - - // Main loop - this->m_Join = TJoinFilter::New( ); - this->m_Slicers.clear( ); - unsigned long N = curve->GetNumberOfPoints( ); - double len = 0; - typename _TCurve::TPoint p, q; - for( unsigned long n = 0; n < N; ++n ) - { - p = curve->GetPoint( n ); - if( n > 0 ) - len += p.EuclideanDistanceTo( q ); - q = p; - - // Prepare slicer - typename TSlicer::Pointer slicer = TSlicer::New( ); - slicer->SetInput( input ); - slicer->SetDefaultValue( minmax->GetMinimum( ) ); - slicer->SpacingFromMinimumOn( ); - if( this->m_Interpolator.IsNotNull( ) ) - slicer->SetInterpolator( this->m_Interpolator ); - slicer->SizeFromMaximumOff( ); - if( this->m_SliceRadius > double( 0 ) ) - { - slicer->SizeFromMinimumOff( ); - slicer->SetSize( this->m_SliceRadius ); - } - else - slicer->SizeFromMinimumOn( ); - slicer->SetTranslation( p ); - slicer->SetRotation( curve->GetFrame( n ) ); - slicer->Update( ); - - this->m_Join->SetInput( n, slicer->GetOutput( ) ); - this->m_Slicers.push_back( slicer ); - - } // rof - this->m_Join->SetSpacing( len / double( N ) ); - this->m_Join->Update( ); - this->GetOutput( )->Graft( this->m_Join->GetOutput( ) ); -} - -#endif // __cpExtensions__Algorithms__CPRImageFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.h b/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.h deleted file mode 100644 index 43f44c3..0000000 --- a/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.h +++ /dev/null @@ -1,66 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__DiscontinuityMapImageFilter__h__ -#define __cpExtensions__Algorithms__DiscontinuityMapImageFilter__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TInputImage > - class DiscontinuityMapImageFilter - : public itk::BoxImageFilter< _TInputImage, itk::Image< double, _TInputImage::ImageDimension > > - { - public: - typedef _TInputImage TInputImage; - typedef itk::Image< double, _TInputImage::ImageDimension > TOutputImage; - typedef DiscontinuityMapImageFilter Self; - typedef itk::BoxImageFilter< TInputImage, TOutputImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef typename TInputImage::PixelType TInputPixel; - typedef typename TInputImage::RegionType TRegion; - typedef typename TOutputImage::PixelType TOutputPixel; - - public: - itkNewMacro( Self ); - itkTypeMacro( DiscontinuityMapImageFilter, itkBoxImageFilter ); - - itkBooleanMacro( UseSquareRoot ); - itkGetConstMacro( UseSquareRoot, bool ); - itkSetMacro( UseSquareRoot, bool ); - - protected: - DiscontinuityMapImageFilter( ); - virtual ~DiscontinuityMapImageFilter( ); - - virtual void ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) override; - - private: - // Purposely not implemented. - DiscontinuityMapImageFilter( const Self& ); - void operator=( const Self& ); - - protected: - bool m_UseSquareRoot; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__DiscontinuityMapImageFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.hxx b/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.hxx deleted file mode 100644 index f1786b4..0000000 --- a/lib/cpExtensions/Algorithms/DiscontinuityMapImageFilter.hxx +++ /dev/null @@ -1,91 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__DiscontinuityMapImageFilter__hxx__ -#define __cpExtensions__Algorithms__DiscontinuityMapImageFilter__hxx__ - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TInputImage > -cpExtensions::Algorithms::DiscontinuityMapImageFilter< _TInputImage >:: -DiscontinuityMapImageFilter( ) - : Superclass( ), - m_UseSquareRoot( false ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage > -cpExtensions::Algorithms::DiscontinuityMapImageFilter< _TInputImage >:: -~DiscontinuityMapImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage > -void cpExtensions::Algorithms::DiscontinuityMapImageFilter< _TInputImage >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) -{ - unsigned int i; - - itk::ZeroFluxNeumannBoundaryCondition< TInputImage > nbc; - itk::ConstNeighborhoodIterator< TInputImage > bit; - itk::ImageRegionIterator< TOutputImage > it; - - // Allocate output - typename TOutputImage::Pointer output = this->GetOutput( ); - typename TInputImage::ConstPointer input = this->GetInput( ); - - // Find the data-set boundary "faces" - typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TInputImage >::FaceListType faceList; - itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TInputImage > bC; - faceList = bC( input, region, this->GetRadius( ) ); - - typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TInputImage >::FaceListType::iterator fit; - - TOutputPixel sum1, sum2; - TOutputPixel neighborhoodSize; - - // Process each of the boundary faces. These are N-d regions which border - // the edge of the buffer. - for( fit = faceList.begin( ); fit != faceList.end( ); ++fit ) - { - bit = itk::ConstNeighborhoodIterator< TInputImage >( this->GetRadius( ), input, *fit ); - neighborhoodSize = TOutputPixel( bit.Size( ) ); - it = itk::ImageRegionIterator< TOutputImage >( output, *fit ); - bit.OverrideBoundaryCondition( &nbc ); - bit.GoToBegin( ); - while( !bit.IsAtEnd( ) ) - { - sum1 = itk::NumericTraits< TOutputPixel >::ZeroValue( ); - sum2 = itk::NumericTraits< TOutputPixel >::ZeroValue( ); - for ( i = 0; i < neighborhoodSize; ++i ) - { - TOutputPixel v = TOutputPixel( bit.GetPixel( i ) ); - sum1 += v; - sum2 += v * v; - } - TOutputPixel var = - ( sum2 - ( ( sum1 * sum1 ) / neighborhoodSize ) ) / - ( neighborhoodSize - TOutputPixel( 1 ) ); - if( this->m_UseSquareRoot ) - it.Set( std::sqrt( double( var ) ) ); - else - it.Set( var ); - ++bit; - ++it; - - } // elihw - - } // rof -} - -#endif // __cpExtensions__Algorithms__DiscontinuityMapImageFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/FluxMedialness.h b/lib/cpExtensions/Algorithms/FluxMedialness.h deleted file mode 100644 index c25f5f4..0000000 --- a/lib/cpExtensions/Algorithms/FluxMedialness.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__H__ -#define __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TGradient, class _TMask = itk::Image< unsigned char, _TGradient::ImageDimension > > - class FluxMedialness - : public GradientImageFunctionBase< _TGradient, _TMask > - { - public: - typedef FluxMedialness Self; - typedef GradientImageFunctionBase< _TGradient, _TMask > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - itkStaticConstMacro( Dimension, unsigned int, Superclass::Dimension ); - - typedef typename Superclass::TOutput TOutput; - typedef typename Superclass::TScalar TScalar; - typedef typename Superclass::TIndex TIndex; - typedef typename Superclass::TVector TVector; - typedef typename Superclass::TPoint TPoint; - - typedef std::vector< double > TRCandidates; - - public: - itkNewMacro( Self ); - itkTypeMacro( FluxMedialness, GradientImageFunctionBase ); - - itkGetConstMacro( RadiusStep, double ); - itkGetConstMacro( MinRadius, double ); - itkGetConstMacro( MaxRadius, double ); - itkGetConstMacro( RadialSampling, unsigned int ); - - itkSetMacro( RadiusStep, double ); - itkSetMacro( MinRadius, double ); - itkSetMacro( MaxRadius, double ); - itkSetMacro( RadialSampling, unsigned int ); - - protected: - FluxMedialness( ); - virtual ~FluxMedialness( ); - - virtual TOutput _Evaluate( const TIndex& i ) const cpExtensions_OVERRIDE; - - private: - // Purposely not implemented. - FluxMedialness( const Self& ); - void operator=( const Self& ); - - protected: - double m_MinRadius; - double m_MaxRadius; - unsigned int m_RadialSampling; - double m_RadiusStep; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/FluxMedialness.hxx b/lib/cpExtensions/Algorithms/FluxMedialness.hxx deleted file mode 100644 index 4412292..0000000 --- a/lib/cpExtensions/Algorithms/FluxMedialness.hxx +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__HXX__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::FluxMedialness< _TGradient, _TMask >:: -FluxMedialness( ) - : Superclass( ), - m_MinRadius( double( 0 ) ), - m_MaxRadius( double( 1 ) ), - m_RadialSampling( 4 ), - m_RadiusStep( double( 1 ) ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::FluxMedialness< _TGradient, _TMask >:: -~FluxMedialness( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename cpExtensions::Algorithms::FluxMedialness< _TGradient, _TMask >:: -TOutput cpExtensions::Algorithms::FluxMedialness< _TGradient, _TMask >:: -_Evaluate( const TIndex& i ) const -{ - itk::Object::GlobalWarningDisplayOff( ); - - double pi2n = double( 2 ) * double( vnl_math::pi ); - pi2n /= int( this->m_RadialSampling ); - const _TGradient* img = this->GetInputImage( ); - // Gradient in central pixel - //TVector grad_idx = img->GetPixel( i ); - - double Flux1 = 0; - double Flux = 0; - - TRCandidates FluxFinal; - TRCandidates radiusGenerated; - double dR = double( 0 ); - double optR = double( 0 ); - TPoint center; - img->TransformIndexToPhysicalPoint( i, center ); - double radius = double(0); - - for( unsigned int cx = 0; cx < Self::Dimension - 1; cx++ ) - { - for( unsigned int cy = cx + 1; cy < Self::Dimension; cy++ ) - { - dR = double( 0 ); - FluxFinal.clear(); - radiusGenerated.clear(); - radius = this->m_MinRadius; - while( radius <= this->m_MaxRadius ) - { - Flux = 0; - for( unsigned int I_radial = 0; I_radial < this->m_RadialSampling ; I_radial++ ) - { - Flux1 = 0; - - // Direction of first profile - typename TPoint::VectorType dir1; - dir1.Fill( double( 0 ) ); - dir1[ cx ] = std::cos( pi2n * double( I_radial ) ); - dir1[ cy ] = std::sin( pi2n * double( I_radial ) ); - dir1 *= (radius); - TIndex rIdx; - if (img->TransformPhysicalPointToIndex( center + dir1, rIdx )) - { - TVector grad_rIdx = img->GetPixel( rIdx ); - TVector u_i1; - u_i1.SetVnlVector( ( center - ( center + dir1 ) ).GetVnlVector( ) ); - u_i1.Normalize( ); - // dot product - Flux1 = grad_rIdx * u_i1; - } - - Flux += Flux1; - - } // rof - //std::cout<<" radius:"<m_RadialSampling; - FluxFinal.push_back(Flux); - radiusGenerated.push_back(radius); - radius += this->m_RadiusStep; - - } //elihw - - dR= *( std::max_element( FluxFinal.begin(), FluxFinal.end() ) ); - optR= (dR>optR)? dR:optR; - - } // rof - - } // rof - return( TScalar(optR) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__FLUXMEDIALNESS__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/GaussianDensityImageFilter.h b/lib/cpExtensions/Algorithms/GaussianDensityImageFilter.h deleted file mode 100644 index 308b3c5..0000000 --- a/lib/cpExtensions/Algorithms/GaussianDensityImageFilter.h +++ /dev/null @@ -1,103 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__GAUSSIANDENSITYIMAGEFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__GAUSSIANDENSITYIMAGEFILTER__H__ - -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TInputImage, class _TEstimator > - class GaussianDensityImageFilter - : public itk::ImageToImageFilter< _TInputImage, itk::Image< typename _TEstimator::TScalar, _TInputImage::ImageDimension > > - { - public: - typedef typename _TEstimator::TScalar TScalar; - typedef itk::Image< TScalar, _TInputImage::ImageDimension > TOutputImage; - typedef GaussianDensityImageFilter Self; - typedef itk::ImageToImageFilter< _TInputImage, TOutputImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TInputImage TInputImage; - typedef _TEstimator TEstimator; - typedef typename TOutputImage::RegionType TRegion; - - public: - itkNewMacro( Self ); - itkTypeMacro( GaussianDensityImageFilter, itkImageToImageFilter ); - - itkGetConstObjectMacro( Estimator, TEstimator ); - itkSetConstObjectMacro( Estimator, TEstimator ); - - protected: - GaussianDensityImageFilter( ) - : Superclass( ) - { - } - virtual ~GaussianDensityImageFilter( ) - { - } - - virtual void ThreadedGenerateData( - const TRegion& region, - itk::ThreadIdType threadId - ) - { - const typename TRegion::SizeType& regionSize = region.GetSize( ); - if( regionSize[ 0 ] == 0 ) - return; - const TInputImage* in = this->GetInput( ); - TOutputImage* out = this->GetOutput( 0 ); - - const size_t nLines = region.GetNumberOfPixels( ) / regionSize[ 0 ]; - itk::ProgressReporter progress( this, threadId, nLines ); - - // Define the iterators - itk::ImageScanlineConstIterator< TInputImage > inIt( in, region ); - itk::ImageScanlineIterator< TOutputImage > outIt( out, region ); - - inIt.GoToBegin( ); - outIt.GoToBegin( ); - while( !inIt.IsAtEnd( ) ) - { - while( !inIt.IsAtEndOfLine( ) ) - { - if( this->m_Estimator.IsNotNull( ) ) - outIt.Set( this->m_Estimator->Density( inIt.Get( ) ) ); - ++inIt; - ++outIt; - - } // elihw - inIt.NextLine( ); - outIt.NextLine( ); - progress.CompletedPixel( ); - - } // elihw - } - - private: - // Purposely not implemented. - GaussianDensityImageFilter( const Self& ); - void operator=( const Self& ); - - protected: - typename TEstimator::ConstPointer m_Estimator; - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__GAUSSIANDENSITYIMAGEFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/GradientImageFunctionBase.h b/lib/cpExtensions/Algorithms/GradientImageFunctionBase.h deleted file mode 100644 index 7350495..0000000 --- a/lib/cpExtensions/Algorithms/GradientImageFunctionBase.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__H__ -#define __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__H__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - * Base class to compute values based on image gradients (vector). - */ - template< class _TGradient, class _TMask = itk::Image< unsigned char, _TGradient::ImageDimension > > - class GradientImageFunctionBase - : public itk::ImageFunction< _TGradient, typename _TGradient::PixelType::ValueType, typename _TGradient::PixelType::ValueType > - { - public: - // Types from input arguments - typedef _TGradient TGradient; - typedef _TMask TMask; - typedef typename _TGradient::PixelType TVector; - typedef typename TVector::ValueType TScalar; - itkStaticConstMacro( - Dimension, unsigned int, _TGradient::ImageDimension - ); - - // Standard itk types - typedef GradientImageFunctionBase Self; - typedef itk::ImageFunction< _TGradient, TScalar, TScalar > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - // Types from base itk::ImageFunction - typedef typename Superclass::InputType TInput; - typedef typename Superclass::OutputType TOutput; - typedef typename Superclass::PointType TPoint; - typedef typename Superclass::ContinuousIndexType TContIndex; - typedef typename Superclass::IndexType TIndex; - - public: - itkTypeMacro( GradientImageFunctionBase, itkImageFunction ); - - itkGetConstObjectMacro( Mask, TMask ); - itkSetConstObjectMacro( Mask, TMask ); - - public: - virtual void Prepare( ) const; - virtual TOutput Evaluate( const TPoint& p ) const cpExtensions_OVERRIDE; - virtual TOutput EvaluateAtIndex( const TIndex& i ) const cpExtensions_OVERRIDE; - virtual TOutput EvaluateAtContinuousIndex( const TContIndex& i ) const cpExtensions_OVERRIDE; - - protected: - GradientImageFunctionBase( ); - virtual ~GradientImageFunctionBase( ); - - virtual TOutput _Evaluate( const TIndex& i ) const = 0; - - private: - // Purposely not implemented. - GradientImageFunctionBase( const Self& ); - void operator=( const Self& ); - - protected: - typename _TMask::ConstPointer m_Mask; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/GradientImageFunctionBase.hxx b/lib/cpExtensions/Algorithms/GradientImageFunctionBase.hxx deleted file mode 100644 index a858650..0000000 --- a/lib/cpExtensions/Algorithms/GradientImageFunctionBase.hxx +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__HXX__ - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -void -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -Prepare( ) const -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -TOutput -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -Evaluate( const TPoint& p ) const -{ - TIndex i; - this->GetInputImage( )->TransformPhysicalPointToIndex( p, i ); - return( this->EvaluateAtIndex( i ) ); -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -TOutput -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -EvaluateAtIndex( const TIndex& i ) const -{ - bool eval = true; - if( this->m_Mask.IsNotNull( ) ) - eval = ( ( unsigned long )( this->m_Mask->GetPixel( i ) ) > 0 ); - if( eval ) - return( this->_Evaluate( i ) ); - else - return( TOutput( -1 ) ); -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -TOutput -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -EvaluateAtContinuousIndex( const TContIndex& i ) const -{ - TPoint p; - this->GetInputImage( )->TransformContinuousIndexToPhysicalPoint( i, p ); - return( this->Evaluate( p ) ); -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -GradientImageFunctionBase( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::GradientImageFunctionBase< _TGradient, _TMask >:: -~GradientImageFunctionBase( ) -{ -} - -#endif // __CPEXTENSIONS__ALGORITHMS__GRADIENTIMAGEFUNCTIONBASE__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/GulsunTekMedialness.h b/lib/cpExtensions/Algorithms/GulsunTekMedialness.h deleted file mode 100644 index 15add9e..0000000 --- a/lib/cpExtensions/Algorithms/GulsunTekMedialness.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__H__ -#define __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TGradient, class _TMask = itk::Image< unsigned char, _TGradient::ImageDimension > > - class GulsunTekMedialness - : public GradientImageFunctionBase< _TGradient, _TMask > - { - public: - typedef GulsunTekMedialness Self; - typedef GradientImageFunctionBase< _TGradient, _TMask > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - itkStaticConstMacro( Dimension, unsigned int, Superclass::Dimension ); - - typedef typename Superclass::TOutput TOutput; - typedef typename Superclass::TScalar TScalar; - typedef typename Superclass::TIndex TIndex; - typedef typename Superclass::TVector TVector; - typedef typename Superclass::TPoint TPoint; - typedef typename TIndex::OffsetType TOffset; - - typedef std::vector< double > TProfile; - typedef std::vector< TOffset > TOffsets; - - public: - itkNewMacro( Self ); - itkTypeMacro( GulsunTekMedialness, GradientImageFunctionBase ); - - itkGetConstMacro( MinRadius, double ); - itkGetConstMacro( MaxRadius, double ); - itkGetConstMacro( ProfileSampling, unsigned int ); - itkGetConstMacro( RadialSampling, unsigned int ); - - itkSetMacro( MinRadius, double ); - itkSetMacro( MaxRadius, double ); - itkSetMacro( ProfileSampling, unsigned int ); - itkSetMacro( RadialSampling, unsigned int ); - - protected: - GulsunTekMedialness( ); - virtual ~GulsunTekMedialness( ); - - virtual TOutput _Evaluate( const TIndex& i ) const cpExtensions_OVERRIDE; - - private: - // Purposely not implemented. - GulsunTekMedialness( const Self& ); - void operator=( const Self& ); - - protected: - double m_MinRadius; - double m_MaxRadius; - unsigned int m_ProfileSampling; - unsigned int m_RadialSampling; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/GulsunTekMedialness.hxx b/lib/cpExtensions/Algorithms/GulsunTekMedialness.hxx deleted file mode 100644 index fc59929..0000000 --- a/lib/cpExtensions/Algorithms/GulsunTekMedialness.hxx +++ /dev/null @@ -1,114 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__HXX__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::GulsunTekMedialness< _TGradient, _TMask >:: -GulsunTekMedialness( ) - : Superclass( ), - m_MinRadius( double( 0 ) ), - m_MaxRadius( double( 1 ) ), - m_ProfileSampling( 4 ), - m_RadialSampling( 10 ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::GulsunTekMedialness< _TGradient, _TMask >:: -~GulsunTekMedialness( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename cpExtensions::Algorithms::GulsunTekMedialness< _TGradient, _TMask >:: -TOutput cpExtensions::Algorithms::GulsunTekMedialness< _TGradient, _TMask >:: -_Evaluate( const TIndex& i ) const -{ - itk::Object::GlobalWarningDisplayOff( ); - - // Various values - const _TGradient* in = this->GetInputImage( ); - double pi2n = - double( 2 ) * double( vnl_math::pi ) / - double( this->m_ProfileSampling ); - double rOff = this->m_MaxRadius / double( this->m_RadialSampling - 1 ); - double optR = double( 0 ); - TPoint pnt; - in->TransformIndexToPhysicalPoint( i, pnt ); - - // Main loop - for( unsigned int cx = 0; cx < Self::Dimension - 1; cx++ ) - { - for( unsigned int cy = cx + 1; cy < Self::Dimension; cy++ ) - { - TProfile maxProfile( this->m_RadialSampling, double( 0 ) ); - for( unsigned int p = 0; p < this->m_ProfileSampling; p++ ) - { - double a = pi2n * double( p ); - - // Direction of this profile - TVector dir; - dir.Fill( TScalar( 0 ) ); - dir[ cx ] = TScalar( std::cos( a ) ); - dir[ cy ] = TScalar( std::sin( a ) ); - - double maxrise = double( 0 ); - double maxfall = double( -1 ); - TProfile profile; - for( unsigned int r = 0; r < this->m_RadialSampling; r++ ) - { - double radius = double( r ) * rOff; - TIndex idx; - typename TPoint::VectorType aux; - aux.SetVnlVector( dir.GetVnlVector( ) ); - if( - in->TransformPhysicalPointToIndex( pnt + ( aux * radius ), idx ) - ) - { - TVector g = in->GetPixel( idx ); - double b = double( g.GetNorm( ) ); - if( double( g * dir ) < double( 0 ) ) - b *= double( -1 ); - maxrise = ( b > maxrise )? b: maxrise; - if( radius >= this->m_MinRadius ) - maxfall = ( b < maxfall )? b: maxfall; - profile.push_back( -b - maxrise ); - } - else - profile.push_back( double( 0 ) ); - - } // rof - - for( unsigned int r = 0; r < this->m_RadialSampling; r++ ) - { - double E = profile[ r ] / -maxfall; - E = ( E < double( 0 ) )? double( 0 ): E; - E = ( E > double( 1 ) )? double( 1 ): E; - maxProfile[ r ] += E; - - } // rof - - } // rof - - for( unsigned int r = 0; r < this->m_RadialSampling; r++ ) - { - double E = maxProfile[ r ] / double( this->m_RadialSampling ); - optR = ( E > optR )? E: optR; - - } // rof - - } // rof - - } // rof - return( TScalar( optR ) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__GULSUNTEKMEDIALNESS__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageBlender.cxx b/lib/cpExtensions/Algorithms/ImageBlender.cxx deleted file mode 100644 index 5a12cd0..0000000 --- a/lib/cpExtensions/Algorithms/ImageBlender.cxx +++ /dev/null @@ -1,234 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Algorithms::ImageBlender:: -Self* cpExtensions::Algorithms::ImageBlender:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Algorithms::ImageBlender:: -GetNumberOfInputs( ) -{ - unsigned int np = this->GetNumberOfInputPorts( ); - unsigned int ni = 0; - for( unsigned int p = 0; p < np; ++p ) - ni += this->GetNumberOfInputConnections( p ); - return( ni ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Algorithms::ImageBlender:: -ImageBlender( ) - : Superclass( ) -{ - this->SetNumberOfInputPorts( 1 ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Algorithms::ImageBlender:: -~ImageBlender( ) -{ -} - -// ------------------------------------------------------------------------- -int cpExtensions::Algorithms::ImageBlender:: -RequestInformation( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - if( this->GetNumberOfInputConnections( 0 ) == 0 ) - return( 0 ); - - vtkDataObject::SetPointDataActiveScalarInfo( - outputVector->GetInformationObject( 0 ), - VTK_UNSIGNED_CHAR, - 1 - ); - return( 1 ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Algorithms::ImageBlender:: -RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - this->m_Ranges.clear( ); - for( int i = 0; i < this->GetNumberOfInputPorts( ); ++i ) - { - vtkInformationVector* portInfo = inputVector[ i ]; - for( int j = 0; j < portInfo->GetNumberOfInformationObjects( ); ++j ) - { - vtkInformation* info = portInfo->GetInformationObject( j ); - vtkImageData* image = vtkImageData::SafeDownCast( - info->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - if( image != NULL ) - { - double r[ 2 ]; - image->GetScalarRange( r ); - this->m_Ranges.push_back( r[ 0 ] ); - this->m_Ranges.push_back( r[ 1 ] ); - } - else - { - this->m_Ranges.push_back( double( 0 ) ); - this->m_Ranges.push_back( double( 0 ) ); - - } // fi - - } // rof - - } // rof - return( - this->Superclass::RequestData( request, inputVector, outputVector ) - ); -} - -// ------------------------------------------------------------------------- -// Description: -// This templated function executes the filter for any type of data. -template< class T > -void cpExtensions_Algorithms_ImageBlender_Execute( - cpExtensions::Algorithms::ImageBlender* self, - vtkImageData** inDatas, int numInputs, - const std::vector< double >& ranges, vtkImageData* outData, - int outExt[ 6 ], int id, T* really_not_used - ) -{ - vtkImageIterator< T > inItsFast[ 256 ]; - T* inSIFast[ 256 ]; - vtkImageProgressIterator< T > outIt( outData, outExt, self, id ); - vtkImageIterator< T >* inIts; - T** inSI; - if( numInputs < 256 ) - { - inIts = inItsFast; - inSI = inSIFast; - } - else - { - inIts = new vtkImageIterator< T >[ numInputs ]; - inSI = new T*[ numInputs ]; - - } // fi - - // Loop through all input ImageData to initialize iterators - for( int i = 0; i < numInputs; ++i ) - inIts[ i ].Initialize( inDatas[ i ], outExt ); - - // Loop through output pixels - while( !outIt.IsAtEnd( ) ) - { - for( int j = 0; j < numInputs; ++j ) - inSI[ j ] = inIts[ j ].BeginSpan( ); - - T* outSI = outIt.BeginSpan( ); - T* outSIEnd = outIt.EndSpan( ); - - // Pixel operation - while( outSI != outSIEnd ) - { - // Input 0 is ignored: it is just used to guarantee sizes all over - // the result - int vmax = 0; - for( int k = 0; k < numInputs; ++k ) - if( double( *inSI[ k ] ) > ranges[ k << 1 ] && vmax <= k ) - vmax = k + 1; - *outSI = static_cast< T >( vmax ); - outSI++; - for( int l = 0; l < numInputs; ++l ) - inSI[ l ]++; - - } // elihw - for( int j = 0; j < numInputs; ++j ) - inIts[ j ].NextSpan( ); - outIt.NextSpan( ); - - } // elihw - - if( numInputs >= 256) - { - delete [] inIts; - delete [] inSI; - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Algorithms::ImageBlender:: -ThreadedRequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector, - vtkImageData*** inData, vtkImageData** outData, - int outExt[ 6 ], int id - ) -{ - if( inData[ 0 ][ 0 ] == NULL ) - { - vtkErrorMacro( << "Input " << 0 << " must be specified." ); - return; - - } // fi - - int numInputs = this->GetNumberOfInputConnections( 0 ); - int scalarType = inData[ 0 ][ 0 ]->GetScalarType( ); - int numComp = inData[ 0 ][ 0 ]->GetNumberOfScalarComponents( ); - for( int i = 0; i < numInputs; ++i ) - { - int otherType = inData[ 0 ][ i ]->GetScalarType( ); - int otherComp = inData[ 0 ][ i ]->GetNumberOfScalarComponents( ); - if( otherType != scalarType || otherComp != numComp ) - { - if( id == 0 ) - vtkErrorMacro( - "ThreadedRequestData: Input " << i - << " has " << otherComp << " components of type " - << otherType << ", but input 0 has " << numComp - << " components of type " << scalarType - ); - return; - - } // fi - - } // rof - - switch( scalarType ) - { - vtkTemplateMacro( - cpExtensions_Algorithms_ImageBlender_Execute( - this, inData[ 0 ], numInputs, this->m_Ranges, - outData[ 0 ], outExt, id, static_cast< VTK_TT* >( 0 ) - ) - ); - default: - if( id == 0 ) - vtkErrorMacro( << "Execute: Unknown ScalarType" ); - return; - } // hctiws -} - -// ------------------------------------------------------------------------- -int cpExtensions::Algorithms::ImageBlender:: -FillInputPortInformation( int i, vtkInformation* info ) -{ - info->Set( vtkAlgorithm::INPUT_IS_REPEATABLE( ), 1 ); - return( this->Superclass::FillInputPortInformation( i,info ) ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageBlender.h b/lib/cpExtensions/Algorithms/ImageBlender.h deleted file mode 100644 index 4d82bcf..0000000 --- a/lib/cpExtensions/Algorithms/ImageBlender.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef __cpExtensions__Algorithms__ImageBlender__h__ -#define __cpExtensions__Algorithms__ImageBlender__h__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - * @note: Based on vtkImageWeightedSum - */ - class cpExtensions_EXPORT ImageBlender - : public vtkThreadedImageAlgorithm - { - public: - typedef ImageBlender Self; - vtkTypeMacro( ImageBlender, vtkThreadedImageAlgorithm ); - - public: - static Self* New( ); - - unsigned int GetNumberOfInputs( ); - - protected: - ImageBlender( ); - virtual ~ImageBlender( ); - - int RequestInformation( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ); - int RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ); - void ThreadedRequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector, - vtkImageData*** inData, vtkImageData** outData, - int outExt[ 6 ], int id - ); - int FillInputPortInformation( int i, vtkInformation* info ); - - private: - // Purposely not implemented. - ImageBlender( const Self& other ); - void operator=( const Self& other ); - - protected: - std::vector< double > m_Ranges; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Algorithms__ImageBlender__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageFunctionFilter.h b/lib/cpExtensions/Algorithms/ImageFunctionFilter.h deleted file mode 100644 index 503f791..0000000 --- a/lib/cpExtensions/Algorithms/ImageFunctionFilter.h +++ /dev/null @@ -1,69 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__H__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TInput, class _TOutput, class _TFunction > - class ImageFunctionFilter - : public itk::ImageToImageFilter< _TInput, _TOutput > - { - public: - typedef ImageFunctionFilter Self; - typedef itk::ImageToImageFilter< _TInput, _TOutput > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TInput TInput; - typedef _TOutput TOutput; - typedef _TFunction TFunction; - - typedef typename TOutput::RegionType TRegion; - - public: - itkNewMacro( Self ); - itkTypeMacro( ImageFunctionFilter, itkImageToImageFilter ); - - itkGetObjectMacro( Function, TFunction ); - itkSetObjectMacro( Function, TFunction ); - - protected: - ImageFunctionFilter( ); - virtual ~ImageFunctionFilter( ); - - virtual void BeforeThreadedGenerateData( ) cpExtensions_OVERRIDE; - virtual void ThreadedGenerateData( - const TRegion& region, - itk::ThreadIdType threadId - ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented. - ImageFunctionFilter( const Self& ); - void operator=( const Self& ); - - protected: - typename TFunction::Pointer m_Function; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageFunctionFilter.hxx b/lib/cpExtensions/Algorithms/ImageFunctionFilter.hxx deleted file mode 100644 index c96c092..0000000 --- a/lib/cpExtensions/Algorithms/ImageFunctionFilter.hxx +++ /dev/null @@ -1,67 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__HXX__ - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TInput, class _TOutput, class _TFilter > -cpExtensions::Algorithms::ImageFunctionFilter< _TInput, _TOutput, _TFilter >:: -ImageFunctionFilter( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInput, class _TOutput, class _TFilter > -cpExtensions::Algorithms::ImageFunctionFilter< _TInput, _TOutput, _TFilter >:: -~ImageFunctionFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInput, class _TOutput, class _TFilter > -void cpExtensions::Algorithms::ImageFunctionFilter< _TInput, _TOutput, _TFilter >:: -BeforeThreadedGenerateData( ) -{ - if( this->m_Function.IsNull( ) ) - itkExceptionMacro( << "Please set a valid itk::ImageFunction" ); - this->m_Function->SetInputImage( this->GetInput( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TInput, class _TOutput, class _TFilter > -void cpExtensions::Algorithms::ImageFunctionFilter< _TInput, _TOutput, _TFilter >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) -{ - const typename TRegion::SizeType& regionSize = region.GetSize( ); - if( regionSize[ 0 ] == 0 ) - return; - const _TInput* in = this->GetInput( ); - _TOutput* out = this->GetOutput( 0 ); - - itk::ProgressReporter pr( this, threadId, region.GetNumberOfPixels( ) ); - - // Define the iterators - itk::ImageRegionConstIteratorWithIndex< TInput > iIt( in, region ); - itk::ImageRegionIteratorWithIndex< TOutput > oIt( out, region ); - - iIt.GoToBegin( ); - oIt.GoToBegin( ); - for( ; !iIt.IsAtEnd( ) && !oIt.IsAtEnd( ); ++iIt, ++oIt ) - { - oIt.Set( this->m_Function->EvaluateAtIndex( iIt.GetIndex( ) ) ); - pr.CompletedPixel( ); - - } // rof -} - -#endif // __CPEXTENSIONS__ALGORITHMS__IMAGEFUNCTIONFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageFunctorFilter.h b/lib/cpExtensions/Algorithms/ImageFunctorFilter.h deleted file mode 100644 index c1a32b0..0000000 --- a/lib/cpExtensions/Algorithms/ImageFunctorFilter.h +++ /dev/null @@ -1,68 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__ImageFunctorFilter__h__ -#define __cpExtensions__Algorithms__ImageFunctorFilter__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TInputImage, class _TOutputImage > - class ImageFunctorFilter - : public itk::ImageToImageFilter< I, O > - { - public: - typedef ImageFunctorFilter Self; - typedef itk::ImageToImageFilter< I, O > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TInputImage TInputImage; - typedef _TOutputImage TOutputImage; - typedef typename TInputImage::PixelType TInputPixel; - typedef typename TOutputImage::PixelType TOutputPixel; - typedef typename TOutputImage::RegionType TRegion; - - typedef itk::FunctionBase< TInputPixel, TOutputPixel > TFunctor; - - public: - itkNewMacro( Self ); - itkTypeMacro( ImageFunctorFilter, itkImageToImageFilter ); - - itkGetObjectMacro( Functor, TFunctor ); - itkGetConstObjectMacro( Functor, TFunctor ); - itkSetObjectMacro( Functor, TFunctor ); - - protected: - ImageFunctorFilter( ); - virtual ~ImageFunctorFilter( ); - - virtual void ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) override; - - private: - // Purposely not implemented. - ImageFunctorFilter( const Self& ); - void operator=( const Self& ); - - protected: - typename TFunctor::Pointer m_Functor; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__ImageFunctorFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageFunctorFilter.hxx b/lib/cpExtensions/Algorithms/ImageFunctorFilter.hxx deleted file mode 100644 index 73777da..0000000 --- a/lib/cpExtensions/Algorithms/ImageFunctorFilter.hxx +++ /dev/null @@ -1,65 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__ImageFunctorFilter__hxx__ -#define __cpExtensions__Algorithms__ImageFunctorFilter__hxx__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TInputImage, class _TOutputImage > -cpExtensions::Algorithms::ImageFunctorFilter< _TInputImage, _TOutputImage >:: -ImageFunctorFilter( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage, class _TOutputImage > -cpExtensions::Algorithms::ImageFunctorFilter< _TInputImage, _TOutputImage >:: -~ImageFunctorFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage, class _TOutputImage > -void -cpExtensions::Algorithms::ImageFunctorFilter< _TInputImage, _TOutputImage >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) -{ - // Configure data for this thread - const typename TRegion::SizeType& regionSize = region.GetSize( ); - if( regionSize[ 0 ] == 0 ) - return; - const TInputImage* in = this->GetInput( ); - TOutputImage* out = this->GetOutput( 0 ); - const size_t nLines = region.GetNumberOfPixels( ) / regionSize[ 0 ]; - itk::ProgressReporter progress( this, threadId, nLines ); - - // Iterate over this region - itk::ImageScanlineConstIterator< TInputImage > iIt( in, region ); - itk::ImageScanlineIterator< TOutputImage > oIt( out, region ); - iIt.GoToBegin( ); - oIt.GoToBegin( ); - while( !iIt.IsAtEnd( ) ) - { - while( !iIt.IsAtEndOfLine( ) ) - { - oIt.Set( this->m_Functor->Evaluate( iIt.Get( ) ) ); - ++iIt; - ++oIt; - - } // elihw - iIt.NextLine( ); - oIt.NextLine( ); - progress.CompletedPixel( ); - - } // elihw -} - -#endif // __cpExtensions__Algorithms__ImageFunctorFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.h b/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.h deleted file mode 100644 index b970df4..0000000 --- a/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.h +++ /dev/null @@ -1,78 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__h__ -#define __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TImage > - class ImageToBoundingBoxFromThreshold - : public itk::Object - { - public: - typedef ImageToBoundingBoxFromThreshold Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TImage TImage; - typedef typename TImage::PixelType TPixel; - typedef typename TImage::IndexType TIndex; - typedef typename TImage::RegionType TRegion; - - public: - itkNewMacro( Self ); - itkTypeMacro( ImageToBoundingBoxFromThreshold, itkObject ); - - itkGetConstObjectMacro( Image, TImage ); - itkGetConstMacro( LowerThreshold, TPixel ); - itkGetConstMacro( UpperThreshold, TPixel ); - itkGetConstMacro( Region, TRegion ); - itkGetConstMacro( PAD, unsigned int ); - - itkSetConstObjectMacro( Image, TImage ); - itkSetMacro( LowerThreshold, TPixel ); - itkSetMacro( UpperThreshold, TPixel ); - itkSetMacro( Region, TRegion ); - itkSetMacro( PAD, unsigned int ); - - public: - void Compute( ); - - protected: - ImageToBoundingBoxFromThreshold( ); - virtual ~ImageToBoundingBoxFromThreshold( ); - - private: - // Purposely not implemented. - ImageToBoundingBoxFromThreshold( const Self& ); - void operator=( const Self& ); - - protected: - typename TImage::ConstPointer m_Image; - TPixel m_LowerThreshold; - TPixel m_UpperThreshold; - TRegion m_Region; - unsigned int m_PAD; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.hxx b/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.hxx deleted file mode 100644 index 55659eb..0000000 --- a/lib/cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold.hxx +++ /dev/null @@ -1,89 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__hxx__ -#define __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__hxx__ - -#include -#include - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::ImageToBoundingBoxFromThreshold< _TImage >:: -Compute( ) -{ - typedef itk::ImageRegionConstIteratorWithIndex< _TImage > _TIt; - - TIndex min_idx, max_idx; - min_idx.Fill( 0 ); - max_idx.Fill( -1 ); - - if( this->m_Image.IsNotNull( ) ) - { - auto region = this->m_Image->GetRequestedRegion( ); - min_idx = max_idx = region.GetIndex( ); - min_idx += region.GetSize( ); - - _TIt i( this->m_Image, region ); - for( i.GoToBegin( ); !i.IsAtEnd( ); ++i ) - { - auto v = i.Get( ); - if( this->m_LowerThreshold <= v && v <= this->m_UpperThreshold ) - { - auto idx = i.GetIndex( ); - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - { - min_idx[ d ] = ( idx[ d ] < min_idx[ d ] )? idx[ d ]: min_idx[ d ]; - max_idx[ d ] = ( idx[ d ] > max_idx[ d ] )? idx[ d ]: max_idx[ d ]; - - } // rof - - } // fi - - } // rof - - // Fix indices - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - { - min_idx[ d ] -= long( this->m_PAD ); - max_idx[ d ] += long( this->m_PAD ); - - if( min_idx[ d ] < region.GetIndex( )[ d ] ) - min_idx[ d ] = region.GetIndex( )[ d ]; - if( max_idx[ d ] > region.GetIndex( )[ d ] + region.GetSize( )[ d ] ) - max_idx[ d ] = region.GetIndex( )[ d ] + region.GetSize( )[ d ]; - - } // rof - - } // fi - - typename _TImage::SizeType size; - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - size[ d ] = max_idx[ d ] - min_idx[ d ] + 1; - - this->m_Region.SetIndex( min_idx ); - this->m_Region.SetSize( size ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::ImageToBoundingBoxFromThreshold< _TImage >:: -ImageToBoundingBoxFromThreshold( ) - : Superclass( ), - m_LowerThreshold( std::numeric_limits< TPixel >::min( ) ), - m_UpperThreshold( std::numeric_limits< TPixel >::max( ) ), - m_PAD( 0 ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::ImageToBoundingBoxFromThreshold< _TImage >:: -~ImageToBoundingBoxFromThreshold( ) -{ -} - -#endif // __cpExtensions__Algorithms__ImageToBoundingBoxFromThreshold__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/InertiaMedialness.h b/lib/cpExtensions/Algorithms/InertiaMedialness.h deleted file mode 100644 index e385513..0000000 --- a/lib/cpExtensions/Algorithms/InertiaMedialness.h +++ /dev/null @@ -1,215 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__INERTIAMEDIALNESS__H__ -#define __CPEXTENSIONS__ALGORITHMS__INERTIAMEDIALNESS__H__ - -#include -#include - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I, class S = float > - class InertiaMedialness - : public itk::ImageFunction< I, S, S > - { - public: - // Standard itk types - typedef InertiaMedialness Self; - typedef itk::ImageFunction< I, S, S > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - // Types from base itk::ImageFunction - typedef typename Superclass::InputType TInput; - typedef typename Superclass::OutputType TOutput; - typedef typename Superclass::PointType TPoint; - typedef typename Superclass::ContinuousIndexType TContIndex; - typedef typename Superclass::IndexType TIndex; - typedef typename TIndex::OffsetType TOffset; - - // Sparse buffer - typedef std::map< TIndex, TOutput, typename TIndex::LexicographicCompare > TBuffer; - - typedef InertiaTensorFunction< S, I::ImageDimension > TInertia; - - public: - itkNewMacro( Self ); - itkTypeMacro( InertiaMedialness, itkImageFunction ); - - itkBooleanMacro( BufferResults ); - itkGetConstMacro( BufferResults, bool ); - itkGetConstMacro( MaxRadius, double ); - - itkSetMacro( BufferResults, bool ); - itkSetMacro( MaxRadius, double ); - - public: - virtual void ResetBuffer( ) - { - this->m_Buffer.clear( ); - } - - virtual TOutput Evaluate( const TPoint& p ) const - { - TIndex i; - this->GetInputImage( )->TransformPhysicalPointToIndex( p, i ); - return( this->EvaluateAtIndex( i ) ); - } - - virtual TOutput EvaluateAtIndex( const TIndex& i ) const - { - TOutput res = TOutput( 0 ); - bool computed = false; - if( this->m_BufferResults ) - { - typename TBuffer::const_iterator bIt = this->m_Buffer.find( i ); - computed = ( bIt != this->m_Buffer.end( ) ); - res = ( computed )? bIt->second: res; - - } // fi - - if( !computed ) - res = this->_Evaluate( i ); - - if( this->m_BufferResults ) - this->m_Buffer[ i ] = res; - return( res ); - } - - virtual TOutput EvaluateAtContinuousIndex( const TContIndex& i ) const - { - TPoint p; - this->GetInputImage( )->TransformContinuousIndexToPhysicalPoint( i, p ); - return( this->Evaluate( p ) ); - } - - protected: - InertiaMedialness( ) - : Superclass( ), - m_BufferResults( false ), - m_MaxRadius( double( 1 ) ) - { - this->m_Buffer.clear( ); - } - - virtual ~InertiaMedialness( ) - { - this->m_Buffer.clear( ); - } - - virtual TOutput _Evaluate( const TIndex& idx ) const - { - const I* image = this->GetInputImage( ); - - typename I::PointType p_i; - image->TransformIndexToPhysicalPoint( idx, p_i ); - - typename I::PointType max_p, min_p; - for( unsigned int d = 0; d < I::ImageDimension; ++d ) - { - max_p[ d ] = p_i[ d ] + this->m_MaxRadius; - min_p[ d ] = p_i[ d ] - this->m_MaxRadius; - - } // rof - TIndex max_i, min_i; - image->TransformPhysicalPointToIndex( max_p, max_i ); - image->TransformPhysicalPointToIndex( min_p, min_i ); - - typename I::RegionType in_region = image->GetRequestedRegion( ); - TIndex in_index = in_region.GetIndex( ); - TIndex in_last = in_index + in_region.GetSize( ); - typename I::SizeType size; - for( unsigned int d = 0; d < I::ImageDimension; ++d ) - { - if( min_i[ d ] < in_index[ d ] ) min_i[ d ] = in_index[ d ]; - if( max_i[ d ] < in_index[ d ] ) max_i[ d ] = in_index[ d ]; - if( min_i[ d ] >= in_last[ d ] ) min_i[ d ] = in_last[ d ]; - if( max_i[ d ] >= in_last[ d ] ) max_i[ d ] = in_last[ d ]; - - size[ d ] = max_i[ d ] - min_i[ d ]; - - } // rof - - typename I::RegionType region; - region.SetIndex( min_i ); - region.SetSize( size ); - - std::vector< typename TInertia::Pointer > inertias; - itk::ImageRegionConstIteratorWithIndex< I > it( image, region ); - for( it.GoToBegin( ); !it.IsAtEnd( ); ++it ) - { - TOffset off = it.GetIndex( ) - idx; - unsigned long l1dist = std::abs( off[ 0 ] ); - for( unsigned int d = 1; d < I::ImageDimension; ++d ) - l1dist = ( std::abs( off[ d ] ) > l1dist )? std::abs( off[ d ] ): l1dist; - - typename TInertia::TPoint i_pnt; - image->TransformIndexToPhysicalPoint( it.GetIndex( ), i_pnt ); - - for( unsigned long l = 0; l < l1dist; ++l ) - { - if( inertias.size( ) <= l ) - inertias.push_back( TInertia::New( ) ); - inertias[ l ]->AddMass( i_pnt.GetVectorFromOrigin( ), S( it.Get( ) ) ); - - /* TODO - typename TInertias::iterator inIt = inertias.find( l ); - if( inIt == inertias.end( ) ) - inIt = inertias.insert( std::pair< unsigned long, typename TInertia::Pointer >( l, TInertia::New( ) ) ).first; - */ - - } // rof - - } // rof - - if( inertias.size( ) > 0 ) - { - S res = S( 0 ); - for( unsigned int l = 0; l < inertias.size( ); ++l ) - { - typename TInertia::TVector pv, r; - typename TInertia::TMatrix pm; - inertias[ l ]->GetEigenAnalysis( pm, pv, r ); - S v = pv.GetNorm( ); - if( l == 0 || v > res ) - res = v; - - } // rof - return( res ); - } - else - return( TOutput( 0 ) ); - } - - private: - // Purposely not implemented. - InertiaMedialness( const Self& ); - void operator=( const Self& ); - - protected: - mutable TBuffer m_Buffer; - bool m_BufferResults; - - double m_MaxRadius; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -// TODO: #include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__INERTIAMEDIALNESS__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/InertiaTensorFunction.h b/lib/cpExtensions/Algorithms/InertiaTensorFunction.h deleted file mode 100644 index ecb341d..0000000 --- a/lib/cpExtensions/Algorithms/InertiaTensorFunction.h +++ /dev/null @@ -1,180 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__INERTIATENSORFUNCTION__H__ -#define __CPEXTENSIONS__ALGORITHMS__INERTIATENSORFUNCTION__H__ - -#include - -#include -#include -#include -#include - - -#include -#include - - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class S, unsigned int D > - class InertiaTensorFunction - : public itk::Object - { - public: - // Standard itk types - typedef InertiaTensorFunction Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef S TScalar; - typedef itk::Matrix< S, D, D > TMatrix; - typedef itk::Point< S, D > TPoint; - typedef typename TPoint::VectorType TVector; - - protected: - typedef TMatrix _TInternalMatrix; - typedef itk::Matrix< S, D, 1 > _TInternalVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( InertiaTensorFunction, itkObject ); - - public: - inline void Reset( ) - { - this->m_M = S( 0 ); - this->m_MPP = S( 0 ); - this->m_MP.Fill( S( 0 ) ); - this->m_MPPT.Fill( S( 0 ) ); - this->Modified( ); - } - inline void AddMass( const TPoint& pnt, const S& mass = S( 1 ) ) - { - this->AddMass( pnt.GetVectorFromOrigin( ), mass ); - } - inline void AddMass( const S* data, const S& mass = S( 1 ) ) - { - this->AddMass( TVector( data ), mass ); - } - inline void AddMass( const TVector& vec, const S& mass = S( 1 ) ) - { - this->m_M += mass; - this->m_MPP += mass * ( vec * vec ); - - _TInternalVector mp; - for( unsigned int d = 0; d < D; ++d ) - { - this->m_MP[ d ][ 0 ] += mass * vec[ d ]; - mp[ d ][ 0 ] = vec[ d ]; - - } // rof - this->m_MPPT += - _TInternalMatrix( mp.GetVnlMatrix( ) * mp.GetTranspose( ) ) * - mass; - } - - inline S GetMass( ) const - { - return( this->m_M ); - } - - inline TMatrix GetInertia( ) const - { - TMatrix I; - if( S( 0 ) < this->m_M ) - { - I.SetIdentity( ); - I *= this->m_MPP - ( ( this->m_MP.GetTranspose( ) * this->m_MP.GetVnlMatrix( ) )[ 0 ][ 0 ] / this->m_M ); - I -= this->m_MPPT; - I += TMatrix( this->m_MP.GetVnlMatrix( ) * this->m_MP.GetTranspose( ) ) / this->m_M; - } - else - I.Fill( S( 0 ) ); - return( I ); - } - - inline TVector GetCenterOfGravity( ) const - { - TVector cog; - if( S( 0 ) < this->m_M ) - { - for( unsigned int d = 0; d < D; ++d ) - cog[ d ] = this->m_MP[ d ][ 0 ] / this->m_M; - } - else - cog.Fill( S( 0 ) ); - return( cog ); - } - - inline void GetEigenAnalysis( TMatrix& pm, TVector& pv, TVector& r ) const - { - TMatrix I = this->GetInertia( ); - - itk::SymmetricEigenAnalysis< TMatrix, TVector, TMatrix > eigen; - eigen.SetDimension( D ); - eigen.SetOrderEigenMagnitudes( true ); - eigen.SetOrderEigenValues( 1 ); - eigen.ComputeEigenValuesAndVectors( I, pv, pm ); - pm = TMatrix( pm.GetTranspose( ) ); - S det = vnl_determinant( pm.GetVnlMatrix( ) ); - for( unsigned int d = 0; d < D; ++d ) - pm[ d ][ D - 1 ] *= det; - - if( D == 2 ) - { - S coeff = S( 4 ) / this->m_M; - r[ 0 ] = std::sqrt( std::fabs( coeff * pv[ 1 ] ) ); - r[ 1 ] = std::sqrt( std::fabs( coeff * pv[ 0 ] ) ); - } - else if( D == 3 ) - { - S coeff = S( 2.5 ) / this->m_M; - r[ 0 ] = std::sqrt( std::fabs( coeff * ( pv[ 1 ] + pv[ 2 ] - pv[ 0 ] ) ) ); - r[ 1 ] = std::sqrt( std::fabs( coeff * ( pv[ 0 ] + pv[ 2 ] - pv[ 1 ] ) ) ); - r[ 2 ] = std::sqrt( std::fabs( coeff * ( pv[ 0 ] + pv[ 1 ] - pv[ 2 ] ) ) ); - } - else - r.Fill( S( 0 ) ); - } - - protected: - InertiaTensorFunction( ) - : Superclass( ) - { - this->Reset( ); - } - virtual ~InertiaTensorFunction( ) - { - } - - private: - // Purposely not implemented. - InertiaTensorFunction( const Self& ); - void operator=( const Self& ); - - protected: - S m_M; - S m_MPP; - _TInternalVector m_MP; - _TInternalMatrix m_MPPT; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -// #include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__INERTIATENSORFUNCTION__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/IsoImageSlicer.h b/lib/cpExtensions/Algorithms/IsoImageSlicer.h deleted file mode 100644 index 9190430..0000000 --- a/lib/cpExtensions/Algorithms/IsoImageSlicer.h +++ /dev/null @@ -1,185 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__H__ -#define __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class R, class I > - class BaseImageSlicer - : public itk::ImageToImageFilter< typename R::InputImageType, itk::Image< typename R::InputImageType::PixelType, R::ImageDimension - 1 > > - { - public: - // Basic types - typedef BaseImageSlicer Self; - typedef R TSlicer; - typedef I TInterpolateFunction; - typedef typename R::InputImageType TImage; - typedef typename I::CoordRepType TScalar; - typedef typename TImage::PixelType TPixel; - enum - { - Dim = TImage::ImageDimension, - SliceDim = TImage::ImageDimension - 1 - }; - typedef itk::Image< TPixel, Self::SliceDim > TSliceImage; - - // itk types - typedef itk::ImageToImageFilter< TImage, TSliceImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - // Internal filters - typedef itk::ExtractImageFilter< TImage, TSliceImage > TCollapsor; - - // Various types - typedef typename TImage::IndexType TIndex; - typedef typename TImage::RegionType TRegion; - typedef typename TImage::SizeType TSize; - typedef typename TImage::SpacingType TSpacing; - typedef typename TSpacing::ValueType TSpacingValue; - - typedef itk::AffineTransform< TScalar, Self::Dim > TTransform; - typedef typename TTransform::MatrixType TMatrix; - typedef typename TTransform::OffsetType TVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( BaseImageSlicer, itkImageToImageFilter ); - - itkBooleanMacro( SizeFromMaximum ); - itkBooleanMacro( SizeFromMinimum ); - itkBooleanMacro( SpacingFromMaximum ); - itkBooleanMacro( SpacingFromMinimum ); - - itkGetConstObjectMacro( Transform, TTransform ); - itkGetConstMacro( DefaultValue, TPixel ); - itkGetConstMacro( Size, TVector ); - itkGetConstMacro( SizeFromMaximum, bool ); - itkGetConstMacro( SizeFromMinimum, bool ); - itkGetConstMacro( Spacing, TSpacingValue ); - itkGetConstMacro( SpacingFromMaximum, bool ); - itkGetConstMacro( SpacingFromMinimum, bool ); - - itkSetObjectMacro( Transform, TTransform ); - itkSetMacro( Size, TVector ); - itkSetMacro( DefaultValue, TPixel ); - itkSetMacro( SizeFromMaximum, bool ); - itkSetMacro( SizeFromMinimum, bool ); - itkSetMacro( Spacing, TSpacingValue ); - itkSetMacro( SpacingFromMaximum, bool ); - itkSetMacro( SpacingFromMinimum, bool ); - - public: - virtual unsigned long GetMTime( ) const cpExtensions_OVERRIDE; - - const TInterpolateFunction* GetInterpolator( ) const; - const TMatrix& GetRotation( ) const; - const TVector& GetTranslation( ) const; - - void SetInterpolator( TInterpolateFunction* f ); - - template< class M > - void SetRotation( const M& r ); - - template< class V > - void SetTranslation( const V& t ); - void SetSize( TScalar s ); - - protected: - BaseImageSlicer( ); - virtual ~BaseImageSlicer( ); - - virtual void GenerateOutputInformation( ) cpExtensions_OVERRIDE; // TODO { } - virtual void GenerateInputRequestedRegion( ) cpExtensions_OVERRIDE; - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - BaseImageSlicer( const Self& ); - void operator=( const Self& ); - - protected: - typename TSlicer::Pointer m_Slicer; - typename TCollapsor::Pointer m_Collapsor; - typename TTransform::Pointer m_Transform; - - TPixel m_DefaultValue; - - TVector m_Size; - bool m_SizeFromMaximum; - bool m_SizeFromMinimum; - - TSpacingValue m_Spacing; - bool m_SpacingFromMaximum; - bool m_SpacingFromMinimum; - }; - - } // ecapseman - -} // ecapseman - -// ------------------------------------------------------------------------- -#define CPPLUGINS_DEFINE_ISOIMAGESLICER( name, R, F ) \ - template< class I, class S = double > \ - class name \ - : public BaseImageSlicer< R< I, I, S >, F< I, S > > \ - { \ - public: \ - typedef BaseImageSlicer< R< I, I, S >, F< I, S > > Superclass; \ - typedef name Self; \ - typedef itk::SmartPointer< Self > Pointer; \ - typedef itk::SmartPointer< const Self > ConstPointer; \ - public: \ - itkNewMacro( Self ); \ - itkTypeMacro( name, BaseSlicer ); \ - protected: \ - name( ) : Superclass( ) { } \ - virtual ~name( ) { } \ - private: \ - name( const Self& ); \ - void operator=( const Self& ); \ - }; - -namespace cpExtensions -{ - namespace Algorithms - { - CPPLUGINS_DEFINE_ISOIMAGESLICER( - IsoImageSlicer, - itk::ResampleImageFilter, - itk::InterpolateImageFunction - ); - CPPLUGINS_DEFINE_ISOIMAGESLICER( - VectorIsoImageSlicer, - itk::VectorResampleImageFilter, - itk::VectorInterpolateImageFunction - ); - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/IsoImageSlicer.hxx b/lib/cpExtensions/Algorithms/IsoImageSlicer.hxx deleted file mode 100644 index 041d874..0000000 --- a/lib/cpExtensions/Algorithms/IsoImageSlicer.hxx +++ /dev/null @@ -1,234 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__HXX__ - -// ------------------------------------------------------------------------- -template< class R, class I > -unsigned long cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GetMTime( ) const -{ - unsigned long t = this->Superclass::GetMTime( ); - unsigned long sT = this->m_Slicer->GetMTime( ); - unsigned long cT = this->m_Collapsor->GetMTime( ); - unsigned long tT = this->m_Transform->GetMTime( ); - t = ( sT > t )? sT: t; - t = ( cT > t )? cT: t; - t = ( tT > t )? tT: t; - return( t ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -const typename cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -TInterpolateFunction* -cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GetInterpolator( ) const -{ - return( this->m_Slicer->GetInterpolator( ) ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -const typename cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -TMatrix& cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GetRotation( ) const -{ - return( this->m_Transform->GetMatrix( ) ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -const typename cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -TVector& cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GetTranslation( ) const -{ - return( this->m_Transform->GetOffset( ) ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -SetInterpolator( TInterpolateFunction* f ) -{ - this->m_Slicer->SetInterpolator( f ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -template< class M > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -SetRotation( const M& r ) -{ - TMatrix rotation; - for( unsigned int i = 0; i < Self::Dim; ++i ) - for( unsigned int j = 0; j < Self::Dim; ++j ) - rotation[ i ][ j ] = r[ i ][ j ]; - this->m_Transform->SetMatrix( rotation ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -template< class V > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -SetTranslation( const V& t ) -{ - TVector off; - for( unsigned int i = 0; i < Self::Dim; ++i ) - off[ i ] = t[ i ]; - this->m_Transform->SetOffset( off ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -SetSize( TScalar s ) -{ - this->m_Size.Fill( s ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -BaseImageSlicer( ) - : Superclass( ), - m_SizeFromMaximum( false ), - m_SizeFromMinimum( false ), - m_Spacing( TSpacingValue( 1 ) ), - m_SpacingFromMaximum( false ), - m_SpacingFromMinimum( false ) -{ - this->m_Size.Fill( TScalar( 1 ) ); - - // Slicer - this->m_Slicer = TSlicer::New( ); - - TIndex idx; - idx.Fill( 0 ); - this->m_Slicer->SetOutputStartIndex( idx ); - - // Dimension collapsor - this->m_Collapsor = TCollapsor::New( ); - this->m_Collapsor->SetInput( this->m_Slicer->GetOutput( ) ); - this->m_Collapsor->SetDirectionCollapseToIdentity( ); - - this->m_Transform = TTransform::New( ); - this->m_Transform->SetIdentity( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -~BaseImageSlicer( ) -{ -} - -// ------------------------------------------------------------------------- -template< class R, class I > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GenerateOutputInformation( ) -{ -} - -// ------------------------------------------------------------------------- -template< class R, class I > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GenerateInputRequestedRegion( ) -{ - TImage* input = const_cast< TImage* >( this->GetInput( ) ); - if( input != NULL ) - input->SetRequestedRegionToLargestPossibleRegion( ); -} - -// ------------------------------------------------------------------------- -template< class R, class I > -void cpExtensions::Algorithms::BaseImageSlicer< R, I >:: -GenerateData( ) -{ - const TImage* input = this->GetInput( ); - - // Spacing - TSpacing spac; - if( this->m_SpacingFromMaximum || this->m_SpacingFromMinimum ) - { - spac = input->GetSpacing( ); - TSpacingValue minIso = spac[ 0 ]; - TSpacingValue maxIso = spac[ 0 ]; - for( unsigned int i = 1; i < Self::Dim; i++ ) - { - minIso = ( spac[ i ] < minIso )? spac[ i ]: minIso; - maxIso = ( spac[ i ] > maxIso )? spac[ i ]: maxIso; - - } // rof - this->m_Spacing = ( this->m_SpacingFromMinimum )? minIso: maxIso; - - } // fi - spac.Fill( this->m_Spacing ); - - // Size and origin - if( this->m_SizeFromMaximum || this->m_SizeFromMinimum ) - { - TSize iSize = input->GetRequestedRegion( ).GetSize( ); - TSpacing iSpac = input->GetSpacing( ); - TScalar minSize = TScalar( iSize[ 0 ] ) * TScalar( iSpac[ 0 ] ); - TScalar maxSize = minSize; - for( unsigned int i = 1; i < Self::Dim; i++ ) - { - TScalar v = TScalar( iSize[ i ] ) * TScalar( iSpac[ i ] ); - minSize = ( v < minSize )? v: minSize; - maxSize = ( v > maxSize )? v: maxSize; - - } // rof - if( this->m_SizeFromMaximum ) - this->m_Size.Fill( maxSize ); - else - this->m_Size.Fill( minSize ); - - } // fi - - TSize size; - typename TSlicer::OriginPointType origin; - size[ 0 ] = 1; - origin[ 0 ] = 0; - for( unsigned int i = 1; i < Self::Dim; i++ ) - { - double s = double( this->m_Size[ i ] ) / double( spac[ i ] ); - size[ i ] = ( unsigned int )( s ); - origin[ i ] = -( 0.5 * this->m_Size[ i ] ); - - } // rof - - // Prepare slicer - this->m_Slicer->SetInput( input ); - this->m_Slicer->SetTransform( this->m_Transform ); - this->m_Slicer->SetOutputSpacing( spac ); - this->m_Slicer->SetOutputOrigin( origin ); - this->m_Slicer->SetSize( size ); - this->m_Slicer->SetDefaultPixelValue( this->m_DefaultValue ); - - // Slice! - // Note: UpdateLargestPossibleRegion( ) is used since we need the - // output regions to be updated at each filter call. - this->m_Slicer->UpdateLargestPossibleRegion( ); - - // Collapse result - TRegion region = this->m_Slicer->GetOutput( )->GetRequestedRegion( ); - TSize regionSize = region.GetSize( ); - regionSize[ 0 ] = 0; - region.SetSize( regionSize ); - this->m_Collapsor->SetExtractionRegion( region ); - - this->m_Collapsor->GraftOutput( this->GetOutput( ) ); - this->m_Collapsor->UpdateLargestPossibleRegion( ); - this->GraftOutput( this->m_Collapsor->GetOutput( ) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__ISOIMAGESLICER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.h b/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.h deleted file mode 100644 index b38e06e..0000000 --- a/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.h +++ /dev/null @@ -1,171 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__H__ -#define __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__H__ - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - * Recursive formulation taken from: - * http://lmb.informatik.uni-freiburg.de/lectures/mustererkennung/Englische_Folien/07_c_ME_en.pdf - */ - template< class _TScalar, unsigned int _VDimension > - class IterativeGaussianModelEstimator - : public itk::Object - { - public: - typedef IterativeGaussianModelEstimator Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TScalar TScalar; - itkStaticConstMacro( Dimension, unsigned int, _VDimension ); - - // Begin concept checking -#ifdef ITK_USE_CONCEPT_CHECKING - itkConceptMacro( - ScalarTypeHasFloatResolution, - ( itk::Concept::IsFloatingPoint< _TScalar > ) - ); -#endif - // End concept checking - - typedef itk::Matrix< TScalar, Dimension, Dimension > TMatrix; - typedef itk::Vector< TScalar, Dimension > TVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( IterativeGaussianModelEstimator, itkObject ); - - itkGetConstMacro( Mean, TVector ); - itkGetConstMacro( Covariance, TMatrix ); - itkGetConstMacro( UnbiasedCovariance, TMatrix ); - itkGetConstMacro( NumberOfSamples, unsigned long ); - - itkSetMacro( Mean, TVector ); - itkSetMacro( Covariance, TMatrix ); - itkSetMacro( NumberOfSamples, unsigned long ); - - public: - void Clear( ); - - template< class _TOtherScalar > - void AddSample( const _TOtherScalar& x1, ... ); - - template< class _TOtherScalar > - void AddSample( const _TOtherScalar* array ); - - template< class _TOtherScalar > - void AddSample( const vnl_vector< _TOtherScalar >& v ); - - template< class _TOtherScalar > - void AddSample( - const itk::CovariantVector< _TOtherScalar, _VDimension >& v - ); - - template< class _TOtherScalar > - void AddSample( const itk::Point< _TOtherScalar, _VDimension >& p ); - - template< class _TOtherScalar > - void AddSample( const itk::Vector< _TOtherScalar, _VDimension >& v ); - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( const _TOtherScalar& x1, ... ) const; - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( const _TOtherScalar* array ) const; - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( - const vnl_vector< _TOtherScalar >& v - ) const; - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( - const itk::CovariantVector< _TOtherScalar, _VDimension >& v - ) const; - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( - const itk::Point< _TOtherScalar, _VDimension >& p - ) const; - - template< class _TOtherScalar > - _TScalar SquaredMahalanobis( - const itk::Vector< _TOtherScalar, _VDimension >& v - ) const; - - template< class _TOtherScalar > - _TScalar Density( const _TOtherScalar& x1, ... ) const; - - template< class _TOtherScalar > - _TScalar Density( const _TOtherScalar* array ) const; - - template< class _TOtherScalar > - _TScalar Density( - const vnl_vector< _TOtherScalar >& v - ) const; - - template< class _TOtherScalar > - _TScalar Density( - const itk::CovariantVector< _TOtherScalar, _VDimension >& v - ) const; - - template< class _TOtherScalar > - _TScalar Density( - const itk::Point< _TOtherScalar, _VDimension >& p - ) const; - - template< class _TOtherScalar > - _TScalar Density( - const itk::Vector< _TOtherScalar, _VDimension >& v - ) const; - - protected: - IterativeGaussianModelEstimator( ); - virtual ~IterativeGaussianModelEstimator( ); - - protected: - void _AddSample( const TVector& v ) const; - _TScalar _SquaredMahalanobis( const TVector& v ) const; - _TScalar _Density( const TVector& v ) const; - - private: - // Purposely not implemented - IterativeGaussianModelEstimator( const Self& other ); - void operator=( const Self& other ); - - protected: - // Recursive avg/cov values - mutable unsigned long m_NumberOfSamples; - mutable TVector m_Mean; - mutable TMatrix m_Covariance; - mutable TMatrix m_UnbiasedCovariance; - mutable bool m_InverseUpdated; - mutable TMatrix m_InverseUnbiasedCovariance; - }; - - } // ecapseman - -} // ecapseman - -#include - -#endif // __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.hxx b/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.hxx deleted file mode 100644 index acd1da7..0000000 --- a/lib/cpExtensions/Algorithms/IterativeGaussianModelEstimator.hxx +++ /dev/null @@ -1,365 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__HXX__ - -#include - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Clear( ) -{ - this->m_NumberOfSamples = 0; - this->m_Mean.Fill( TScalar( 0 ) ); - this->m_Covariance.Fill( TScalar( 0 ) ); - this->m_InverseUpdated = false; - this->m_InverseUnbiasedCovariance.Fill( TScalar( 0 ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const _TOtherScalar& x1, ... ) -{ - TVector s; - std::va_list lst; - va_start( lst, x1 ); - s[ 0 ] = TScalar( x1 ); - for( unsigned int d = 1; d < _VDimension; ++d ) - s[ d ] = TScalar( va_arg( lst, double ) ); - va_end( lst ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const _TOtherScalar* array ) -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( array[ d ] ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const vnl_vector< _TOtherScalar >& v ) -{ - unsigned int len = ( v.size( ) < _VDimension )? v.size: _VDimension; - TVector s; - for( unsigned d = 0; d < len; ++d ) - s[ d ] = TScalar( v[ d ] ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const itk::CovariantVector< _TOtherScalar, _VDimension >& v ) -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const itk::Point< _TOtherScalar, _VDimension >& p ) -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( p[ d ] ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -AddSample( const itk::Vector< _TOtherScalar, _VDimension >& v ) -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - this->_AddSample( s ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( const _TOtherScalar& x1, ... ) const -{ - TVector s; - std::va_list lst; - va_start( lst, x1 ); - s[ 0 ] = TScalar( x1 ); - for( unsigned int d = 1; d < _VDimension; ++d ) - s[ d ] = TScalar( va_arg( lst, double ) ); - va_end( lst ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( const _TOtherScalar* array ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( array[ d ] ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( const vnl_vector< _TOtherScalar >& v ) const -{ - unsigned int len = ( v.size( ) < _VDimension )? v.size: _VDimension; - TVector s; - for( unsigned d = 0; d < len; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( - const itk::CovariantVector< _TOtherScalar, _VDimension >& v - ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( const itk::Point< _TOtherScalar, _VDimension >& p ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( p[ d ] ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -SquaredMahalanobis( const itk::Vector< _TOtherScalar, _VDimension >& v ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_SquaredMahalanobis( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( const _TOtherScalar& x1, ... ) const -{ - TVector s; - std::va_list lst; - va_start( lst, x1 ); - s[ 0 ] = TScalar( x1 ); - for( unsigned int d = 1; d < _VDimension; ++d ) - s[ d ] = TScalar( va_arg( lst, double ) ); - va_end( lst ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( const _TOtherScalar* array ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( array[ d ] ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( const vnl_vector< _TOtherScalar >& v ) const -{ - unsigned int len = ( v.size( ) < _VDimension )? v.size: _VDimension; - TVector s; - for( unsigned d = 0; d < len; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( - const itk::CovariantVector< _TOtherScalar, _VDimension >& v - ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( const itk::Point< _TOtherScalar, _VDimension >& p ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( p[ d ] ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -template< class _TOtherScalar > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -Density( const itk::Vector< _TOtherScalar, _VDimension >& v ) const -{ - TVector s; - for( unsigned d = 0; d < _VDimension; ++d ) - s[ d ] = TScalar( v[ d ] ); - return( this->_Density( s ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -IterativeGaussianModelEstimator( ) - : Superclass( ) -{ - this->Clear( ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -~IterativeGaussianModelEstimator( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -void cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -_AddSample( const TVector& v ) const -{ - this->m_NumberOfSamples += 1; - TScalar a = TScalar( 1 ) / TScalar( this->m_NumberOfSamples ); - TScalar b = TScalar( 1 ) - a; - TVector c = v - this->m_Mean; - TMatrix m; - for( unsigned int i = 0; i < _VDimension; ++i ) - { - m[ i ][ i ] = c[ i ] * c[ i ]; - for( unsigned int j = i + 1; j < _VDimension; ++j ) - m[ i ][ j ] = m[ j ][ i ] = c[ i ] * c[ j ]; - - } // rof - this->m_Covariance = ( this->m_Covariance + ( m * a ) ) * b; - this->m_Mean = ( this->m_Mean * b ) + ( v * a ); - - TScalar u = - TScalar( this->m_NumberOfSamples ) / - TScalar( this->m_NumberOfSamples - 1 ); - this->m_UnbiasedCovariance = this->m_Covariance * u; - this->m_InverseUpdated = false; -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -_SquaredMahalanobis( const TVector& v ) const -{ - if( !this->m_InverseUpdated ) - { - double d = - double( - vnl_determinant( this->m_UnbiasedCovariance.GetVnlMatrix( ) ) - ); - if( std::fabs( d ) > double( 0 ) ) - this->m_InverseUnbiasedCovariance = - this->m_UnbiasedCovariance.GetInverse( ); - else - this->m_InverseUnbiasedCovariance.SetIdentity( ); - this->m_InverseUpdated = true; - - } // fi - TVector x = v - this->m_Mean; - return( x * ( this->m_InverseUnbiasedCovariance * x ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar, unsigned int _VDimension > -_TScalar cpExtensions::Algorithms:: -IterativeGaussianModelEstimator< _TScalar, _VDimension >:: -_Density( const TVector& v ) const -{ - static const double _2pik = - std::pow( double( 2 ) * double( vnl_math::pi ), _VDimension ); - - double s = double( this->_SquaredMahalanobis( v ) ) / double( 2 ); - double d = - double( - vnl_determinant( this->m_UnbiasedCovariance.GetVnlMatrix( ) ) - ); - return( _TScalar( std::exp( -s ) / std::sqrt( _2pik * d ) ) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__ITERATIVEGAUSSIANMODELESTIMATOR__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanConstantFilter.cxx b/lib/cpExtensions/Algorithms/KalmanConstantFilter.cxx deleted file mode 100644 index 0fd5d6c..0000000 --- a/lib/cpExtensions/Algorithms/KalmanConstantFilter.cxx +++ /dev/null @@ -1,49 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#include - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanConstantFilter< T >:: -Configure( unsigned int m ) -{ - this->Superclass::Configure( m, 1, m ); -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanConstantFilter< T >:: -Initialize( ) -{ - this->Superclass::Initialize( ); - - this->m_A.set_identity( ); - this->m_B.fill( TScalar( 0 ) ); - this->m_H.set_identity( ); -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanConstantFilter< T >:: -KalmanConstantFilter( ) - : Superclass( ) -{ - this->Configure( 1 ); -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanConstantFilter< T >:: -~KalmanConstantFilter( ) -{ -} - -// ------------------------------------------------------------------------- -// Explicit instantiations - -template class cpExtensions::Algorithms::KalmanConstantFilter< float >; -template class cpExtensions::Algorithms::KalmanConstantFilter< double >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanConstantFilter.h b/lib/cpExtensions/Algorithms/KalmanConstantFilter.h deleted file mode 100644 index 82cd263..0000000 --- a/lib/cpExtensions/Algorithms/KalmanConstantFilter.h +++ /dev/null @@ -1,56 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__KALMANCONSTANTFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__KALMANCONSTANTFILTER__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< typename T > - class cpExtensions_EXPORT KalmanConstantFilter - : public KalmanFilter< T > - { - public: - typedef KalmanConstantFilter Self; - typedef KalmanFilter< T > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef typename Superclass::TScalar TScalar; - typedef typename Superclass::TMatrix TMatrix; - typedef typename Superclass::TVector TVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( KalmanConstantFilter, KalmanFilter ); - - public: - void Configure( unsigned int m ); - - // Iteration methods - virtual void Initialize( ) cpExtensions_OVERRIDE; - - protected: - KalmanConstantFilter( ); - virtual ~KalmanConstantFilter( ); - - private: - // Purposely not implemented. - KalmanConstantFilter( const Self& ); - void operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__KALMANCONSTANTFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanFilter.cxx b/lib/cpExtensions/Algorithms/KalmanFilter.cxx deleted file mode 100644 index add2041..0000000 --- a/lib/cpExtensions/Algorithms/KalmanFilter.cxx +++ /dev/null @@ -1,137 +0,0 @@ -#include - -#include -#include - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Configure( unsigned int s, unsigned int i, unsigned int m ) -{ - this->m_StateSize = s; - this->m_InputSize = i; - this->m_MeasureSize = m; - - // Matrices - this->m_A.set_size( s, s ); - this->m_B.set_size( s, i ); - this->m_H.set_size( m, s ); - this->m_Id.set_size( s, s ); - this->m_Q.set_size( s, s ); - this->m_R.set_size( m, m ); - this->m_P0.set_size( s, s ); - this->m_K.set_size( s, m ); - this->m_Pm.set_size( s, s ); - this->m_Pp.set_size( s, s ); - - // Vectors - this->m_x0.set_size( s ); - this->m_u.set_size( i ); - this->m_m.set_size( m ); - this->m_xm.set_size( s ); - this->m_xp.set_size( s ); - - // Static values - this->m_Id.set_identity( ); -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Initialize( ) -{ - // Set all to the first iteration - this->m_I = 0; - this->m_Step = Self::StFilt; -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Predict( ) -{ - if( this->m_Step == Self::StFilt ) - { - if( this->m_I == 0 ) - { - this->m_xp = this->m_x0; - this->m_Pp = this->m_P0; - - } // fi - - // Project the state - this->m_xm = ( this->m_A * this->m_xp ) + ( this->m_B * this->m_u ); - - // Project the error - this->m_Pm = this->m_A * this->m_Pp * this->m_A.transpose( ); - this->m_Pm += this->m_Q; - - this->m_Step = Self::StPred; - - } // fi -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Innovate( ) -{ - typedef vnl_matrix_inverse< T > _TInv; - - if( this->m_Step == Self::StPred ) - { - // Kalman gain - this->m_K = this->m_Pm * this->m_H.transpose( ); - this->m_K *= - _TInv( - ( this->m_H * this->m_Pm * this->m_H.transpose( ) ) + this->m_R - ); - - this->m_Step = Self::StInno; - - } // fi -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Filtrate( ) -{ - if( this->m_Step == Self::StInno ) - { - // A posteriori state - this->m_xp = this->m_xm; - this->m_xp += this->m_K * ( this->m_m - ( this->m_H * this->m_xm ) ); - - // A posteriori error - this->m_Pp = ( this->m_Id - ( this->m_K * this->m_H ) ) * this->m_Pm; - - this->m_Step = Self::StFilt; - this->m_I++; - - } // fi -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanFilter< T >:: -KalmanFilter( ) - : Superclass( ) -{ - this->Configure( 1, 1, 1 ); -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanFilter< T >:: -~KalmanFilter( ) -{ -} - -// ------------------------------------------------------------------------- -// Explicit instantiations - -template class cpExtensions::Algorithms::KalmanFilter< float >; -template class cpExtensions::Algorithms::KalmanFilter< double >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanFilter.h b/lib/cpExtensions/Algorithms/KalmanFilter.h deleted file mode 100644 index 0039620..0000000 --- a/lib/cpExtensions/Algorithms/KalmanFilter.h +++ /dev/null @@ -1,213 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__H__ - -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -#define kalmanGetSetMacro( type, name ) \ - itkGetConstMacro( name, type ); \ - itkSetMacro( name, type ); - -// ------------------------------------------------------------------------- -#define kalmanGetMatrixMacro( var, name ) \ - virtual const TMatrix& Get##name( ) const \ - { return( this->m_##var ); } - -// ------------------------------------------------------------------------- -#define kalmanSetMatrixMacro( var, name ) \ - virtual void Set##name( const TMatrix& m ) \ - { this->Set##var( m ); } - -// ------------------------------------------------------------------------- -#define kalmanGetSetMatrixMacro( var, name ) \ - kalmanGetMatrixMacro( var, name ); \ - kalmanSetMatrixMacro( var, name ); - -// ------------------------------------------------------------------------- -#define kalmanGetVectorMacro( var, name ) \ - virtual const TVector& Get##name( ) const \ - { return( this->m_##var ); } - -// ------------------------------------------------------------------------- -#define kalmanSetVectorMacro( var, name ) \ - virtual void Set##name( const TVector& v ) \ - { this->Set##var( v ); } - -// ------------------------------------------------------------------------- -#define kalmanGetSetVectorMacro( var, name ) \ - kalmanGetVectorMacro( var, name ); \ - kalmanSetVectorMacro( var, name ); - -namespace cpExtensions -{ - namespace Algorithms - { - /** - * Abstract class implementing the classical kalman filter. See - * http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf - * for a description of this algorithm. - */ - template< typename T > - class cpExtensions_EXPORT KalmanFilter - : public itk::Object - { - public: - typedef KalmanFilter Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - // Template parameters types - typedef T TScalar; - - // VNL types - typedef vnl_matrix< TScalar > TMatrix; - typedef vnl_vector< TScalar > TVector; - - // stage identificators - enum - { - StPred, - StInno, - StFilt - }; - - public: - itkNewMacro( Self ); - itkTypeMacro( KalmanFilter, itkObject ); - - // Values - itkGetConstMacro( StateSize, unsigned int ); - itkGetConstMacro( InputSize, unsigned int ); - itkGetConstMacro( MeasureSize, unsigned int ); - - // Matrices - kalmanGetSetMacro( TMatrix, A ); - kalmanGetSetMacro( TMatrix, B ); - kalmanGetSetMacro( TMatrix, H ); - kalmanGetSetMacro( TMatrix, Q ); - kalmanGetSetMacro( TMatrix, R ); - kalmanGetSetMacro( TMatrix, P0 ); - kalmanGetSetMacro( TMatrix, K ); - kalmanGetSetMacro( TMatrix, Pm ); - kalmanGetSetMacro( TMatrix, Pp ); - - // Vectors - kalmanGetSetMacro( TVector, x0 ); - kalmanGetSetMacro( TVector, u ); - kalmanGetSetMacro( TVector, m ); - kalmanGetSetMacro( TVector, xm ); - kalmanGetSetMacro( TVector, xp ); - - // Human-readable matrices - kalmanGetSetMatrixMacro( A, TransitionMatrix ); - kalmanGetSetMatrixMacro( B, InputControlMatrix ); - kalmanGetSetMatrixMacro( H, MeasureMatrix ); - kalmanGetSetMatrixMacro( Q, ProcessNoise ); - kalmanGetSetMatrixMacro( R, MeasureNoise ); - kalmanGetSetMatrixMacro( P0, InitialNoise ); - kalmanGetSetMatrixMacro( K, Gain ); - kalmanGetSetMatrixMacro( Pm, APrioriNoise ); - kalmanGetSetMatrixMacro( Pp, APosterioriNoise ); - - // Human-readable vectors - kalmanGetSetVectorMacro( x0, InitialState ); - kalmanGetSetVectorMacro( u, Input ); - kalmanGetSetVectorMacro( m, Measure ); - kalmanGetSetVectorMacro( xm, APrioriState ); - kalmanGetSetVectorMacro( xp, APosterioriState ); - - public: - - void Configure( unsigned int s, unsigned int i, unsigned int m ); - - // Iteration methods - virtual void Initialize( ); - virtual void Predict( ); - virtual void Innovate( ); - virtual void Filtrate( ); - virtual void OneStep( ) - { - this->Predict( ); - this->Innovate( ); - this->Filtrate( ); - } - virtual void NSteps( unsigned int n ) - { - for( unsigned int i = 0; i < n; i++ ) - this->OneStep( ); - } - unsigned int CurrentIteration( ) const - { return( this->m_I ); } - unsigned char CurrentStep( ) const - { return( this->m_Step ); } - - protected: - KalmanFilter( ); - virtual ~KalmanFilter( ); - - private: - // Purposely not implemented - KalmanFilter( const Self& ); - void operator=( const Self& ); - - protected: - // Filter dimensions - unsigned int m_StateSize; - unsigned int m_InputSize; - unsigned int m_MeasureSize; - - // Transition matrices - TMatrix m_A; // Transition - TMatrix m_B; // Input control - TMatrix m_H; // Measure - TMatrix m_Id; // Identity matrix - - // Noise matrices - TMatrix m_Q; // Process noise covariance - TMatrix m_R; // Measure noise covariance - - // Initial values - TVector m_x0; // Initial state - TMatrix m_P0; // Initial error covariance - - // Loop vectors - TVector m_u; // Last real input - TVector m_m; // Last real measure - TVector m_xm; // A priori state - TVector m_xp; // A posteriori state - - // Loop matrices - TMatrix m_K; // kalman gain - TMatrix m_Pm; // A priori error - TMatrix m_Pp; // A posteriori error - - // Loop values - unsigned int m_I; // Current iteration - unsigned char m_Step; // Current step within current iteration - - // ------------------------------------------------------------------- - // Classic kronecker product operator - // ------------------------------------------------------------------- - template< class M > - static void Kronecker( M& AkB, const M& A, const M& B ); - }; - - } // ecapseman - -} // ecapseman - -#include - -#endif // __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanFilter.hxx b/lib/cpExtensions/Algorithms/KalmanFilter.hxx deleted file mode 100644 index e81cae2..0000000 --- a/lib/cpExtensions/Algorithms/KalmanFilter.hxx +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__HXX__ - -// ------------------------------------------------------------------------- -template< typename T > -template< class M > -void cpExtensions::Algorithms::KalmanFilter< T >:: -Kronecker( M& AkB, const M& A, const M& B ) -{ - unsigned int m = A.rows( ); unsigned int n = A.cols( ); - unsigned int p = B.rows( ); unsigned int q = B.cols( ); - AkB.set_size( m * p, n * q ); - - for( unsigned int i = 1; i <= m; ++i ) - { - for( unsigned int j = 1; j <= n; ++j ) - { - for( unsigned int k = 1; k <= p; ++k ) - { - for( unsigned int l = 1; l <= q; ++l ) - { - unsigned int al = ( ( p * ( i - 1 ) ) + k ) - 1; - unsigned int be = ( ( q * ( j - 1 ) ) + l ) - 1; - AkB[ al ][ be ] = A[ i - 1 ][ j - 1 ] * B[ k - 1 ][ l - 1 ]; - - } // rof - - } // rof - - } // rof - - } // rof -} - -#endif // __CPEXTENSIONS__ALGORITHMS__KALMANFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanVelocityFilter.cxx b/lib/cpExtensions/Algorithms/KalmanVelocityFilter.cxx deleted file mode 100644 index a725e16..0000000 --- a/lib/cpExtensions/Algorithms/KalmanVelocityFilter.cxx +++ /dev/null @@ -1,90 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#include -#include - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -Configure( unsigned int m ) -{ - this->Superclass::Configure( m << 1, 1, m ); - - this->m_TimeOffset.set_size( 2, 2 ); - this->SetTimeOffset( TScalar( 1 ) ); - - this->m_Sigma.set_size( this->m_MeasureSize, this->m_MeasureSize ); - this->m_Sigma.set_identity( ); -} - -// ------------------------------------------------------------------------- -template< typename T > -typename cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -TScalar cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -GetTimeOffset( ) const -{ - return( TScalar( std::sqrt( double( this->m_TimeOffset[ 1 ][ 1 ] ) ) ) ); -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -SetTimeOffset( TScalar t ) -{ - TScalar t2 = t * t; - TScalar t3 = t2 * t; - TScalar t4 = t3 * t; - this->m_TimeOffset[ 0 ][ 0 ] = t4 / TScalar( 4 ); - this->m_TimeOffset[ 1 ][ 1 ] = t2; - - this->m_TimeOffset[ 0 ][ 1 ] = t3 / TScalar( 2 ); - this->m_TimeOffset[ 1 ][ 0 ] = this->m_TimeOffset[ 0 ][ 1 ]; -} - -// ------------------------------------------------------------------------- -template< typename T > -void cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -Initialize( ) -{ - this->Superclass::Initialize( ); - - Self::Kronecker( this->m_Q, this->m_Sigma, this->m_TimeOffset ); - - this->m_A.set_identity( ); - this->m_B.fill( TScalar( 0 ) ); - this->m_H.fill( TScalar( 0 ) ); - - TScalar tOff = this->GetTimeOffset( ); - for( unsigned int i = 0; i < this->m_MeasureSize; i++ ) - { - this->m_A[ i ][ this->m_MeasureSize + i ] = tOff; - this->m_H[ i ][ i ] = TScalar( 1 ); - - } // rof -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -KalmanVelocityFilter( ) - : Superclass( ) -{ - this->Configure( 1 ); -} - -// ------------------------------------------------------------------------- -template< typename T > -cpExtensions::Algorithms::KalmanVelocityFilter< T >:: -~KalmanVelocityFilter( ) -{ -} - -// ------------------------------------------------------------------------- -// Explicit instantiations - -template class cpExtensions::Algorithms::KalmanVelocityFilter< float >; -template class cpExtensions::Algorithms::KalmanVelocityFilter< double >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/KalmanVelocityFilter.h b/lib/cpExtensions/Algorithms/KalmanVelocityFilter.h deleted file mode 100644 index c32dde6..0000000 --- a/lib/cpExtensions/Algorithms/KalmanVelocityFilter.h +++ /dev/null @@ -1,66 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__KALMANVELOCITYFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__KALMANVELOCITYFILTER__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< typename T > - class cpExtensions_EXPORT KalmanVelocityFilter - : public KalmanFilter< T > - { - public: - typedef KalmanVelocityFilter Self; - typedef KalmanFilter< T > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef typename Superclass::TScalar TScalar; - typedef typename Superclass::TMatrix TMatrix; - typedef typename Superclass::TVector TVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( KalmanVelocityFilter, KalmanFilter ); - - kalmanGetSetMacro( TMatrix, Sigma ); - kalmanGetSetMatrixMacro( Sigma, AccelerationNoise ); - - public: - void Configure( unsigned int m ); - - TScalar GetTimeOffset( ) const; - void SetTimeOffset( TScalar t ); - - /// Iteration methods - virtual void Initialize( ) cpExtensions_OVERRIDE; - - protected: - KalmanVelocityFilter( ); - virtual ~KalmanVelocityFilter( ); - - private: - // Purposely not implemented. - KalmanVelocityFilter( const Self& ); - void operator=( const Self& ); - - protected: - TMatrix m_TimeOffset; - TMatrix m_Sigma; - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__KALMANVELOCITYFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/LightCompensationFilter.h b/lib/cpExtensions/Algorithms/LightCompensationFilter.h deleted file mode 100644 index a3c28ff..0000000 --- a/lib/cpExtensions/Algorithms/LightCompensationFilter.h +++ /dev/null @@ -1,65 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__H__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I > - class LightCompensationFilter - : public itk::InPlaceImageFilter< I, I > - { - public: - typedef LightCompensationFilter Self; - typedef itk::InPlaceImageFilter< I, I > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef I TImage; - typedef typename I::RegionType TRegion; - - typedef cpExtensions::Algorithms::ParallelImageMean< I > TMeanCalculator; - typedef typename TMeanCalculator::TMean TMean; - - public: - itkNewMacro( Self ); - itkTypeMacro( LightCompensationFilter, itkInPlaceImageFilter ); - - itkGetConstMacro( Mean, TMean ); - - protected: - LightCompensationFilter( ); - virtual ~LightCompensationFilter( ); - - private: - virtual void BeforeThreadedGenerateData( ); - virtual void ThreadedGenerateData( - const TRegion& region, itk::ThreadIdType id - ); - virtual void AfterThreadedGenerateData( ); - - protected: - TMean m_Mean; - TMean m_Coefficient; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/LightCompensationFilter.hxx b/lib/cpExtensions/Algorithms/LightCompensationFilter.hxx deleted file mode 100644 index f75ffcd..0000000 --- a/lib/cpExtensions/Algorithms/LightCompensationFilter.hxx +++ /dev/null @@ -1,96 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__HXX__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class I > -cpExtensions::Algorithms::LightCompensationFilter< I >:: -LightCompensationFilter( ) - : Superclass( ) -{ - this->SetNumberOfRequiredInputs( 1 ); - this->InPlaceOff( ); -} - -// ------------------------------------------------------------------------- -template< class I > -cpExtensions::Algorithms::LightCompensationFilter< I >:: -~LightCompensationFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::LightCompensationFilter< I >:: -BeforeThreadedGenerateData( ) -{ - this->Superclass::BeforeThreadedGenerateData( ); - - I* input = const_cast< I* >( this->GetInput( ) ); - - typename TMeanCalculator::Pointer mc = TMeanCalculator::New( ); - mc->Execute( input, input->GetRequestedRegion( ) ); - this->m_Mean = mc->GetMean( ); - - double gm = this->m_Mean[ 0 ] + this->m_Mean[ 1 ] + this->m_Mean[ 2 ]; - gm /= double( 3 ); - this->m_Coefficient = this->m_Mean; - this->m_Coefficient.Fill( gm ); - this->m_Coefficient[ 0 ] /= this->m_Mean[ 0 ]; - this->m_Coefficient[ 1 ] /= this->m_Mean[ 1 ]; - this->m_Coefficient[ 2 ] /= this->m_Mean[ 2 ]; -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::LightCompensationFilter< I >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType id ) -{ - typedef itk::NumericTraits< typename I::PixelType > _TPixelTraits; - typedef typename _TPixelTraits::ValueType _TPixelChannel; - typedef itk::NumericTraits< _TPixelChannel > _TChannelTraits; - static const double max_value = double( _TChannelTraits::max( ) ); - - itk::ImageRegionConstIterator< I > iIt( this->GetInput( ), region ); - itk::ImageRegionIterator< I > oIt( this->GetOutput( ), region ); - - iIt.GoToBegin( ); - oIt.GoToBegin( ); - for( ; !iIt.IsAtEnd( ); ++iIt, ++oIt ) - { - double r = double( iIt.Get( )[ 0 ] ) * this->m_Coefficient[ 0 ]; - double g = double( iIt.Get( )[ 1 ] ) * this->m_Coefficient[ 1 ]; - double b = double( iIt.Get( )[ 2 ] ) * this->m_Coefficient[ 2 ]; - - if( r > max_value ) r = max_value; - if( g > max_value ) g = max_value; - if( b > max_value ) b = max_value; - - typename I::PixelType pix; - pix.SetRed( _TPixelChannel( r ) ); - pix.SetGreen( _TPixelChannel( g ) ); - pix.SetBlue( _TPixelChannel( b ) ); - - oIt.Set( pix ); - - } // rof -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::LightCompensationFilter< I >:: -AfterThreadedGenerateData( ) -{ - this->Superclass::AfterThreadedGenerateData( ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__LIGHTCOMPENSATIONFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/MFluxMedialness.h b/lib/cpExtensions/Algorithms/MFluxMedialness.h deleted file mode 100644 index 97bc44f..0000000 --- a/lib/cpExtensions/Algorithms/MFluxMedialness.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__H__ -#define __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TGradient, class _TMask = itk::Image< unsigned char, _TGradient::ImageDimension > > - class MFluxMedialness - : public GradientImageFunctionBase< _TGradient, _TMask > - { - public: - typedef MFluxMedialness Self; - typedef GradientImageFunctionBase< _TGradient, _TMask > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - itkStaticConstMacro( Dimension, unsigned int, Superclass::Dimension ); - - typedef typename Superclass::TOutput TOutput; - typedef typename Superclass::TScalar TScalar; - typedef typename Superclass::TIndex TIndex; - typedef typename Superclass::TVector TVector; - typedef typename Superclass::TPoint TPoint; - - typedef std::vector< double > TRCandidates; - - public: - itkNewMacro( Self ); - itkTypeMacro( MFluxMedialness, GradientImageFunctionBase ); - - itkGetConstMacro( RadiusStep, double ); - itkGetConstMacro( MinRadius, double ); - itkGetConstMacro( MaxRadius, double ); - itkGetConstMacro( RadialSampling, unsigned int ); - - itkSetMacro( RadiusStep, double ); - itkSetMacro( MinRadius, double ); - itkSetMacro( MaxRadius, double ); - itkSetMacro( RadialSampling, unsigned int ); - - protected: - MFluxMedialness( ); - virtual ~MFluxMedialness( ); - - virtual TOutput _Evaluate( const TIndex& i ) const cpExtensions_OVERRIDE; - - private: - // Purposely not implemented. - MFluxMedialness( const Self& ); - void operator=( const Self& ); - - protected: - double m_MinRadius; - double m_MaxRadius; - unsigned int m_RadialSampling; - double m_RadiusStep; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/MFluxMedialness.hxx b/lib/cpExtensions/Algorithms/MFluxMedialness.hxx deleted file mode 100644 index bc5db37..0000000 --- a/lib/cpExtensions/Algorithms/MFluxMedialness.hxx +++ /dev/null @@ -1,159 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__HXX__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::MFluxMedialness< _TGradient, _TMask >:: -MFluxMedialness( ) - : Superclass( ), - m_MinRadius( double( 0 ) ), - m_MaxRadius( double( 1 ) ), - m_RadialSampling( 4 ), - m_RadiusStep( double( 1 ) ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -cpExtensions::Algorithms::MFluxMedialness< _TGradient, _TMask >:: -~MFluxMedialness( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TGradient, class _TMask > -typename cpExtensions::Algorithms::MFluxMedialness< _TGradient, _TMask >:: -TOutput cpExtensions::Algorithms::MFluxMedialness< _TGradient, _TMask >:: -_Evaluate( const TIndex& i ) const -{ - itk::Object::GlobalWarningDisplayOff( ); - - double pi2n = double( 2 ) * double( vnl_math::pi ); - pi2n /= int( this->m_RadialSampling ); - const _TGradient* img = this->GetInputImage( ); - //const itk::Image::SpacingType& input_spacing = img->GetSpacing( ); - - double Flux1 = 0; - double Flux2 = 0; - double MFlux = 0; - - TRCandidates FluxFinal; - TRCandidates radiusGenerated; - double dR = double( 0 ); - double optR = double( 0 ); - TPoint center; - img->TransformIndexToPhysicalPoint( i, center ); - double radius; - - for( unsigned int cx = 0; cx < Self::Dimension - 1; cx++ ) - { - for( unsigned int cy = cx + 1; cy < Self::Dimension; cy++ ) - { - dR = double( 0 ); - FluxFinal.clear(); - radiusGenerated.clear(); - radius = this->m_MinRadius; - while( radius <= this->m_MaxRadius ) - { - MFlux = 0; - for( unsigned int I_radial = 0; I_radial < this->m_RadialSampling / 2; I_radial++ ) - { - Flux1 = 0; - Flux2 = 0; - - // Direction of first profile - typename TPoint::VectorType dir1; - dir1.Fill( double( 0 ) ); - dir1[ cx ] = std::cos( pi2n * double( I_radial ) ); - dir1[ cy ] = std::sin( pi2n * double( I_radial ) ); - //dir1 *= (radius); - - TIndex rIdx; - - if ( img->TransformPhysicalPointToIndex( center + (dir1*radius), rIdx ) ) - { - TVector grad_rIdx = img->GetPixel( rIdx ); - TVector u_i1; - u_i1.SetVnlVector( ( center - ( center + dir1 ) ).GetVnlVector( ) ); - u_i1.Normalize( ); - // dot product - Flux1 = grad_rIdx * u_i1; - } - else - { - //if (Self::Dimension==3) - //{ - //std::cout<<"Point Edge x:"<TransformPhysicalPointToIndex( center + (dir2*radius), rIdx2 ) ) - { - TVector grad_rIdx2 = img->GetPixel( rIdx2 ); - TVector u_i2; - u_i2.SetVnlVector( ( center - ( center + dir2 ) ).GetVnlVector( ) ); - u_i2.Normalize( ); - - Flux2 = grad_rIdx2 * u_i2; - } - else - { - //if (Self::Dimension==3) - //{ - //std::cout<<"Point Edge x:"<m_RadialSampling; - FluxFinal.push_back(MFlux); - radiusGenerated.push_back(radius); - - radius += this->m_RadiusStep; - - } //elihw - - dR= *( std::max_element( FluxFinal.begin(), FluxFinal.end() ) ); - optR= (dR>optR)? dR:optR; - - } // rof - - } // rof - return( TScalar(optR) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__MFLUXMEDIALNESS__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/MacheteImageFilter.h b/lib/cpExtensions/Algorithms/MacheteImageFilter.h deleted file mode 100644 index d9d3c32..0000000 --- a/lib/cpExtensions/Algorithms/MacheteImageFilter.h +++ /dev/null @@ -1,72 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Jose Luis Guzman (cycopepe@gmail.com) -// ------------------------------------------------------------------------- - - -#ifndef __CPEXTENSIONS__ALGORITHMS__MACHETEIMAGEFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__MACHETEIMAGEFILTER__H__ - -#include - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - template< class I, class O> - class MacheteImageFilter :public itk::ImageToImageFilter < I, O > - { - public: - /** Standard class typedefs. */ - typedef MacheteImageFilter Self; - - typedef itk::ImageToImageFilter< I, O > Superclass; - typedef itk::SmartPointer< Self > Pointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(MacheteImageFilter, ImageToImageFilter); - - typedef typename I::PixelType RadiusType; - //typedef typename I::SizeValueType RadiusValueType; - - itkGetConstReferenceMacro(Radius, RadiusType); - - - void SetRadius(const RadiusType & rad); - //void SetRadius(const RadiusValueType & rad); - - void SetPoint(itk::Point & point); - void SetPoint(const double & x, const double & y, const double & z); - - protected: - MacheteImageFilter(){} - ~MacheteImageFilter(){} - - /** Does the real work. */ - virtual void GenerateData(); - - RadiusType m_Radius; - itk::Point point; - - private: - MacheteImageFilter(const Self &); //purposely not implemented - void operator=(const Self &); //purposely not implemented - - - }; - - } // ecapseman - -} // ecapseman - - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif - - -#endif // __CPEXTENSIONS__ALGORITHMS__MACHETEIMAGEFILTER__H__ \ No newline at end of file diff --git a/lib/cpExtensions/Algorithms/MacheteImageFilter.hxx b/lib/cpExtensions/Algorithms/MacheteImageFilter.hxx deleted file mode 100644 index a984df1..0000000 --- a/lib/cpExtensions/Algorithms/MacheteImageFilter.hxx +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__MACHETEIMAGEFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__MACHETEIMAGEFILTER__HXX__ - -#include - -//filter stuff -#include "itkObjectFactory.h" -#include "itkImageRegionIterator.h" -#include "itkImageRegionConstIterator.h" - -//typedef itk::Image ImageType; - -template< class I, class O> -void cpExtensions::Algorithms::MacheteImageFilter< I, O> -::GenerateData() -{ - //const typename Superclass::OutputImageRegionType& region; - - typename I::ConstPointer input = this->GetInput(); - - typename O::Pointer output = this->GetOutput(); - output->SetRegions(input->GetLargestPossibleRegion()); - output->Allocate(); - - itk::ImageRegionIterator outputIterator(output, output->GetLargestPossibleRegion()); - itk::ImageRegionConstIterator inputIterator(input, input->GetLargestPossibleRegion()); - - while (!outputIterator.IsAtEnd()) - { - auto p0 = inputIterator.GetIndex(); - itk::Point otherPoint; - otherPoint[0] = p0[0]; - otherPoint[1] = p0[1]; - otherPoint[2] = p0[2]; - //otherPoint[2] = this->point[2]; // TODO : Solve this hammer - - double dist = this->point.EuclideanDistanceTo(otherPoint); - if (dist <= this->m_Radius) - { - outputIterator.Set(0); - } - else - { - outputIterator.Set(inputIterator.Get()); - } - - ++inputIterator; - ++outputIterator; - } - - -} - -template< class I, class O> -void cpExtensions::Algorithms::MacheteImageFilter< I, O>::SetRadius(const RadiusType & rad) -{ - if (this->m_Radius != rad) - { - this->m_Radius = rad; - this->Modified(); - } -} - -//template< class I, class O> -//void cpExtensions::Algorithms::MacheteImageFilter< I, O>::SetRadius(const RadiusValueType & rad) -//{ -// RadiusType r; -// r.Fill(rad); -// this->SetRadius(r); -//} - -template< class I, class O> -void cpExtensions::Algorithms::MacheteImageFilter< I, O>::SetPoint(itk::Point & p){ - if (point != p) - { - this->point = p; - this->Modified(); - } -} - -template< class I, class O> -void cpExtensions::Algorithms::MacheteImageFilter< I, O>::SetPoint(const double & x, const double & y, const double & z) -{ - this->point[0] = x; - this->point[1] = y; - this->point[2] = z; - this->Modified(); -} - - - -#endif \ No newline at end of file diff --git a/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.h b/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.h deleted file mode 100644 index 63fb8a8..0000000 --- a/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.h +++ /dev/null @@ -1,86 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__h__ -#define __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__h__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I, class O > - class MultiScaleGaussianImageFilter - : public itk::ImageToImageFilter< I, O > - { - public: - typedef MultiScaleGaussianImageFilter Self; - typedef itk::ImageToImageFilter< I, O > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef I TInputImage; - typedef O TOutputImage; - - typedef std::set< double > TScalesContainer; - - protected: - /** - */ - class _Greater - { - public: - typedef typename O::PixelType _T; - - public: - _Greater( ); - virtual ~_Greater( ); - bool operator!=( const _Greater& b ) const; - bool operator==( const _Greater& b ) const; - inline _T operator()( const _T& a ) const; - inline _T operator()( const _T& a, const _T& b ) const; - }; - - public: - itkNewMacro( Self ); - itkTypeMacro( MultiScaleGaussianImageFilter, itkImageToImageFilter ); - - public: - void AddScale( const double& s ); - unsigned long GetNumberOfScales( ) const; - - protected: - MultiScaleGaussianImageFilter( ); - virtual ~MultiScaleGaussianImageFilter( ); - - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - template< class F > - void _GenerateData( ); - - private: - // Purposely not implemented. - MultiScaleGaussianImageFilter( const Self& ); - void operator=( const Self& ); - - protected: - TScalesContainer m_Scales; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.hxx b/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.hxx deleted file mode 100644 index 985cbec..0000000 --- a/lib/cpExtensions/Algorithms/MultiScaleGaussianImageFilter.hxx +++ /dev/null @@ -1,226 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__hxx__ -#define __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__hxx__ - -#include - -#include -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -_Greater( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -~_Greater( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O > -bool cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -operator!=( const _Greater& b ) const -{ - return( false ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -bool cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -operator==( const _Greater& b ) const -{ - return !( *this != b ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -typename cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -_T cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -operator()( const _T& a ) const -{ - return( a ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -typename cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -_T cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >::_Greater:: -operator()( const _T& a, const _T& b ) const -{ - typedef itk::NumericTraits< _T > _TTraits; - typedef typename _TTraits::ValueType _TValue; - typedef vnl_vector< _TValue > _TVector; - - _TVector va( _TTraits::GetLength( ) ); - _TVector vb( _TTraits::GetLength( ) ); - - _TTraits::AssignToArray( a, va ); - _TTraits::AssignToArray( b, vb ); - return( ( vb.magnitude( ) < va.magnitude( ) )? a: b ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -void -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -AddScale( const double& s ) -{ - if( this->m_Scales.insert( s ).second ) - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -unsigned long -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -GetNumberOfScales( ) const -{ - return( this->m_Scales.size( ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -MultiScaleGaussianImageFilter( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -~MultiScaleGaussianImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O > -void -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -GenerateData( ) -{ - typedef itk::GradientRecursiveGaussianImageFilter< I, O > _TGF; - this->_GenerateData< _TGF >( ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -template< class F > -void -cpExtensions::Algorithms:: -MultiScaleGaussianImageFilter< I, O >:: -_GenerateData( ) -{ - // Some types - typedef itk::BinaryFunctorImageFilter< O, O, O, _Greater > _TMaxFilter; - typedef itk::UnaryFunctorImageFilter< O, O, _Greater > _TCopyFilter; - typedef itk::ImageRegionConstIterator< O > _TConstIt; - typedef itk::ImageRegionIterator< O > _TIt; - typedef itk::ProgressAccumulator _TProgress; - - // Some values - typename I::ConstPointer input = this->GetInput( ); - typename O::Pointer output = this->GetOutput( ); - unsigned int nThreads = this->GetNumberOfThreads( ); - float fw = float( 1 ) / float( this->m_Scales.size( ) << 1 ); - - // Progress accumulator - _TProgress::Pointer pg = _TProgress::New( ); - pg->SetMiniPipelineFilter( this ); - - // Copy image information - output->SetLargestPossibleRegion( input->GetLargestPossibleRegion( ) ); - output->SetRequestedRegion( input->GetRequestedRegion( ) ); - output->SetBufferedRegion( input->GetBufferedRegion( ) ); - output->SetSpacing( input->GetSpacing( ) ); - output->SetOrigin( input->GetOrigin( ) ); - output->SetDirection( input->GetDirection( ) ); - output->Allocate( ); - - // Intermediary buffer - typename O::Pointer buffer = O::New( ); - buffer->SetLargestPossibleRegion( input->GetLargestPossibleRegion( ) ); - buffer->SetRequestedRegion( input->GetRequestedRegion( ) ); - buffer->SetBufferedRegion( input->GetBufferedRegion( ) ); - buffer->SetSpacing( input->GetSpacing( ) ); - buffer->SetOrigin( input->GetOrigin( ) ); - buffer->SetDirection( input->GetDirection( ) ); - buffer->Allocate( ); - - // Perform all scales - _TIt gIt( output, output->GetRequestedRegion( ) ); - TScalesContainer::const_iterator sIt = this->m_Scales.begin( ); - for( ; sIt != this->m_Scales.end( ); sIt++ ) - { - // Single scale filter - typename F::Pointer filter = F::New( ); - filter->SetInput( input ); - filter->SetNormalizeAcrossScale( true ); - filter->SetNumberOfThreads( nThreads ); - filter->SetSigma( *sIt ); - pg->RegisterInternalFilter( filter, fw ); - filter->GraftOutput( buffer ); - filter->Update( ); - buffer->Graft( filter->GetOutput( ) ); - - // Get maximum response - if( sIt == this->m_Scales.begin( ) ) - { - // Copy first result - typename _TCopyFilter::Pointer copy = _TCopyFilter::New( ); - copy->SetInput( buffer ); - copy->InPlaceOff( ); - copy->SetNumberOfThreads( nThreads ); - pg->RegisterInternalFilter( copy, fw ); - copy->GraftOutput( output ); - copy->Update( ); - output->Graft( copy->GetOutput( ) ); - } - else - { - // Maximize results - typename _TMaxFilter::Pointer max = _TMaxFilter::New( ); - max->SetInput1( output ); - max->SetInput2( buffer ); - max->InPlaceOn( ); - max->SetNumberOfThreads( nThreads ); - pg->RegisterInternalFilter( max, fw ); - max->GraftOutput( output ); - max->Update( ); - output->Graft( max->GetOutput( ) ); - - } // fi - - } // rof -} - -#endif // __cpExtensions__Algorithms__MultiScaleGaussianImageFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ParallelImageMean.h b/lib/cpExtensions/Algorithms/ParallelImageMean.h deleted file mode 100644 index 6122ce3..0000000 --- a/lib/cpExtensions/Algorithms/ParallelImageMean.h +++ /dev/null @@ -1,70 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__H__ -#define __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__H__ - -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I > - class ParallelImageMean - : public itk::DomainThreader< itk::ThreadedImageRegionPartitioner< I::ImageDimension >, I > - { - public: - // Standard ITK typedefs. - typedef itk::DomainThreader< itk::ThreadedImageRegionPartitioner< I::ImageDimension >, I > Superclass; - typedef ParallelImageMean Self; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef typename Superclass::DomainType DomainType; - - typedef itk::Array< double > TMean; - - protected: - typedef itk::NumericTraits< typename I::PixelType > _TPixelTraits; - - - public: - itkNewMacro( Self ); - itkTypeMacro( ParallelImageMean, itkDomainThreader ); - - itkGetConstMacro( Mean, TMean ); - - protected: - ParallelImageMean( ); - virtual ~ParallelImageMean( ); - - private: - virtual void BeforeThreadedExecution( ); - virtual void ThreadedExecution( - const DomainType& region, const itk::ThreadIdType id - ); - virtual void AfterThreadedExecution( ); - - protected: - itk::Array< double > m_Mean; - unsigned long m_N; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/ParallelImageMean.hxx b/lib/cpExtensions/Algorithms/ParallelImageMean.hxx deleted file mode 100644 index b3e4716..0000000 --- a/lib/cpExtensions/Algorithms/ParallelImageMean.hxx +++ /dev/null @@ -1,65 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__HXX__ - -#include - -// ------------------------------------------------------------------------- -template< class I > -cpExtensions::Algorithms::ParallelImageMean< I >:: -ParallelImageMean( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I > -cpExtensions::Algorithms::ParallelImageMean< I >:: -~ParallelImageMean( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::ParallelImageMean< I >:: -BeforeThreadedExecution( ) -{ - this->m_Mean.SetSize( _TPixelTraits::GetLength( ) ); - this->m_Mean.Fill( double( 0 ) ); - this->m_N = 0; -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::ParallelImageMean< I >:: -ThreadedExecution( const DomainType& region, const itk::ThreadIdType id ) -{ - itk::ImageRegionConstIterator< I > i( this->m_Associate, region ); - for( i.GoToBegin( ); !i.IsAtEnd( ); ++i ) - { - for( unsigned int d = 0; d < _TPixelTraits::GetLength( ); ++d ) - { - this->m_Mean.SetElement( - d, this->m_Mean.GetElement( d ) + double( i.Get( )[ d ] ) - ); - this->m_N++; - - } // rof - - } // rof -} - -// ------------------------------------------------------------------------- -template< class I > -void cpExtensions::Algorithms::ParallelImageMean< I >:: -AfterThreadedExecution( ) -{ - this->m_Mean /= double( this->m_N ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__PARALLELIMAGEMEAN__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.cxx b/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.cxx deleted file mode 100644 index 9eecda1..0000000 --- a/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.cxx +++ /dev/null @@ -1,94 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#include - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -_TPolyLine* cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -GetInput( ) -{ - return( dynamic_cast< _TPolyLine* >( this->Superclass::GetInput( 0 ) ) ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -const _TPolyLine* cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -GetInput( ) const -{ - return( dynamic_cast< const _TPolyLine* >( this->Superclass::GetInput( 0 ) ) ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -void cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -SetInput( _TPolyLine* pl ) -{ - this->Superclass::SetNthInput( 0, pl ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -_TCurve* cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -GetOutput( ) -{ - return( dynamic_cast< _TCurve* >( this->Superclass::GetOutput( 0 ) ) ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -const _TCurve* cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -GetOutput( ) const -{ - return( dynamic_cast< const _TCurve* >( this->Superclass::GetOutput( 0 ) ) ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -PolyLineParametricPathToSimple3DCurve( ) - : Superclass( ), - m_NumberOfSamples( 0 ) -{ - this->SetNumberOfRequiredInputs( 1 ); - this->SetNumberOfRequiredOutputs( 1 ); - typename _TCurve::Pointer curve = _TCurve::New( ); - this->Superclass::SetNthOutput( 0, curve ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -~PolyLineParametricPathToSimple3DCurve( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TCurve > -void cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPolyLine, _TCurve >:: -GenerateData( ) -{ - const _TPolyLine* line = this->GetInput( ); - _TCurve* curve = this->GetOutput( ); - unsigned long N = this->m_NumberOfSamples; - if( N == 0 ) - N = line->GetSize( ); - curve->Clear( ); - - for( unsigned long n = 0; n < N; ++n ) - { - double u = double( n ) / double( N - 1 ); - curve->AddPoint( line->GetSmoothPoint( u ) ); - - } // rof -} - -// ------------------------------------------------------------------------- -#include -#include - -template class cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< cpExtensions::DataStructures::PolyLineParametricPath< 3 >, cpExtensions::DataStructures::Simple3DCurve< float > >; -template class cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< cpExtensions::DataStructures::PolyLineParametricPath< 3 >, cpExtensions::DataStructures::Simple3DCurve< double > >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.h b/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.h deleted file mode 100644 index 5282e88..0000000 --- a/lib/cpExtensions/Algorithms/PolyLineParametricPathToSimple3DCurve.h +++ /dev/null @@ -1,65 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__PolyLineParametricPathToSimple3DCurve__h__ -#define __cpExtensions__Algorithms__PolyLineParametricPathToSimple3DCurve__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TPolyLine, class _TCurve > - class cpExtensions_EXPORT PolyLineParametricPathToSimple3DCurve - : public itk::ProcessObject - { - public: - // Basic types - typedef PolyLineParametricPathToSimple3DCurve Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( PolyLineParametricPathToSimple3DCurve, itk::ProcessObject ); - - itkGetConstMacro( NumberOfSamples, unsigned long ); - itkSetMacro( NumberOfSamples, unsigned long ); - - public: - _TPolyLine* GetInput( ); - const _TPolyLine* GetInput( ) const; - void SetInput( _TPolyLine* pl ); - - _TCurve* GetOutput( ); - const _TCurve* GetOutput( ) const; - - protected: - PolyLineParametricPathToSimple3DCurve( ); - virtual ~PolyLineParametricPathToSimple3DCurve( ); - - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - PolyLineParametricPathToSimple3DCurve( const Self& ); - void operator=( const Self& ); - - protected: - unsigned long m_NumberOfSamples; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Algorithms__PolyLineParametricPathToSimple3DCurve__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.h b/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.h deleted file mode 100644 index deb6b30..0000000 --- a/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.h +++ /dev/null @@ -1,74 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__PolyLineParametricPathWriter__h__ -#define __cpExtensions__Algorithms__PolyLineParametricPathWriter__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TPolyLine, class _TImage = itk::Image< unsigned char, _TPolyLine::PathDimension > > - class PolyLineParametricPathWriter - : public itk::ProcessObject - { - public: - // Basic types - typedef PolyLineParametricPathWriter Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( PolyLineParametricPathWriter, itk::ProcessObject ); - - itkGetConstMacro( FileName, std::string ); - itkGetConstMacro( NumberOfPoints, long ); - - itkSetMacro( FileName, std::string ); - itkSetMacro( NumberOfPoints, long ); - - public: - void SetInput( const _TPolyLine* input ); - const _TPolyLine* GetInput( ); - - void SetImage( const _TImage* image ); - const _TImage* GetImage( ); - - virtual void Update( ); - - protected: - PolyLineParametricPathWriter( ); - virtual ~PolyLineParametricPathWriter( ); - - virtual void GenerateData( ) override; - - private: - // Purposely not implemented - PolyLineParametricPathWriter( const Self& ); - void operator=( const Self& ); - - protected: - std::string m_FileName; - long m_NumberOfPoints; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__PolyLineParametricPathWriter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.hxx b/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.hxx deleted file mode 100644 index d71c6e3..0000000 --- a/lib/cpExtensions/Algorithms/PolyLineParametricPathWriter.hxx +++ /dev/null @@ -1,160 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__PolyLineParametricPathWriter__hxx__ -#define __cpExtensions__Algorithms__PolyLineParametricPathWriter__hxx__ - -#include - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -void cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -SetInput( const _TPolyLine* input ) -{ - this->itk::ProcessObject::SetNthInput( - 0, const_cast< _TPolyLine* >( input ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -const _TPolyLine* -cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -GetInput( ) -{ - return( - dynamic_cast< const _TPolyLine* >( - this->itk::ProcessObject::GetInput( 0 ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -void cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -SetImage( const _TImage* image ) -{ - this->itk::ProcessObject::SetNthInput( - 1, const_cast< _TImage* >( image ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -const _TImage* cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -GetImage( ) -{ - return( - dynamic_cast< const _TImage* >( - this->itk::ProcessObject::GetInput( 1 ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -void cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -Update( ) -{ - _TPolyLine* input = const_cast< _TPolyLine* >( this->GetInput( ) ); - if( input != NULL ) - { - input->UpdateOutputInformation( ); - input->UpdateOutputData( ); - this->GenerateData( ); - this->ReleaseInputs( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -PolyLineParametricPathWriter( ) - : Superclass( ), - m_FileName( "" ), - m_NumberOfPoints( 100 ) -{ - this->SetNumberOfRequiredInputs( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -~PolyLineParametricPathWriter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine, class _TImage > -void cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLine, _TImage >:: -GenerateData( ) -{ - typedef typename _TPolyLine::TContinuousIndex _TContinuousIndex; - - // "Serialize" data - const _TPolyLine* input = this->GetInput( ); - const _TImage* image = this->GetImage( ); - unsigned int dim = _TPolyLine::PathDimension; - std::stringstream buffer; - long step = input->GetSize( ) / this->m_NumberOfPoints; - - for( unsigned long i = 0; i < input->GetSize( ); i += step ) - { - _TContinuousIndex idx; - idx.Fill( 0 ); - int c = 0; - for( long j = -step; j <= step; ++j ) - { - long k = i + j; - if( k >= 0 && k < input->GetSize( ) ) - { - _TContinuousIndex kdx = input->GetContinuousVertex( k ); - for( unsigned int d = 0; d < dim; ++d ) - idx[ d ] += kdx[ d ]; - c++; - - } // fi - - } // rof - if( c != 0 ) - for( unsigned int d = 0; d < dim; ++d ) - idx[ d ] /= c; - - buffer << idx[ 0 ]; - for( unsigned int d = 1; d < dim; ++d ) - buffer << " " << idx[ d ]; - if( image != NULL ) - { - typename _TImage::PointType pidx; - typename _TImage::IndexType iidx; - image->TransformContinuousIndexToPhysicalPoint( idx, pidx ); - image->TransformPhysicalPointToIndex( pidx, iidx ); - buffer << " " << image->GetPixel( iidx ); - - } // fi - buffer << std::endl; - - } // rof - - // Real write - std::ofstream file_stream( - this->m_FileName.c_str( ), std::ofstream::binary - ); - if( !file_stream ) - { - itkExceptionMacro( - << "Could not open file \"" << this->m_FileName << "\" to write a " - << "cpExtensions::DataStructures::PolyLineParametricPath< " << dim - << " > object." - ); - return; - - } // fi - file_stream.write( buffer.str( ).c_str( ), buffer.str( ).size( ) ); -} - -#endif // __cpExtensions__Algorithms__PolyLineParametricPathWriter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBExtractFunction.h b/lib/cpExtensions/Algorithms/RGBExtractFunction.h deleted file mode 100644 index ec7126b..0000000 --- a/lib/cpExtensions/Algorithms/RGBExtractFunction.h +++ /dev/null @@ -1,54 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__RGBEXTRACTFUNCTION__H__ -#define __CPEXTENSIONS__ALGORITHMS__RGBEXTRACTFUNCTION__H__ - -#include -#include -#include - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class P > - struct RGBExtractFunction - { - typedef RGBExtractFunction Self; - typedef P TOutPixel; - typedef typename P::ValueType TValue; - - template< class Tr, class Tg, class Tb > - P operator()( const Tr& r, const Tg& g, const Tb& b ) const - { - P out; - out[ 0 ] = TValue( r ); - out[ 1 ] = TValue( g ); - out[ 2 ] = TValue( b ); - return( out ); - } - - template< class C > - TOutPixel operator()( const itk::RGBPixel< C >& rgb ) const - { - return( - this->operator()( - rgb.GetRed( ), rgb.GetGreen( ), rgb.GetBlue( ) - ) - ); - } - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__RGBEXTRACTFUNCTION__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.h b/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.h deleted file mode 100644 index 4ce6754..0000000 --- a/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.h +++ /dev/null @@ -1,67 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I, class O, class C > - class RGBImageToOtherChannelsFilter - : public itk::ImageToImageFilter< I, O > - { - public: - typedef RGBImageToOtherChannelsFilter Self; - typedef itk::ImageToImageFilter< I, O > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef I TInputImage; - typedef O TOutputImage; - typedef C TConverter; - typedef typename I::PixelType TInputPixel; - typedef typename O::PixelType TOutputPixel; - - public: - itkNewMacro( Self ); - itkTypeMacro( RGBImageToOtherChannelsFilter, itkImageToImageFilter ); - - protected: - RGBImageToOtherChannelsFilter( ); - virtual ~RGBImageToOtherChannelsFilter( ); - - virtual void BeforeThreadedGenerateData( ); - virtual void AfterThreadedGenerateData( ); - - virtual void ThreadedGenerateData( - const typename Superclass::OutputImageRegionType& region, - itk::ThreadIdType threadId - ); - - private: - // Purposely not implemented - RGBImageToOtherChannelsFilter( const Self& other ); - void operator=( const Self& other ); - - private: - TConverter Converter; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.hxx b/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.hxx deleted file mode 100644 index 74578d4..0000000 --- a/lib/cpExtensions/Algorithms/RGBImageToOtherChannelsFilter.hxx +++ /dev/null @@ -1,71 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__HXX__ - -#include -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -template< class I, class O, class C > -cpExtensions::Algorithms::RGBImageToOtherChannelsFilter< I, O, C >:: -RGBImageToOtherChannelsFilter( ) - : Superclass( ) -{ - this->SetNumberOfRequiredInputs( 1 ); - this->SetNumberOfRequiredOutputs( 1 ); - - typename O::Pointer o = O::New( ); - this->SetNthOutput( 0, o ); -} - -// ------------------------------------------------------------------------- -template< class I, class O, class C > -cpExtensions::Algorithms::RGBImageToOtherChannelsFilter< I, O, C >:: -~RGBImageToOtherChannelsFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O, class C > -void cpExtensions::Algorithms::RGBImageToOtherChannelsFilter< I, O, C >:: -BeforeThreadedGenerateData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O, class C > -void cpExtensions::Algorithms::RGBImageToOtherChannelsFilter< I, O, C >:: -AfterThreadedGenerateData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O, class C > -void cpExtensions::Algorithms::RGBImageToOtherChannelsFilter< I, O, C >:: -ThreadedGenerateData( - const typename Superclass::OutputImageRegionType& region, - itk::ThreadIdType threadId - ) -{ - // typedef typename TInputPixel::ComponentType _TComponent; - typedef itk::ImageRegionConstIterator< I > _TInIt; - typedef itk::ImageRegionIterator< O > _TOutIt; - - _TInIt inIt( this->GetInput( ), region ); - _TOutIt outIt( this->GetOutput( ), region ); - inIt.GoToBegin( ); - outIt.GoToBegin( ); - for( ; !inIt.IsAtEnd( ); ++inIt, ++outIt ) - outIt.Set( this->Converter( inIt.Get( ) ) ); -} - -#endif // __CPEXTENSIONS__ALGORITHMS__RGBIMAGETOOTHERCHANNELSFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBToHSVFunction.h b/lib/cpExtensions/Algorithms/RGBToHSVFunction.h deleted file mode 100644 index b10f295..0000000 --- a/lib/cpExtensions/Algorithms/RGBToHSVFunction.h +++ /dev/null @@ -1,87 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__ -#define __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__ - -#include -#include -#include - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class P > - struct RGBToHSVFunction - { - typedef RGBToHSVFunction Self; - typedef P TOutPixel; - typedef typename P::ValueType TValue; - - template< class Tr, class Tg, class Tb > - P operator()( const Tr& r, const Tg& g, const Tb& b ) const - { - static const double mVal = - double( std::numeric_limits< TValue >::max( ) ); - static const double _0 = double( 0 ); - static const double _1 = double( 1 ); - static const double _2 = double( 2 ); - static const double _3 = double( 3 ); - static const double _2pi = _2 * double( vnl_math::pi ); - - P hsv; - - double R = double( r ); - double G = double( g ); - double B = double( b ); - double sRGB = R + G + B; - double RG = R - G; - double RB = R - B; - double GB = G - B; - - // Hue - double A = std::sqrt( ( RG * RG ) + ( RB * GB ) ); - if( A != _0 ) - A = std::acos( ( RG + RB ) / ( _2 * A ) ); - A /= _2pi; - hsv[ 0 ] = TValue( mVal * ( ( G >= B )? A: _1 - A ) ); - - // Saturation - if( sRGB != _0 ) - { - double C = ( G < R )? G: R; - C = ( B < C )? B: C; - hsv[ 1 ] = TValue( mVal * ( _1 - ( ( _3 * C ) / sRGB ) ) ); - } - else - hsv[ 1 ] = TValue( 0 ); - - // Value - hsv[ 2 ] = TValue( sRGB / _3 ); - return( hsv ); - } - - template< class C > - TOutPixel operator()( const itk::RGBPixel< C >& rgb ) const - { - return( - this->operator()( - rgb.GetRed( ), rgb.GetGreen( ), rgb.GetBlue( ) - ) - ); - } - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.h b/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.h deleted file mode 100644 index 815b936..0000000 --- a/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.h +++ /dev/null @@ -1,86 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__RGBToSingleChannelFunctor__h__ -#define __cpExtensions__Algorithms__RGBToSingleChannelFunctor__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TScalar > - class RGBToSingleChannelFunctor - : public itk::FunctionBase< itk::RGBPixel< _TScalar >, _TScalar > - { - public: - typedef _TScalar TScalar; - typedef itk::RGBPixel< _TScalar > TPixel; - typedef RGBToSingleChannelFunctor Self; - typedef itk::FunctionBase< TPixel, TScalar > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - enum ChannelType - { - Red = 0, - Green, - Blue, - Hue, - Saturation, - Value - }; - - public: - itkNewMacro( Self ); - itkTypeMacro( RGBToSingleChannelFunctor, itkFunctionBase ); - - itkGetConstMacro( Channel, ChannelType ); - itkSetMacro( Channel, ChannelType ); - - public: - bool IsChannelRed( ) const; - bool IsChannelGreen( ) const; - bool IsChannelBlue( ) const; - bool IsChannelHue( ) const; - bool IsChannelSaturation( ) const; - bool IsChannelValue( ) const; - - void SetChannelToRed( ); - void SetChannelToGreen( ); - void SetChannelToBlue( ); - void SetChannelToHue( ); - void SetChannelToSaturation( ); - void SetChannelToValue( ); - - virtual TScalar Evaluate( const TPixel& pixel ) const override; - - protected: - RGBToSingleChannelFunctor( ); - virtual ~RGBToSingleChannelFunctor( ); - - private: - // Purposely not implemented. - RGBToSingleChannelFunctor( const Self& ); - void operator=( const Self& ); - - protected: - ChannelType m_Channel; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__RGBToSingleChannelFunctor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.hxx b/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.hxx deleted file mode 100644 index c99e592..0000000 --- a/lib/cpExtensions/Algorithms/RGBToSingleChannelFunctor.hxx +++ /dev/null @@ -1,188 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__RGBToSingleChannelFunctor__hxx__ -#define __cpExtensions__Algorithms__RGBToSingleChannelFunctor__hxx__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelRed( ) const -{ - return( this->m_Channel == Self::Red ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelGreen( ) const -{ - return( this->m_Channel == Self::Green ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelBlue( ) const -{ - return( this->m_Channel == Self::Blue ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelHue( ) const -{ - return( this->m_Channel == Self::Hue ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelSaturation( ) const -{ - return( this->m_Channel == Self::Saturation ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -bool cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -IsChannelValue( ) const -{ - return( this->m_Channel == Self::Value ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToRed( ) -{ - this->SetChannel( Self::Red ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToGreen( ) -{ - this->SetChannel( Self::Green ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToBlue( ) -{ - this->SetChannel( Self::Blue ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToHue( ) -{ - this->SetChannel( Self::Hue ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToSaturation( ) -{ - this->SetChannel( Self::Saturation ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -SetChannelToValue( ) -{ - this->SetChannel( Self::Value ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -_TScalar cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -Evaluate( const TPixel& pixel ) const -{ - _TScalar res; - switch( this->m_Channel ) - { - case Self::Hue: - { - double R = double( pixel.GetRed( ) ); - double G = double( pixel.GetRed( ) ); - double B = double( pixel.GetBlue( ) ); - double RG = R - G; - double RB = R - B; - double GB = G - B; - double A = std::sqrt( ( RG * RG ) + ( RB * GB ) ); - if( A != _0 ) - A = std::acos( ( RG + RB ) / ( double( 2 ) * A ) ); - A /= double( 2 ) * double( vnl_math::pi ); - res = - _TScalar( - double( std::numeric_limits< _TScalar >::max( ) ) * - ( ( G >= B )? A: double( 1 ) - A ) - ); - } - break; - case Self::Saturation: - { - double R = double( r ); - double G = double( g ); - double B = double( b ); - double sRGB = R + G + B; - double RG = R - G; - double RB = R - B; - double GB = G - B; - if( sRGB != double( 0 ) ) - { - double C = ( G < R )? G: R; - C = ( B < C )? B: C; - res = - _TScalar( - double( std::numeric_limits< _TScalar >::max( ) ) * - ( double( 1 ) - ( ( double( 3 ) * C ) / sRGB ) ) - ); - } - else - res = _TScalar( 0 ); - } - break; - case Self::Value: - { - res = ( pixel.GetRed( ) + pixel.GetGreen( ) + pixel.GetBlue( ) ) / 3; - } - break; - case Self::Green: { res = pixel.GetGreen( ); } break; - case Self::Blue: { res = pixel.GetBlue( ); } break; - case Self::Red: default: { res = pixel.GetRed( ); } break; - } // hctiws - return( res ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -RGBToSingleChannelFunctor( ) - : Superclass( ) -{ - this->SetChannelToRed( ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -cpExtensions::Algorithms::RGBToSingleChannelFunctor< _TScalar >:: -~RGBToSingleChannelFunctor( ) -{ -} - -#endif // __cpExtensions__Algorithms__RGBToSingleChannelFunctor__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RGBToYPbPrFunction.h b/lib/cpExtensions/Algorithms/RGBToYPbPrFunction.h deleted file mode 100644 index 83085fe..0000000 --- a/lib/cpExtensions/Algorithms/RGBToYPbPrFunction.h +++ /dev/null @@ -1,72 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__RGBTOYPBPRFUNCTION__H__ -#define __CPEXTENSIONS__ALGORITHMS__RGBTOYPBPRFUNCTION__H__ - -#include -#include -#include -#include - -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class P > - struct RGBToYPbPrFunction - { - typedef RGBToYPbPrFunction Self; - typedef P TOutPixel; - typedef typename P::ValueType TValue; - - template< class Tr, class Tg, class Tb > - P operator()( const Tr& r, const Tg& g, const Tb& b ) const - { - static const double M[] = - { - double( 0.2990 ), double( 0.5870 ), double( 0.1140 ), - double( -0.1687 ), double( -0.3313 ), double( 0.5000 ), - double( 0.5000 ), double( -0.4187 ), double( -0.0813 ) - }; - static const vnl_matrix< double > vM( M, 3, 3 ); - static const itk::Matrix< double, 3, 3 > iM( vM ); - - itk::Vector< double, 3 > rgb; - rgb[ 0 ] = double( r ); - rgb[ 1 ] = double( b ); - rgb[ 2 ] = double( g ); - rgb = iM * rgb; - - P out; - out[ 0 ] = TValue( rgb[ 0 ] ); - out[ 1 ] = TValue( rgb[ 1 ] ); - out[ 2 ] = TValue( rgb[ 2 ] ); - return( out ); - } - - template< class C > - TOutPixel operator()( const itk::RGBPixel< C >& rgb ) const - { - return( - this->operator()( - rgb.GetRed( ), rgb.GetGreen( ), rgb.GetBlue( ) - ) - ); - } - }; - - } // ecapseman - -} // ecapseman - -#endif // __CPEXTENSIONS__ALGORITHMS__RGBTOYPBPRFUNCTION__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RasterContourFilter.h b/lib/cpExtensions/Algorithms/RasterContourFilter.h deleted file mode 100644 index 4797dec..0000000 --- a/lib/cpExtensions/Algorithms/RasterContourFilter.h +++ /dev/null @@ -1,105 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__RasterContourFilter__h__ -#define __cpExtensions__Algorithms__RasterContourFilter__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TImage > - class RasterContourFilter - : public itk::ImageSource< _TImage > - { - public: - // Basic types - typedef RasterContourFilter Self; - typedef itk::ImageSource< _TImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TImage TImage; - typedef typename _TImage::IndexType TIndex; - typedef typename _TImage::PixelType TPixel; - typedef typename _TImage::PointType TPoint; - typedef typename _TImage::RegionType TRegion; - typedef itk::ImageBase< 2 > TImageBase; - - public: - itkNewMacro( Self ); - itkTypeMacro( RasterContourFilter, itk::ImageSource ); - - itkGetConstObjectMacro( Template, TImageBase ); - itkGetConstMacro( InsideValue, TPixel ); - itkGetConstMacro( OutsideValue, TPixel ); - - itkSetConstObjectMacro( Template, TImageBase ); - itkSetMacro( InsideValue, TPixel ); - itkSetMacro( OutsideValue, TPixel ); - - public: - void AddPoint( double x, double y ); - void AddPoint( double p[ 2 ] ); - template< class _TPoint > - inline void AddPoint( const _TPoint& p ); - void ClearPoints( ); - - protected: - RasterContourFilter( ); - virtual ~RasterContourFilter( ); - - virtual void AllocateOutputs( ) cpExtensions_OVERRIDE; - virtual void BeforeThreadedGenerateData( ) cpExtensions_OVERRIDE; - virtual void AfterThreadedGenerateData( ) cpExtensions_OVERRIDE; - virtual void ThreadedGenerateData( - const TRegion& region, itk::ThreadIdType id - ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - RasterContourFilter( const Self& ); - void operator=( const Self& ); - - protected: - std::deque< TPoint > m_Contour; - std::deque< TIndex > m_Polygon; - TRegion m_ROI; - typename TImageBase::ConstPointer m_Template; - TPixel m_InsideValue; - TPixel m_OutsideValue; - }; - - } // ecapseman - -} // ecapseman - -// ------------------------------------------------------------------------- -template< class _TImage > -template< class _TPoint > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -AddPoint( const _TPoint& p ) -{ - TPoint pnt; - pnt[ 0 ] = p[ 0 ]; - pnt[ 1 ] = p[ 2 ]; - this->m_Contour.push_back( pnt ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__RasterContourFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RasterContourFilter.hxx b/lib/cpExtensions/Algorithms/RasterContourFilter.hxx deleted file mode 100644 index d325b1a..0000000 --- a/lib/cpExtensions/Algorithms/RasterContourFilter.hxx +++ /dev/null @@ -1,172 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------ - -// Inclusion test taken from: -// https://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html - -#ifndef __cpExtensions__Algorithms__RasterContourFilter__hxx__ -#define __cpExtensions__Algorithms__RasterContourFilter__hxx__ - -#include -#include - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -AddPoint( double x, double y ) -{ - TPoint pnt; - pnt[ 0 ] = x; - pnt[ 1 ] = y; - this->m_Contour.push_back( pnt ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -AddPoint( double p[ 2 ] ) -{ - TPoint pnt; - pnt[ 0 ] = p[ 0 ]; - pnt[ 1 ] = p[ 1 ]; - this->m_Contour.push_back( pnt ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -ClearPoints( ) -{ - this->m_Contour.clear( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -RasterContourFilter( ) - : Superclass( ), - m_InsideValue( TPixel( 1 ) ), - m_OutsideValue( TPixel( 0 ) ) -{ - this->ClearPoints( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -~RasterContourFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -AllocateOutputs( ) -{ - _TImage* out = this->GetOutput( 0 ); - out->SetSpacing( this->m_Template->GetSpacing( ) ); - out->SetRegions( this->m_Template->GetRequestedRegion( ) ); - out->SetOrigin( this->m_Template->GetOrigin( ) ); - out->SetDirection( this->m_Template->GetDirection( ) ); - out->Allocate( ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -BeforeThreadedGenerateData( ) -{ - // Keep just indices, not points - this->m_Polygon.clear( ); - _TImage* out = this->GetOutput( 0 ); - TIndex minIdx, maxIdx; - for( auto c = this->m_Contour.begin( ); c != this->m_Contour.end( ); ++c ) - { - TIndex idx; - out->TransformPhysicalPointToIndex( *c, idx ); - bool added = true; - if( this->m_Polygon.size( ) > 0 ) - { - if( this->m_Polygon.back( ) != idx ) - { - this->m_Polygon.push_back( idx ); - minIdx[ 0 ] = ( idx[ 0 ] < minIdx[ 0 ] )? idx[ 0 ]: minIdx[ 0 ]; - minIdx[ 1 ] = ( idx[ 1 ] < minIdx[ 1 ] )? idx[ 1 ]: minIdx[ 1 ]; - maxIdx[ 0 ] = ( idx[ 0 ] > maxIdx[ 0 ] )? idx[ 0 ]: maxIdx[ 0 ]; - maxIdx[ 1 ] = ( idx[ 1 ] > maxIdx[ 1 ] )? idx[ 1 ]: maxIdx[ 1 ]; - - } // fi - } - else - { - this->m_Polygon.push_back( idx ); - minIdx = maxIdx = idx; - - } // fi - - } // rof - - // Set ROI - typename _TImage::SizeType size; - size[ 0 ] = maxIdx[ 0 ] - minIdx[ 0 ] + 1; - size[ 1 ] = maxIdx[ 1 ] - minIdx[ 1 ] + 1; - this->m_ROI.SetIndex( minIdx ); - this->m_ROI.SetSize( size ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -AfterThreadedGenerateData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RasterContourFilter< _TImage >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType id ) -{ - long nVerts = this->m_Polygon.size( ); - _TImage* out = this->GetOutput( ); - itk::ImageRegionIteratorWithIndex< _TImage > iIt( out, region ); - for( iIt.GoToBegin( ); !iIt.IsAtEnd( ); ++iIt ) - { - TIndex p = iIt.GetIndex( ); - bool inside = false; - if( this->m_ROI.IsInside( p ) ) - { - long i, j; - for( i = 0, j = nVerts - 1; i < nVerts; j = i++ ) - { - TIndex pi = this->m_Polygon[ i ]; - TIndex pj = this->m_Polygon[ j ]; - double pi0 = double( pi[ 0 ] ); - double pi1 = double( pi[ 1 ] ); - double pj0 = double( pj[ 0 ] ); - double pj1 = double( pj[ 1 ] ); - double p0 = double( p[ 0 ] ); - double p1 = double( p[ 1 ] ); - double ji0 = pj0 - pi0; - double ji1 = pj1 - pi1; - double i1 = p1 - pi1; - if( - ( ( pi1 > p1 ) != ( pj1 > p1 ) ) && - ( p0 < ( ( ji0 * i1 ) / ji1 ) + pi0 ) - ) - inside = !inside; - - } // rof - - } // fi - iIt.Set( ( inside )? this->m_InsideValue: this->m_OutsideValue ); - - } // rof -} - -#endif // __cpExtensions__Algorithms__RasterContourFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.h b/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.h deleted file mode 100644 index 84102ad..0000000 --- a/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.h +++ /dev/null @@ -1,73 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__H__ -#define __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__H__ - -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TImage > - class RegionOfInterestImageCalculator - : public itk::Object - { - public: - // Basic types - typedef RegionOfInterestImageCalculator Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TImage TImage; - typedef typename _TImage::IndexType TIndex; - typedef typename _TImage::PixelType TPixel; - - public: - itkNewMacro( Self ); - itkTypeMacro( RegionOfInterestImageCalculator, itkObject ); - - itkGetConstObjectMacro( Image, _TImage ); - itkGetConstMacro( BackgroundValue, TPixel ); - itkGetConstMacro( Minimum, TIndex ); - itkGetConstMacro( Maximum, TIndex ); - - itkSetConstObjectMacro( Image, _TImage ); - itkSetMacro( BackgroundValue, TPixel ); - - public: - void Compute( ); - - protected: - RegionOfInterestImageCalculator( ); - virtual ~RegionOfInterestImageCalculator( ); - - private: - // Purposely not implemented - RegionOfInterestImageCalculator( const Self& ); - void operator=( const Self& ); - - protected: - typename _TImage::ConstPointer m_Image; - TPixel m_BackgroundValue; - TIndex m_Minimum; - TIndex m_Maximum; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.hxx b/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.hxx deleted file mode 100644 index fd7867f..0000000 --- a/lib/cpExtensions/Algorithms/RegionOfInterestImageCalculator.hxx +++ /dev/null @@ -1,92 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__HXX__ - -#include - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::RegionOfInterestImageCalculator< _TImage >:: -Compute( ) -{ - typedef itk::ImageRegionConstIteratorWithIndex< _TImage > _TIterator; - typedef typename _TImage::RegionType _TRegion; - - if( this->m_Image.IsNotNull( ) ) - { - _TRegion region = this->m_Image->GetRequestedRegion( ); - TIndex minidx = region.GetIndex( ); - TIndex maxidx = minidx + region.GetSize( ); - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - maxidx[ d ] -= 1; - - bool first = true; - _TIterator i( this->m_Image, region ); - for( i.GoToBegin( ); !i.IsAtEnd( ); ++i ) - { - if( i.Get( ) != this->m_BackgroundValue ) - { - TIndex idx = i.GetIndex( ); - if( !first ) - { - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - { - minidx[ d ] = ( idx[ d ] < minidx[ d ] )? idx[ d ]: minidx[ d ]; - maxidx[ d ] = ( idx[ d ] > maxidx[ d ] )? idx[ d ]: maxidx[ d ]; - - } // rof - } - else - { - minidx = maxidx = idx; - first = false; - - } // fi - - } // fi - - } // rof - this->m_Minimum = minidx; - this->m_Maximum = maxidx; - } - else - { - this->m_Minimum.Fill( 0 ); - this->m_Maximum.Fill( 0 ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::RegionOfInterestImageCalculator< _TImage >:: -RegionOfInterestImageCalculator( ) - : Superclass( ), - m_BackgroundValue( TPixel( 0 ) ) -{ - this->m_Minimum.Fill( 0 ); - this->m_Maximum.Fill( 0 ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::RegionOfInterestImageCalculator< _TImage >:: -~RegionOfInterestImageCalculator( ) -{ -} - - -/* TODO - typename _TImage::ConstPointer m_Image; - TPixel m_BackgroundValue; - TIndex m_Minimum; - TIndex m_Maximum; - }; -*/ - -#endif // __CPEXTENSIONS__ALGORITHMS__REGIONOFINTERESTIMAGECALCULATOR__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonReader.h b/lib/cpExtensions/Algorithms/SkeletonReader.h deleted file mode 100644 index e1a3064..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonReader.h +++ /dev/null @@ -1,85 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonReader__h__ -#define __cpExtensions__Algorithms__SkeletonReader__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TSkeleton > - class SkeletonReader - : public itk::ProcessObject - { - public: - // Basic types - typedef SkeletonReader Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TSkeleton TSkeleton; - - public: - itkNewMacro( Self ); - itkTypeMacro( SkeletonReader, itk::ImageSource ); - - itkGetConstMacro( FileName, std::string ); - itkSetMacro( FileName, std::string ); - - public: - TSkeleton* GetOutput( ); - TSkeleton* GetOutput( unsigned int i ); - - virtual void GraftOutput( itk::DataObject* out ); - virtual void GraftOutput( - const typename Superclass::DataObjectIdentifierType& key, - itk::DataObject* out - ); - virtual void GraftNthOutput( unsigned int i, itk::DataObject* out ); - virtual itk::DataObject::Pointer MakeOutput( - itk::ProcessObject::DataObjectPointerArraySizeType i - ) cpExtensions_OVERRIDE; - - virtual void Update( ) cpExtensions_OVERRIDE - { this->GenerateData( ); } - - protected: - SkeletonReader( ); - virtual ~SkeletonReader( ); - - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - // Do nothing - virtual void GenerateOutputInformation( ) cpExtensions_OVERRIDE - { } - - private: - // Purposely not implemented - SkeletonReader( const Self& ); - void operator=( const Self& ); - - protected: - std::string m_FileName; - }; - - } // ecapseman - -} // ecapseman - -// ------------------------------------------------------------------------- -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__SkeletonReader__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonReader.hxx b/lib/cpExtensions/Algorithms/SkeletonReader.hxx deleted file mode 100644 index 4235539..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonReader.hxx +++ /dev/null @@ -1,176 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonReader__hxx__ -#define __cpExtensions__Algorithms__SkeletonReader__hxx__ - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -_TSkeleton* cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GetOutput( ) -{ - return( - itkDynamicCastInDebugMode< TSkeleton* >( this->GetPrimaryOutput( ) ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -_TSkeleton* cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GetOutput( unsigned int i ) -{ - return( - itkDynamicCastInDebugMode< TSkeleton* >( - this->itk::ProcessObject::GetOutput( i ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GraftOutput( itk::DataObject* out ) -{ - this->GraftNthOutput( 0, out ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GraftOutput( - const typename Superclass::DataObjectIdentifierType& key, - itk::DataObject* out - ) -{ - if( out == NULL ) - { - itkExceptionMacro( - << "Requested to graft output that is a NULL pointer" - ); - - } // fi - itk::DataObject* output = this->itk::ProcessObject::GetOutput( key ); - output->Graft( out ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GraftNthOutput( unsigned int i, itk::DataObject* out ) -{ - if( i >= this->GetNumberOfIndexedOutputs( ) ) - { - itkExceptionMacro( - << "Requested to graft output " << i - << " but this filter only has " - << this->GetNumberOfIndexedOutputs( ) - << " indexed Outputs." - ); - - } // fi - this->GraftOutput( this->MakeNameFromOutputIndex( i ), out ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -itk::DataObject::Pointer -cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -MakeOutput( itk::ProcessObject::DataObjectPointerArraySizeType i ) -{ - return( TSkeleton::New( ).GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -SkeletonReader( ) - : Superclass( ) -{ - typename TSkeleton::Pointer out = - static_cast< TSkeleton* >( this->MakeOutput( 0 ).GetPointer( ) ); - this->itk::ProcessObject::SetNumberOfRequiredInputs( 0 ); - this->itk::ProcessObject::SetNumberOfRequiredOutputs( 1 ); - this->itk::ProcessObject::SetNthOutput( 0, out.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -~SkeletonReader( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonReader< _TSkeleton >:: -GenerateData( ) -{ - typedef typename TSkeleton::TPath _TPath; - typedef typename _TPath::TSpacing _TSpacing; - typedef typename _TPath::TPoint _TPoint; - typedef typename _TPath::TDirection _TDirection; - typedef typename _TPath::TContinuousIndex _TContinuousIndex; - - std::string buffer; - /* TODO - if( !( cpExtensions::Read( buffer, this->m_FileName ) ) ) - { - itkExceptionMacro( - << "Error reading skeleton from \"" << this->m_FileName << "\"" - ); - return; - - } // fi - */ - - std::istringstream in( buffer ); - unsigned int dim; - in >> dim; - if( dim != TSkeleton::Dimension ) - { - itkExceptionMacro( - << "Mismatched skeletons dimension: " << dim - << " != " << TSkeleton::Dimension - ); - return; - - } // fi - - TSkeleton* out = this->GetOutput( ); - unsigned long size; - in >> size; - while( size > 0 ) - { - _TSpacing spa; - _TPoint ori; - _TDirection dir; - for( unsigned int d = 0; d < dim; ++d ) - in >> spa[ d ]; - for( unsigned int d = 0; d < dim; ++d ) - in >> ori[ d ]; - for( unsigned int d = 0; d < dim; ++d ) - for( unsigned int e = 0; e < dim; ++e ) - in >> dir[ d ][ e ]; - - typename _TPath::Pointer path = _TPath::New( ); - path->SetSpacing( spa ); - path->SetOrigin( ori ); - path->SetDirection( dir ); - for( unsigned long s = 0; s < size; ++s ) - { - _TContinuousIndex idx; - for( unsigned int d = 0; d < dim; ++d ) - in >> idx[ d ]; - path->AddVertex( idx ); - - } // rof - out->AddBranch( path ); - in >> size; - - } // elihw -} - -#endif // __cpExtensions__Algorithms__SkeletonReader__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonToImageFilter.h b/lib/cpExtensions/Algorithms/SkeletonToImageFilter.h deleted file mode 100644 index 8c9d8fe..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonToImageFilter.h +++ /dev/null @@ -1,81 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonToImageFilter__h__ -#define __cpExtensions__Algorithms__SkeletonToImageFilter__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TSkeleton, class _TImage > - class SkeletonToImageFilter - : public itk::ImageSource< _TImage > - { - public: - // Basic types - typedef SkeletonToImageFilter Self; - typedef itk::ImageSource< _TImage > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TSkeleton TSkeleton; - typedef _TImage TImage; - typedef typename _TImage::IndexType TIndex; - typedef typename _TImage::PixelType TPixel; - typedef typename _TImage::PointType TPoint; - typedef typename _TImage::RegionType TRegion; - typedef itk::ImageBase< _TImage::ImageDimension > TImageBase; - - public: - itkNewMacro( Self ); - itkTypeMacro( SkeletonToImageFilter, itk::ImageSource ); - - itkGetConstMacro( InsideValue, TPixel ); - itkGetConstMacro( OutsideValue, TPixel ); - - itkSetMacro( InsideValue, TPixel ); - itkSetMacro( OutsideValue, TPixel ); - - public: - const TImageBase* GetTemplateImage( ) const; - void SetTemplateImage( const TImageBase* image ); - - const TSkeleton* GetSkeleton( ) const; - void SetSkeleton( const TSkeleton* skeleton ); - - protected: - SkeletonToImageFilter( ); - virtual ~SkeletonToImageFilter( ); - - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - SkeletonToImageFilter( const Self& ); - void operator=( const Self& ); - - protected: - TPixel m_InsideValue; - TPixel m_OutsideValue; - }; - - } // ecapseman - -} // ecapseman - -// ------------------------------------------------------------------------- -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__SkeletonToImageFilter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonToImageFilter.hxx b/lib/cpExtensions/Algorithms/SkeletonToImageFilter.hxx deleted file mode 100644 index 1f428c9..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonToImageFilter.hxx +++ /dev/null @@ -1,119 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonToImageFilter__hxx__ -#define __cpExtensions__Algorithms__SkeletonToImageFilter__hxx__ - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -const typename -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -TImageBase* -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -GetTemplateImage( ) const -{ - return( - dynamic_cast< const TImageBase* >( - this->itk::ProcessObject::GetInput( 0 ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -void -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -SetTemplateImage( const TImageBase* image ) -{ - this->itk::ProcessObject::SetNthInput( - 0, const_cast< TImageBase* >( image ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -const typename -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -TSkeleton* -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -GetSkeleton( ) const -{ - return( - dynamic_cast< const TSkeleton* >( - this->itk::ProcessObject::GetInput( 1 ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -void -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -SetSkeleton( const TSkeleton* skeleton ) -{ - this->itk::ProcessObject::SetNthInput( - 1, const_cast< TSkeleton* >( skeleton ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -SkeletonToImageFilter( ) - : Superclass( ), - m_InsideValue( TPixel( 1 ) ), - m_OutsideValue( TPixel( 0 ) ) -{ - this->SetNumberOfRequiredInputs( 2 ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -~SkeletonToImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton, class _TImage > -void cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage >:: -GenerateData( ) -{ - const TSkeleton* sk = this->GetSkeleton( ); - const TImageBase* im = this->GetTemplateImage( ); - TImage* out = this->GetOutput( 0 ); - - out->SetLargestPossibleRegion( im->GetLargestPossibleRegion( ) ); - out->SetRequestedRegion( im->GetRequestedRegion( ) ); - out->SetBufferedRegion( im->GetBufferedRegion( ) ); - out->SetSpacing( im->GetSpacing( ) ); - out->SetOrigin( im->GetOrigin( ) ); - out->SetDirection( im->GetDirection( ) ); - out->Allocate( ); - out->FillBuffer( this->m_OutsideValue ); - - // Fill skeleton - auto mIt = sk->BeginEdgesRows( ); - for( ; mIt != sk->EndEdgesRows( ); ++mIt ) - { - auto rIt = mIt->second.begin( ); - for( ; rIt != mIt->second.end( ); ++rIt ) - { - auto eIt = rIt->second.begin( ); - for( ; eIt != rIt->second.end( ); ++eIt ) - { - auto path = *eIt; - for( unsigned int i = 0; i < path->GetSize( ); ++i ) - out->SetPixel( path->GetVertex( i ), this->m_InsideValue ); - - } // rof - - } // rof - - } // rof -} - -#endif // __cpExtensions__Algorithms__SkeletonToImageFilter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonWriter.h b/lib/cpExtensions/Algorithms/SkeletonWriter.h deleted file mode 100644 index 3112693..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonWriter.h +++ /dev/null @@ -1,69 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonWriter__h__ -#define __cpExtensions__Algorithms__SkeletonWriter__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class _TSkeleton > - class SkeletonWriter - : public itk::ProcessObject - { - public: - // Basic types - typedef SkeletonWriter Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TSkeleton TSkeleton; - - public: - itkNewMacro( Self ); - itkTypeMacro( SkeletonWriter, itk::ImageSource ); - - itkGetConstMacro( FileName, std::string ); - itkSetMacro( FileName, std::string ); - - public: - const TSkeleton* GetInput( ) const; - void SetInput( const TSkeleton* skeleton ); - virtual void Update( ) cpExtensions_OVERRIDE; - - protected: - SkeletonWriter( ); - virtual ~SkeletonWriter( ); - - virtual void GenerateData( ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - SkeletonWriter( const Self& ); - void operator=( const Self& ); - - protected: - std::string m_FileName; - }; - - } // ecapseman - -} // ecapseman - -// ------------------------------------------------------------------------- -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__Algorithms__SkeletonWriter__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SkeletonWriter.hxx b/lib/cpExtensions/Algorithms/SkeletonWriter.hxx deleted file mode 100644 index 15093f6..0000000 --- a/lib/cpExtensions/Algorithms/SkeletonWriter.hxx +++ /dev/null @@ -1,159 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __cpExtensions__Algorithms__SkeletonWriter__hxx__ -#define __cpExtensions__Algorithms__SkeletonWriter__hxx__ - -#include - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -const _TSkeleton* cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -GetInput( ) const -{ - return( - dynamic_cast< const TSkeleton* >( - this->itk::ProcessObject::GetInput( 0 ) - ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -SetInput( const _TSkeleton* skeleton ) -{ - this->itk::ProcessObject::SetNthInput( - 0, const_cast< TSkeleton* >( skeleton ) - ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -Update( ) -{ - TSkeleton* input = const_cast< TSkeleton* >( this->GetInput( ) ); - if( input != NULL ) - { - input->UpdateOutputInformation( ); - input->UpdateOutputData( ); - this->GenerateData( ); - this->ReleaseInputs( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -SkeletonWriter( ) - : Superclass( ), - m_FileName( "" ) -{ - this->SetNumberOfRequiredInputs( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -~SkeletonWriter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Algorithms::SkeletonWriter< _TSkeleton >:: -GenerateData( ) -{ - const TSkeleton* sk = this->GetInput( ); - auto mIt = sk->BeginEdgesRows( ); - auto rIt = mIt->second.begin( ); - auto eIt = rIt->second.begin( ); - auto path = *eIt; - - // Write base information - std::stringstream out1, out2; - out1 << TSkeleton::Dimension << std::endl; - auto spa = path->GetSpacing( ); - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - out1 << spa[ d ] << " "; - out1 << std::endl; - auto dir = path->GetDirection( ); - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - for( unsigned int e = 0; e < TSkeleton::Dimension; ++e ) - out1 << dir[ d ][ e ] << " "; - out1 << std::endl; - auto ori = path->GetOrigin( ); - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - out1 << ori[ d ] << " "; - out1 << std::endl; - - // End points - auto end_points = sk->GetEndPoints( ); - out1 << end_points.size( ) << std::endl; - for( auto point : end_points ) - { - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - out1 << point[ d ] << " "; - out1 << std::endl; - - } // rof - - // Bifurcations - auto bifurcations = sk->GetBifurcations( ); - out1 << bifurcations.size( ) << std::endl; - for( auto point : bifurcations ) - { - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - out1 << point[ d ] << " "; - out1 << std::endl; - - } // rof - - // Write paths - unsigned long pathCount = 0; - mIt = sk->BeginEdgesRows( ); - for( ; mIt != sk->EndEdgesRows( ); ++mIt ) - { - auto rIt = mIt->second.begin( ); - for( ; rIt != mIt->second.end( ); ++rIt ) - { - auto eIt = rIt->second.begin( ); - for( ; eIt != rIt->second.end( ); ++eIt ) - { - auto path = *eIt; - pathCount++; - unsigned int size = path->GetSize( ); - out2 << size << std::endl; - for( unsigned int i = 0; i < path->GetSize( ); ++i ) - { - auto v = path->GetVertex( i ); - for( unsigned int d = 0; d < TSkeleton::Dimension; ++d ) - out2 << v[ d ] << " "; - - } // rof - out2 << std::endl; - - } // rof - - } // rof - - } // rof - out1 << pathCount << std::endl << out2.str( ); - - // Real write - std::ofstream file_stream( this->m_FileName.c_str( ), std::ofstream::binary ); - if( !file_stream ) - itkExceptionMacro( - << "Unable to write skeleton to \"" - << this->m_FileName - << "\"" - ); - file_stream.write( out1.str( ).c_str( ), out1.str( ).size( ) ); -} - -#endif // __cpExtensions__Algorithms__SkeletonWriter__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.h b/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.h deleted file mode 100644 index 2b81fb7..0000000 --- a/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__H__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace Algorithms - { - /** - */ - template< class I, class O = I > - class SpatialObjectMaskImageFilter - : public itk::ImageToImageFilter< I, O > - { - public: - typedef SpatialObjectMaskImageFilter Self; - typedef itk::ImageToImageFilter< I, O > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef I TInputImage; - typedef O TOutputImage; - - itkStaticConstMacro( InputDimension, unsigned int, I::ImageDimension ); - itkStaticConstMacro( OutputDimension, unsigned int, O::ImageDimension ); - -#ifdef ITK_USE_CONCEPT_CHECKING - itkConceptMacro( - SameDimensionCheck1, - ( itk::Concept::SameDimension< InputDimension, OutputDimension > ) - ); -#endif - - typedef typename I::RegionType TRegion; - typedef typename O::PixelType TOutPixel; - typedef itk::SpatialObject< InputDimension > TSpatialObject; - - public: - itkNewMacro( Self ); - itkTypeMacro( SpatialObjectMaskImageFilter, itk::ImageToImageFilter ); - - itkGetObjectMacro( SpatialObject, TSpatialObject ); - itkGetConstObjectMacro( SpatialObject, TSpatialObject ); - itkGetConstMacro( OutsideValue, TOutPixel ); - - itkSetObjectMacro( SpatialObject, TSpatialObject ); - itkSetMacro( OutsideValue, TOutPixel ); - - public: - O* GetPositiveOutput( ); - const O* GetPositiveOutput( ) const; - O* GetNegativeOutput( ); - const O* GetNegativeOutput( ) const; - - protected: - SpatialObjectMaskImageFilter( ); - virtual ~SpatialObjectMaskImageFilter( ); - - virtual void GenerateOutputInformation( ); - virtual void ThreadedGenerateData( - const TRegion& region, itk::ThreadIdType threadId - ); - - private: - // Purposely not implemented. - SpatialObjectMaskImageFilter( const Self& other ); - Self& operator=( const Self& other ); - - protected: - typename TSpatialObject::Pointer m_SpatialObject; - TOutPixel m_OutsideValue; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.hxx b/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.hxx deleted file mode 100644 index 2c3cac7..0000000 --- a/lib/cpExtensions/Algorithms/SpatialObjectMaskImageFilter.hxx +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__HXX__ - -#include -#include - -// ------------------------------------------------------------------------- -template< class I, class O > -O* cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -GetPositiveOutput( ) -{ - return( this->GetOutput( 0 ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -const O* cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -GetPositiveOutput( ) const -{ - return( this->GetOutput( 0 ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -O* cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -GetNegativeOutput( ) -{ - return( this->GetOutput( 1 ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -const O* cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -GetNegativeOutput( ) const -{ - return( this->GetOutput( 1 ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -SpatialObjectMaskImageFilter( ) - : Superclass( ) -{ - this->SetNumberOfRequiredInputs( 1 ); - this->SetNumberOfRequiredOutputs( 2 ); - this->SetNthOutput( 0, O::New( ) ); - this->SetNthOutput( 1, O::New( ) ); -} - -// ------------------------------------------------------------------------- -template< class I, class O > -cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -~SpatialObjectMaskImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class I, class O > -void cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -GenerateOutputInformation( ) -{ - const I* in = - dynamic_cast< const I* >( this->itk::ProcessObject::GetInput( 0 ) ); - for( unsigned int idx = 0; idx < this->GetNumberOfOutputs( ); ++idx ) - { - itk::DataObject* out = this->GetOutput( idx ); - if( out ) - out->CopyInformation( in ); - - } // rof -} - -// ------------------------------------------------------------------------- -template< class I, class O > -void cpExtensions::Algorithms::SpatialObjectMaskImageFilter< I, O >:: -ThreadedGenerateData( const TRegion& region, itk::ThreadIdType threadId ) -{ - if( this->m_SpatialObject.IsNull( ) ) - { - itkGenericExceptionMacro( << "No itk::SpatialObject given." ); - return; - - } // fi - - // Get inputs - const I* in = - dynamic_cast< const I* >( this->itk::ProcessObject::GetInput( 0 ) ); - O* pos_out = this->GetPositiveOutput( ); - O* neg_out = this->GetNegativeOutput( ); - const auto size0 = region.GetSize( 0 ); - if( size0 == 0 ) - return; - const auto nLines = region.GetNumberOfPixels( ) / size0; - - // Create iterators - itk::ImageScanlineConstIterator< I > iIt( in, region ); - itk::ImageScanlineIterator< O > pos_oIt( pos_out, region ); - itk::ImageScanlineIterator< O > neg_oIt( neg_out, region ); - itk::ProgressReporter progress( this, threadId, nLines ); - - // Main loop - typename TSpatialObject::PointType pnt; - while( !iIt.IsAtEnd( ) ) - { - while( !iIt.IsAtEndOfLine( ) ) - { - auto idx = iIt.GetIndex( ); - in->TransformIndexToPhysicalPoint( idx, pnt ); - if( this->m_SpatialObject->IsInside( pnt ) ) - { - pos_oIt.Set( TOutPixel( iIt.Get( ) ) ); - neg_oIt.Set( this->m_OutsideValue ); - } - else - { - neg_oIt.Set( TOutPixel( iIt.Get( ) ) ); - pos_oIt.Set( this->m_OutsideValue ); - - } // fi - ++iIt; - ++pos_oIt; - ++neg_oIt; - - } // elihw - iIt.NextLine( ); - pos_oIt.NextLine( ); - neg_oIt.NextLine( ); - progress.CompletedPixel( ); - - } // elihw -} - -#endif // __CPEXTENSIONS__ALGORITHMS__SPATIALOBJECTMASKIMAGEFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.h b/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.h deleted file mode 100644 index 7de8b66..0000000 --- a/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.h +++ /dev/null @@ -1,102 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__H__ -#define __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__H__ - -#include - -namespace cpExtensions -{ - namespace Algorithms - { - namespace Functor - { - /** - */ - template< typename _TInput > - class UnaryThreshold - { - public: - UnaryThreshold( ); - virtual ~UnaryThreshold( ); - - const _TInput& GetThreshold( ) const; - const _TInput& GetInsideValue( ) const; - const _TInput& GetOutsideValue( ) const; - const bool& GetStrict( ) const; - - void StrictOn( ); - void StrictOff( ); - void SetStrict( bool s ); - void SetThreshold( const _TInput& thresh ); - void SetInsideValue( const _TInput& value ); - void SetOutsideValue( const _TInput& value ); - bool operator!=( const UnaryThreshold& other ) const; - bool operator==( const UnaryThreshold& other ) const; - _TInput operator()( const _TInput& A ) const; - - private: - _TInput m_Threshold; - _TInput m_InsideValue; - _TInput m_OutsideValue; - bool m_Strict; - }; - } - - /** - */ - template< class _TImage > - class UnaryThresholdImageFilter - : public itk::UnaryFunctorImageFilter< _TImage, _TImage, cpExtensions::Algorithms::Functor::UnaryThreshold< typename _TImage::PixelType > > - { - public: - // Basic types - typedef typename _TImage::PixelType TPixel; - typedef cpExtensions::Algorithms::Functor::UnaryThreshold< TPixel > TFunctor; - typedef itk::UnaryFunctorImageFilter< _TImage, _TImage, TFunctor > Superclass; - typedef UnaryThresholdImageFilter Self; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TImage TImage; - - public: - itkNewMacro( Self ); - itkTypeMacro( UnaryThresholdImageFilter, itkUnaryFunctorImageFilter ); - - public: - const TPixel& GetThreshold( ) const; - const TPixel& GetInsideValue( ) const; - const TPixel& GetOutsideValue( ) const; - const bool& GetStrict( ) const; - - void StrictOn( ); - void StrictOff( ); - void SetStrict( bool s ); - void SetThreshold( const TPixel& thresh ); - void SetInsideValue( const TPixel& value ); - void SetOutsideValue( const TPixel& value ); - - protected: - UnaryThresholdImageFilter( ); - virtual ~UnaryThresholdImageFilter( ); - - private: - // Purposely not implemented - UnaryThresholdImageFilter( const Self& ); - void operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.hxx b/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.hxx deleted file mode 100644 index ff85edd..0000000 --- a/lib/cpExtensions/Algorithms/UnaryThresholdImageFilter.hxx +++ /dev/null @@ -1,245 +0,0 @@ -// ------------------------------------------------------------------------- -// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) -// ------------------------------------------------------------------------- - -#ifndef __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__HXX__ -#define __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__HXX__ - -// ------------------------------------------------------------------------- -template< typename _TInput > -cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -UnaryThreshold( ) - : m_Strict( false ) -{ - this->m_Threshold = itk::NumericTraits< _TInput >::NonpositiveMin( ); - this->m_OutsideValue = itk::NumericTraits< _TInput >::ZeroValue( ); - this->m_InsideValue = itk::NumericTraits< _TInput >::max( ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -~UnaryThreshold( ) -{ -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -const _TInput& cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -GetThreshold( ) const -{ - return( this->m_Threshold ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -const _TInput& cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -GetInsideValue( ) const -{ - return( this->m_InsideValue ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -const _TInput& cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -GetOutsideValue( ) const -{ - return( this->m_OutsideValue ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -const bool& cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -GetStrict( ) const -{ - return( this->m_Strict ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -StrictOn( ) -{ - this->SetStrict( true ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -StrictOff( ) -{ - this->SetStrict( false ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -SetStrict( bool s ) -{ - this->m_Strict = s; -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -SetThreshold( const _TInput& thresh ) -{ - this->m_Threshold = thresh; -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -SetInsideValue( const _TInput& value ) -{ - this->m_InsideValue = value; -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -void cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -SetOutsideValue( const _TInput& value ) -{ - this->m_OutsideValue = value; -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -bool cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -operator!=( const UnaryThreshold& other ) const -{ - return( - this->m_Threshold != other.m_Threshold || - itk::Math::NotExactlyEquals( this->m_InsideValue, other.m_InsideValue ) || - itk::Math::NotExactlyEquals( this->m_OutsideValue, other.m_OutsideValue ) - ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -bool cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -operator==( const UnaryThreshold& other ) const -{ - return( !( *this != other ) ); -} - -// ------------------------------------------------------------------------- -template< typename _TInput > -_TInput cpExtensions::Algorithms::Functor::UnaryThreshold< _TInput >:: -operator()( const _TInput& A ) const -{ - if( this->m_Strict ) - { - if( this->m_Threshold < A ) - return( this->m_InsideValue ); - return( this->m_OutsideValue ); - } - else - { - if( this->m_Threshold <= A ) - return( this->m_InsideValue ); - return( this->m_OutsideValue ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TImage > -const typename cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -TPixel& cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -GetThreshold( ) const -{ - return( this->GetFunctor( ).GetThreshold( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -const typename cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -TPixel& cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -GetInsideValue( ) const -{ - return( this->GetFunctor( ).GetInsideValue( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -const typename cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -TPixel& cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -GetOutsideValue( ) const -{ - return( this->GetFunctor( ).GetOutsideValue( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -const bool& cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -GetStrict( ) const -{ - return( this->GetFunctor( ).GetStrict( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -StrictOn( ) -{ - this->GetFunctor( ).SetStrict( true ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -StrictOff( ) -{ - this->GetFunctor( ).SetStrict( false ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -SetStrict( bool s ) -{ - this->GetFunctor( ).SetStrict( s ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -SetThreshold( const TPixel& thresh ) -{ - this->GetFunctor( ).SetThreshold( thresh ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -SetInsideValue( const TPixel& value ) -{ - this->GetFunctor( ).SetInsideValue( value ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -SetOutsideValue( const TPixel& value ) -{ - this->GetFunctor( ).SetOutsideValue( value ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -UnaryThresholdImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage >:: -~UnaryThresholdImageFilter( ) -{ -} - -#endif // __CPEXTENSIONS__ALGORITHMS__UNARYTHRESHOLDIMAGEFILTER__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Config.h.in b/lib/cpExtensions/Config.h.in deleted file mode 100644 index 4585244..0000000 --- a/lib/cpExtensions/Config.h.in +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef __cpExtensions__Config__h__ -#define __cpExtensions__Config__h__ - -#include - -/* - * ========================================================================= - * Identify OS - * ========================================================================= - */ -#define cpExtensions_OS_@CMAKE_SYSTEM_NAME@ - -/* - * ========================================================================= - * Some global values - * ========================================================================= - */ -#define cpExtensions_QT4_@QT4_FOUND@ -#ifdef cpExtensions_QT4_TRUE -# ifndef cpExtensions_QT4 -# define cpExtensions_QT4 -# endif // cpExtensions_QT4 -# define cpExtensions_QVTKWidget @cpPlugins_Qt4_VTKWidget@ -# include <@cpPlugins_Qt4_VTKWidget@.h> -#else // cpExtensions_QT4_TRUE -# undef cpExtensions_QT4 -#endif // cpExtensions_QT4_TRUE - -/* - * ========================================================================= - * Version numbers and strings - * ========================================================================= - */ - -#define cpExtensions_MAJOR_VERSION @prj_MAJOR_VERSION@ -#define cpExtensions_MINOR_VERSION @prj_MINOR_VERSION@ -#define cpExtensions_RELEASE_VERSION @prj_RELEASE_VERSION@ -#define cpExtensions_VERSION "@prj_VERSION@" -#define cpExtensions_SHORT_VERSION "@prj_SHORT_VERSION@" - -/* - * ========================================================================= - * Language related macros - * ========================================================================= - */ - -#if __cplusplus >= 201103L -# define cpExtensions_OVERRIDE override -# define cpExtensions_DELETE_FUNCTION =delete -# define cpExtensions_NULLPTR nullptr -# define cpExtensions_NOEXCEPT noexcept -# define cpExtensions_HAS_CXX11_STATIC_ASSERT -# define cpExtensions_HAS_CXX11_RVREF -#else -# define cpExtensions_OVERRIDE -# define cpExtensions_DELETE_FUNCTION -# define cpExtensions_NULLPTR NULL -# define cpExtensions_NOEXCEPT throw() -#endif - -// ------------------------------------------------------------------------- -#ifdef cpExtensions_OS_Windows -# define cpExtensions_SPRINTF( B, S, O ) sprintf_s( B, S, "%s", O ); -#else // cpExtensions_OS_Windows -# define cpExtensions_SPRINTF( B, S, O ) std::sprintf( B, "%s", O ); -#endif // cpExtensions_OS_Windows - -#endif // __cpExtensions__Config__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Graph.h b/lib/cpExtensions/DataStructures/Graph.h deleted file mode 100644 index d9e913d..0000000 --- a/lib/cpExtensions/DataStructures/Graph.h +++ /dev/null @@ -1,166 +0,0 @@ -#ifndef __cpExtensions__DataStructures__Graph__h__ -#define __cpExtensions__DataStructures__Graph__h__ - -#include -#include -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace DataStructures - { - /** \brief A generic graph with templated index types. - * - * @param _TVertex Vertex type. - * @param _TCost Cost type. - * @param _TIndex Index type (it should be a strict weak ordering type). - */ - template< class _TVertex, class _TCost, class _TIndex = unsigned long, class _TIndexCompare = std::less< _TIndex > > - class Graph - : public itk::DataObject - { - public: - typedef Graph Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TVertex TVertex; - typedef _TCost TCost; - typedef _TIndex TIndex; - typedef _TIndexCompare TIndexCompare; - - // Base types - typedef std::map< TIndex, TVertex, TIndexCompare > TVertices; - typedef std::vector< TCost > TEdges; - typedef std::map< TIndex, TEdges, TIndexCompare > TMatrixRow; - typedef std::map< TIndex, TMatrixRow, TIndexCompare > TMatrix; - - public: - itkNewMacro( Self ); - itkTypeMacro( Graph, itk::DataObject ); - - public: - /*! \brief Iterators over vertices. - * These allow you to iterate over all of graph's vertices. - * - * Typical iteration should be done as: - * - * TGraph g; - * ... - * TGraph::TVertices::[const_]iterator vIt = g.BeginVertices( ); - * for( ; vIt != g.EndVertices( ); ++vIt ) - * { - * vIt->first; --> this is the vertex's index <-- - * vIt->second; --> this is the vertex's value <-- - * } - */ - inline typename TVertices::iterator BeginVertices( ) - { return( this->m_Vertices.begin( ) ); } - inline typename TVertices::iterator EndVertices( ) - { return( this->m_Vertices.end( ) ); } - inline typename TVertices::const_iterator BeginVertices( ) const - { return( this->m_Vertices.begin( ) ); } - inline typename TVertices::const_iterator EndVertices( ) const - { return( this->m_Vertices.end( ) ); } - - /*! \brief Iterators over edges. - * These allow you to iterate over all of graph's edges. - * - * Typical iteration should be done as: - * - * TGraph g; - * ... - * TGraph::TMatrix::[const_]iterator mIt = g.BeginEdgesRows( ); - * for( ; mIt != g.EndEdgesRows( ); ++mIt ) - * { - * mIt->first; --> this is the row index. <-- - * TGraph::TMatrixRow::[const_]iterator rIt = mIt->second.begin( ); - * for( ; rIt != mIt->second.end( ); ++rIt ) - * { - * rIt->first; --> this is the column index. - * TGraph::TEdges::[const_]iterator eIt = rIt->second.begin( ); - * for( ; eIt != rIt->second.end( ); ++eIt ) - * *eIt; --> this is the cost between mIt->first and rIt->first - * } - * } - */ - inline typename TMatrix::iterator BeginEdgesRows( ) - { return( this->m_Matrix.begin( ) ); } - inline typename TMatrix::iterator EndEdgetsRows( ) - { return( this->m_Matrix.end( ) ); } - inline typename TMatrix::const_iterator BeginEdgesRows( ) const - { return( this->m_Matrix.begin( ) ); } - inline typename TMatrix::const_iterator EndEdgesRows( ) const - { return( this->m_Matrix.end( ) ); } - - /*! \brief Clear all vertices and edges. - */ - void Clear( ); - - /*! \brief Clear all edges. - */ - inline void ClearEdges( ) - { this->m_Matrix.clear( ); } - - /*! \brief Vertex manipulation methods. - * Names are self-explanatory. - */ - inline bool HasVertexIndex( const TIndex& i ) const - { return( this->m_Vertices.find( i ) != this->m_Vertices.end( ) ); } - inline void SetVertex( const TIndex& index, TVertex& vertex ) - { this->m_Vertices[ index ] = vertex; } - inline TVertex& GetVertex( const TIndex& index ) - { return( this->m_Vertices[ index ] ); } - inline const TVertex& GetVertex( const TIndex& index ) const - { return( this->m_Vertices[ index ] ); } - bool RenameVertex( const TIndex& old_index, const TIndex& new_index ); - void RemoveVertex( const TIndex& index ); - - /*! \brief Edge manipulation methods. - * Names are self-explanatory. - */ - inline void AddEdge( const TIndex& orig, const TIndex& dest, const TCost& cost ) - { this->m_Matrix[ orig ][ dest ].push_back( cost ); } - TEdges& GetEdges( const TIndex& orig, const TIndex& dest ); - const TEdges& GetEdges( const TIndex& orig, const TIndex& dest ) const; - bool HasEdge( const TIndex& orig, const TIndex& dest ) const; - void RemoveEdge( const TIndex& orig, const TIndex& dest, const TCost& cost ); - void RemoveEdges( const TIndex& orig, const TIndex& dest ); - - /*! \brief Returns graph's sinks. - * - * A sink is a special vertex which does not have any "exiting" edges. - * - * @return Sinks ordered by their index. - */ - std::set< TIndex, TIndexCompare > GetSinks( ) const; - - protected: - Graph( ); - virtual ~Graph( ); - - private: - // Purposely not implemented - Graph( const Self& other ); - Self& operator=( const Self& other ); - - protected: - TVertices m_Vertices; - TMatrix m_Matrix; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__DataStructures__Graph__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Graph.hxx b/lib/cpExtensions/DataStructures/Graph.hxx deleted file mode 100644 index 62c6b75..0000000 --- a/lib/cpExtensions/DataStructures/Graph.hxx +++ /dev/null @@ -1,267 +0,0 @@ -#ifndef __cpExtensions__DataStructures__Graph__hxx__ -#define __cpExtensions__DataStructures__Graph__hxx__ - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -void cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -Clear( ) -{ - this->m_Vertices.clear( ); - this->m_Matrix.clear( ); -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -bool cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -RenameVertex( const TIndex& old_index, const TIndex& new_index ) -{ - auto old_v = this->m_Vertices.find( old_index ); - auto new_v = this->m_Vertices.find( new_index ); - if( old_v != this->m_Vertices.end( ) && new_v == this->m_Vertices.end( ) ) - { - // Replace vertex - this->m_Vertices[ new_index ] = old_v->second; - this->m_Vertices.erase( old_index ); - - // Duplicate edges - auto mIt = this->m_Matrix.begin( ); - auto found_row = this->m_Matrix.end( ); - for( ; mIt != this->m_Matrix.end( ); ++mIt ) - { - if( mIt->first == old_index ) - found_row = mIt; - - auto rIt = mIt->second.begin( ); - for( ; rIt != mIt->second.end( ); ++rIt ) - { - if( mIt->first == old_index ) - this->m_Matrix[ new_index ][ rIt->first ] = rIt->second; - else if( rIt->first == old_index ) - this->m_Matrix[ mIt->first ][ new_index ] = rIt->second; - - } // rof - - } // rof - - // Delete old edges - if( found_row != this->m_Matrix.end( ) ) - this->m_Matrix.erase( found_row ); - - mIt = this->m_Matrix.begin( ); - for( ; mIt != this->m_Matrix.end( ); ++mIt ) - { - auto rIt = mIt->second.begin( ); - while( rIt != mIt->second.end( ) ) - { - if( rIt->first == old_index ) - { - mIt->second.erase( rIt ); - rIt = mIt->second.begin( ); - } - else - ++rIt; - - } // elihw - - } // rof - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -void cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -RemoveVertex( const TIndex& index ) -{ - auto i = this->m_Vertices.find( index ); - if( i != this->m_Vertices.end( ) ) - { - // Delete vertex - this->m_Vertices.erase( i ); - - // Delete edges starting from given vertex - auto mIt = this->m_Matrix.find( index ); - if( mIt != this->m_Matrix.end( ) ) - this->m_Matrix.erase( mIt ); - - // Delete edges arriving to given vertex - mIt = this->m_Matrix.begin( ); - for( ; mIt != this->m_Matrix.end( ); ++mIt ) - { - auto rIt = mIt->second.begin( ); - while( rIt != mIt->second.end( ) ) - { - if( rIt->first == index ) - { - mIt->second.erase( rIt ); - rIt = mIt->second.begin( ); - } - else - ++rIt; - - } // elihw - - } // rof - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -typename -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -TEdges& -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -GetEdges( const TIndex& orig, const TIndex& dest ) -{ - static TEdges null_edges; - auto o = this->m_Matrix.find( orig ); - if( o != this->m_Matrix.find( orig ) ) - { - auto d = o->second.find( dest ); - if( d == o->second.end( ) ) - { - null_edges.clear( ); - return( null_edges ); - } - else - return( d->second ); - } - else - { - null_edges.clear( ); - return( null_edges ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -const typename -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -TEdges& -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -GetEdges( const TIndex& orig, const TIndex& dest ) const -{ - static const TEdges null_edges; - auto o = this->m_Matrix.find( orig ); - if( o != this->m_Matrix.find( orig ) ) - { - auto d = o->second.find( dest ); - if( d == o->second.end( ) ) - return( null_edges ); - else - return( d->second ); - } - else - return( null_edges ); -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -bool cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -HasEdge( const TIndex& orig, const TIndex& dest ) const -{ - auto mIt = this->m_Matrix.find( orig ); - if( mIt != this->m_Matrix.end( ) ) - return( mIt->second.find( dest ) != mIt->second.end( ) ); - else - return( false ); -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -void cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -RemoveEdge( const TIndex& orig, const TIndex& dest, const TCost& cost ) -{ - auto m = this->m_Matrix.find( orig ); - if( m != this->m_Matrix.end( ) ) - { - auto r = m->second.find( dest ); - if( r != m->second.end( ) ) - { - auto e = r->second.end( ); - for( - auto i = r->second.begin( ); - i != r->second.end( ) && e == r->second.end( ); - ++i - ) - if( *i == cost ) - e = i; - if( e != r->second.end( ) ) - { - r->second.erase( e ); - if( r->second.size( ) == 0 ) - { - m->second.erase( r ); - if( m->second.size( ) == 0 ) - this->m_Matrix.erase( m ); - - } // fi - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -void cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -RemoveEdges( const TIndex& orig, const TIndex& dest ) -{ - auto m = this->m_Matrix.find( orig ); - if( m != this->m_Matrix.end( ) ) - { - auto r = m->second.find( dest ); - if( r != m->second.end( ) ) - { - m->second.erase( r ); - if( m->second.size( ) == 0 ) - this->m_Matrix.erase( m ); - - } // fi - - } // fi - -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -std::set< _TIndex, _TIndexCompare > -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -GetSinks( ) const -{ - std::set< _TIndex, _TIndexCompare > sinks; - - auto vIt = this->m_Vertices.begin( ); - for( ; vIt != this->m_Vertices.end( ); ++vIt ) - sinks.insert( vIt->first ); - auto mIt = this->m_Matrix.begin( ); - for( ; mIt != this->m_Matrix.end( ); ++mIt ) - sinks.erase( mIt->first ); - - return( sinks ); -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -Graph( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TVertex, class _TCost, class _TIndex, class _TIndexCompare > -cpExtensions::DataStructures::Graph< _TVertex, _TCost, _TIndex, _TIndexCompare >:: -~Graph( ) -{ -} - -#endif // __cpExtensions__DataStructures__Graph__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/PolyLineParametricPath.h b/lib/cpExtensions/DataStructures/PolyLineParametricPath.h deleted file mode 100644 index 7f12200..0000000 --- a/lib/cpExtensions/DataStructures/PolyLineParametricPath.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef __cpExtensions__DataStructures__PolyLineParametricPath__h__ -#define __cpExtensions__DataStructures__PolyLineParametricPath__h__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace DataStructures - { - /** - */ - template< unsigned int _VDim > - class PolyLineParametricPath - : public itk::PolyLineParametricPath< _VDim > - { - public: - typedef PolyLineParametricPath Self; - typedef itk::PolyLineParametricPath< _VDim > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef itk::ImageBase< _VDim > TImageBase; - typedef typename TImageBase::SpacingType TSpacing; - typedef typename TImageBase::PointType TPoint; - typedef typename TImageBase::DirectionType TDirection; - typedef typename Superclass::ContinuousIndexType TContinuousIndex; - typedef typename TContinuousIndex::IndexType TIndex; - - typedef typename TPoint::VectorType TVector; - typedef cpExtensions::Algorithms::BezierCurveFunction< TVector > TBezier; - - public: - itkNewMacro( Self ); - itkTypeMacro( PolyLineParametricPath, itk::PolyLineParametricPath ); - - itkGetConstReferenceMacro( Spacing, TSpacing ); - itkGetConstReferenceMacro( Origin, TPoint ); - itkGetConstReferenceMacro( Direction, TDirection ); - itkGetConstReferenceMacro( InverseDirection, TDirection ); - - itkSetMacro( Origin, TPoint ); - - public: - void AddVertex( const TContinuousIndex& vertex ); - unsigned long GetSize( ) const; - TContinuousIndex GetContinuousVertex( unsigned long i ) const; - TIndex GetVertex( unsigned long i ) const; - TPoint GetPoint( unsigned long i ) const; - TPoint GetSmoothPoint( double u ) const; - - virtual void SetSpacing( const TSpacing& spac ); - virtual void SetSpacing( const double spac[ _VDim ] ); - virtual void SetSpacing( const float spac[ _VDim ] ); - virtual void SetOrigin( const double ori[ _VDim ] ); - virtual void SetOrigin( const float ori[ _VDim ] ); - virtual void SetDirection( const TDirection& dir ); - - template< class _TRefImage > - inline void SetReferenceImage( const _TRefImage* image ) - { - this->SetSpacing( image->GetSpacing( ) ); - this->SetOrigin( image->GetOrigin( ) ); - this->SetDirection( image->GetDirection( ) ); - } - - protected: - PolyLineParametricPath( ); - virtual ~PolyLineParametricPath( ); - - virtual void _ComputeIndexToPhysicalPointMatrices( ); - - private: - // Purposely not implemented - PolyLineParametricPath( const Self& other ); - Self& operator=( const Self& other ); - - protected: - typename TBezier::Pointer m_Bezier; - - TSpacing m_Spacing; - TPoint m_Origin; - TDirection m_Direction; - TDirection m_InverseDirection; - TDirection m_IndexToPhysicalPoint; - TDirection m_PhysicalPointToIndex; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__DataStructures__PolyLineParametricPath__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/PolyLineParametricPath.hxx b/lib/cpExtensions/DataStructures/PolyLineParametricPath.hxx deleted file mode 100644 index 635c8b7..0000000 --- a/lib/cpExtensions/DataStructures/PolyLineParametricPath.hxx +++ /dev/null @@ -1,215 +0,0 @@ -#ifndef __cpExtensions__DataStructures__PolyLineParametricPath__hxx__ -#define __cpExtensions__DataStructures__PolyLineParametricPath__hxx__ - -#include -#include - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -AddVertex( const TContinuousIndex& vertex ) -{ - this->Superclass::AddVertex( vertex ); - this->m_Bezier->AddPoint( - this->GetPoint( this->GetSize( ) - 1 ).GetVectorFromOrigin( ) - ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -unsigned long cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -GetSize( ) const -{ - return( this->GetVertexList( )->Size( ) ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -typename cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -TContinuousIndex -cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -GetContinuousVertex( unsigned long i ) const -{ - return( this->GetVertexList( )->GetElement( i ) ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -typename cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -TIndex cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -GetVertex( unsigned long i ) const -{ - TContinuousIndex cidx = this->GetContinuousVertex( i ); - TIndex idx; - for( unsigned int d = 0; d < _VDim; ++d ) - idx[ d ] = cidx[ d ]; - return( idx ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -typename cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -TPoint cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -GetPoint( unsigned long i ) const -{ - typedef typename TPoint::CoordRepType _TCoordRep; - TPoint pnt; - TContinuousIndex idx = this->GetVertex( i ); - for( unsigned int r = 0; r < _VDim; ++r ) - { - _TCoordRep sum = itk::NumericTraits< _TCoordRep >::ZeroValue( ); - for( unsigned int c = 0; c < _VDim; ++c ) - sum += this->m_IndexToPhysicalPoint( r, c ) * idx[ c ]; - pnt[ r ] = sum + this->m_Origin[ r ]; - - } // rof - return( pnt ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -typename cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -TPoint cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -GetSmoothPoint( double u ) const -{ - TPoint p; - p.Fill( 0 ); - p += this->m_Bezier->Evaluate( u ); - return( p ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetSpacing( const TSpacing& spac ) -{ - if( this->m_Spacing != spac ) - { - this->m_Spacing = spac; - this->_ComputeIndexToPhysicalPointMatrices( ); - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetSpacing( const double spac[ _VDim ] ) -{ - this->SetSpacing( TSpacing( spac ) ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetSpacing( const float spac[ _VDim ] ) -{ - TSpacing s; - for( unsigned int d = 0; d < _VDim; ++d ) - s[ d ] = spac[ d ]; - this->SetSpacing( s ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetOrigin( const double ori[ _VDim ] ) -{ - this->SetOrigin( TPoint( ori ) ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetOrigin( const float ori[ _VDim ] ) -{ - this->SetOrigin( TPoint( ori ) ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -SetDirection( const TDirection& dir ) -{ - bool modified = false; - for( unsigned int r = 0; r < _VDim; r++ ) - { - for( unsigned int c = 0; c < _VDim; c++ ) - { - if( - itk::Math::NotExactlyEquals( - this->m_Direction[ r ][ c ], dir[ r ][ c ] - ) - ) - { - this->m_Direction[ r ][ c ] = dir[ r ][ c ]; - modified = true; - } // fi - - } // rof - - } // rof - if( modified ) - { - this->_ComputeIndexToPhysicalPointMatrices( ); - this->m_InverseDirection = this->m_Direction.GetInverse( ); - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -PolyLineParametricPath( ) - : Superclass( ) -{ - this->m_Bezier = TBezier::New( ); - - this->m_Spacing.Fill( 1.0 ); - this->m_Origin.Fill( 0.0 ); - this->m_Direction.SetIdentity( ); - this->m_InverseDirection.SetIdentity( ); - this->m_IndexToPhysicalPoint.SetIdentity( ); - this->m_PhysicalPointToIndex.SetIdentity( ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -~PolyLineParametricPath( ) -{ -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::PolyLineParametricPath< _VDim >:: -_ComputeIndexToPhysicalPointMatrices( ) -{ - TDirection scale; - scale.Fill( 0.0 ); - for( unsigned int i = 0; i < _VDim; i++ ) - { - if( this->m_Spacing[ i ] == 0.0 ) - itkExceptionMacro( - "A spacing of 0 is not allowed: Spacing is " << this->m_Spacing - ); - scale[ i ][ i ] = this->m_Spacing[ i ]; - - } // rof - - if( vnl_determinant( this->m_Direction.GetVnlMatrix( ) ) == 0.0 ) - itkExceptionMacro( - << "Bad direction, determinant is 0. Direction is " - << this->m_Direction - ); - this->m_IndexToPhysicalPoint = this->m_Direction * scale; - this->m_PhysicalPointToIndex = this->m_IndexToPhysicalPoint.GetInverse( ); - this->Modified( ); -} - -#endif // __cpExtensions__DataStructures__PolyLineParametricPath__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Simple3DCurve.cxx b/lib/cpExtensions/DataStructures/Simple3DCurve.cxx deleted file mode 100644 index 1d1a92e..0000000 --- a/lib/cpExtensions/DataStructures/Simple3DCurve.cxx +++ /dev/null @@ -1,137 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -Modified( ) const -{ - this->Superclass::Modified( ); - this->m_FramesUpdated = false; -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -void cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -Clear( ) -{ - this->m_Points.clear( ); - this->m_Frames.clear( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -unsigned long cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -GetNumberOfPoints( ) const -{ - return( this->m_Points.size( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -const typename cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -TMatrix& cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -GetFrame( unsigned int id ) const -{ - if( !( this->m_FramesUpdated ) ) - { - unsigned long N = this->m_Points.size( ); - - std::vector< TVector > tg( N ); - tg[ 0 ] = this->m_Points[ 1 ] - this->m_Points[ 0 ]; - tg[ N - 1 ] = this->m_Points[ N - 1 ] - this->m_Points[ N - 2 ]; - for( unsigned int i = 1; i < N - 1; ++i ) - tg[ i ] = this->m_Points[ i + 1 ] - this->m_Points[ i - 1 ]; - - std::vector< TVector > no( N ); - std::vector< TVector > bn( N ); - TVector prev_tg( _TScalar( 0 ) ), prev_no( _TScalar( 0 ) ); - prev_tg[ 0 ] = _TScalar( 1 ); - prev_no[ 1 ] = _TScalar( 1 ); - for( unsigned int i = 0; i < N; ++i ) - { - auto ntg = tg[ i ].GetNorm( ); - if( double( ntg ) > double( 0 ) ) - tg[ i ] /= ntg; - - _TScalar ct = prev_tg * tg[ i ]; - TVector a = itk::CrossProduct( prev_tg, tg[ i ] ); - _TScalar st = a.GetNorm( ); - if( st > _TScalar( 0 ) ) - a /= st; - - no[ i ] = - ( prev_no * ct ) + - ( itk::CrossProduct( a, prev_no ) * st ) + - ( a * ( ( a * prev_no ) * ( _TScalar( 1 ) - ct ) ) ); - auto nno = no[ i ].GetNorm( ); - if( double( nno ) > double( 0 ) ) - no[ i ] /= nno; - - bn[ i ] = itk::CrossProduct( tg[ i ], no[ i ] ); - - prev_tg = tg[ i ]; - prev_no = no[ i ]; - - } // rof - - this->m_Frames.clear( ); - for( unsigned int i = 0; i < N; ++i ) - { - TMatrix m; - for( unsigned int d = 0; d < 3; ++d ) - { - m[ d ][ 0 ] = tg[ i ][ d ]; - m[ d ][ 1 ] = no[ i ][ d ]; - m[ d ][ 2 ] = bn[ i ][ d ]; - - } // rof - this->m_Frames.push_back( m ); - - } // rof - - this->m_FramesUpdated = true; - - } // fi - return( this->m_Frames[ id ] ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -const typename cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -TPoint& cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -GetPoint( unsigned int id ) const -{ - return( this->m_Points[ id ] ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -typename cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -TVector cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -GetVector( unsigned int id ) const -{ - return( this->m_Points[ id ].GetVectorFromOrigin( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -Simple3DCurve( ) - : Superclass( ), - m_FramesUpdated( false ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TScalar > -cpExtensions::DataStructures::Simple3DCurve< _TScalar >:: -~Simple3DCurve( ) -{ -} - -// ------------------------------------------------------------------------- -template class cpExtensions::DataStructures::Simple3DCurve< float >; -template class cpExtensions::DataStructures::Simple3DCurve< double >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Simple3DCurve.h b/lib/cpExtensions/DataStructures/Simple3DCurve.h deleted file mode 100644 index 0641d43..0000000 --- a/lib/cpExtensions/DataStructures/Simple3DCurve.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef __cpExtensions__DataStructures__Simple3DCurve__h__ -#define __cpExtensions__DataStructures__Simple3DCurve__h__ - -#include -#include -#include -#include -#include - -namespace cpExtensions -{ - namespace DataStructures - { - /** - */ - template< class _TScalar > - class cpExtensions_EXPORT Simple3DCurve - : public itk::DataObject - { - public: - typedef Simple3DCurve Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef _TScalar TScalar; - typedef itk::Matrix< TScalar, 3, 3 > TMatrix; - typedef itk::Point< TScalar, 3 > TPoint; - typedef typename TPoint::VectorType TVector; - - public: - itkNewMacro( Self ); - itkTypeMacro( Simple3DCurve, itk::DataObject ); - - public: - template< class _TVector > - inline void AddPoint( const _TVector& v ) - { - TPoint p; - p[ 0 ] = v[ 0 ]; - p[ 1 ] = v[ 1 ]; - p[ 2 ] = v[ 2 ]; - this->m_Points.push_back( p ); - this->Modified( ); - } - - virtual void Modified( ) const cpExtensions_OVERRIDE; - void Clear( ); - unsigned long GetNumberOfPoints( ) const; - const TMatrix& GetFrame( unsigned int id ) const; - const TPoint& GetPoint( unsigned int id ) const; - TVector GetVector( unsigned int id ) const; - - protected: - Simple3DCurve( ); - virtual ~Simple3DCurve( ); - - private: - // Purposely not implemented - Simple3DCurve( const Self& other ); - Self& operator=( const Self& other ); - - protected: - std::vector< TPoint > m_Points; - mutable std::vector< TMatrix > m_Frames; - mutable bool m_FramesUpdated; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__DataStructures__Simple3DCurve__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Skeleton.h b/lib/cpExtensions/DataStructures/Skeleton.h deleted file mode 100644 index 671b8ac..0000000 --- a/lib/cpExtensions/DataStructures/Skeleton.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef __cpExtensions__DataStructures__Skeleton__h__ -#define __cpExtensions__DataStructures__Skeleton__h__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace DataStructures - { - /** - */ - template< unsigned int _VDim > - class Skeleton - : public Graph< typename PolyLineParametricPath< _VDim >::TIndex, typename PolyLineParametricPath< _VDim >::Pointer, typename PolyLineParametricPath< _VDim >::TIndex, typename PolyLineParametricPath< _VDim >::TIndex::LexicographicCompare > - { - public: - typedef PolyLineParametricPath< _VDim > TPath; - typedef typename TPath::TIndex TIndex; - typedef typename TIndex::LexicographicCompare TIndexCompare; - typedef typename TPath::Pointer TPathPointer; - - itkStaticConstMacro( Dimension, unsigned int, _VDim ); - - typedef Graph< TIndex, TPathPointer, TIndex, TIndexCompare > Superclass; - typedef Skeleton Self; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( Skeleton, Graph ); - - public: - void AddBranch( TPath* path ); - const TPath* GetBranch( const TIndex& a, const TIndex& b ) const; - - std::vector< TIndex > GetEndPoints( ) const; - std::vector< TIndex > GetBifurcations( ) const; - - protected: - Skeleton( ); - virtual ~Skeleton( ); - - private: - // Purposely not implemented - Skeleton( const Self& other ); - Self& operator=( const Self& other ); - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -# include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __cpExtensions__DataStructures__Skeleton__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/DataStructures/Skeleton.hxx b/lib/cpExtensions/DataStructures/Skeleton.hxx deleted file mode 100644 index 12f463f..0000000 --- a/lib/cpExtensions/DataStructures/Skeleton.hxx +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef __cpExtensions__DataStructures__Skeleton__hxx__ -#define __cpExtensions__DataStructures__Skeleton__hxx__ - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -void cpExtensions::DataStructures::Skeleton< _VDim >:: -AddBranch( TPath* path ) -{ - // Check inputs - if( path == NULL ) - return; - unsigned long size = path->GetSize( ); - if( size == 0 ) - return; - TIndex a = path->GetVertex( 0 ); - TIndex b = path->GetVertex( size - 1 ); - if( this->HasEdge( a, b ) ) - return; - - // Add path - this->SetVertex( a, a ); - this->SetVertex( b, b ); - this->AddEdge( a, b, path ); - this->AddEdge( b, a, path ); - // TODO: this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -const typename cpExtensions::DataStructures::Skeleton< _VDim >:: -TPath* cpExtensions::DataStructures::Skeleton< _VDim >:: -GetBranch( const TIndex& a, const TIndex& b ) const -{ - static const TPath* null_path = NULL; - if( this->HasEdge( a, b ) ) - return( this->GetEdges( a, b ).front( ) ); - else - return( null_path ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -std::vector< typename cpExtensions::DataStructures::Skeleton< _VDim >::TIndex > -cpExtensions::DataStructures::Skeleton< _VDim >:: -GetEndPoints( ) const -{ - std::vector< TIndex > res; - auto mIt = this->BeginEdgesRows( ); - for( ; mIt != this->EndEdgesRows( ); ++mIt ) - { - unsigned long count = mIt->second.size( ); - if( count == 1 ) - res.push_back( mIt->first ); - - } // rof - return( res ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -std::vector< typename cpExtensions::DataStructures::Skeleton< _VDim >::TIndex > -cpExtensions::DataStructures::Skeleton< _VDim >:: -GetBifurcations( ) const -{ - std::vector< TIndex > res; - auto mIt = this->BeginEdgesRows( ); - for( ; mIt != this->EndEdgesRows( ); ++mIt ) - { - unsigned long count = mIt->second.size( ); - if( count > 1 ) - res.push_back( mIt->first ); - - } // rof - return( res ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -cpExtensions::DataStructures::Skeleton< _VDim >:: -Skeleton( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -cpExtensions::DataStructures::Skeleton< _VDim >:: -~Skeleton( ) -{ -} - -#endif // __cpExtensions__DataStructures__Skeleton__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/BaseStyle.cxx b/lib/cpExtensions/Interaction/BaseStyle.cxx deleted file mode 100644 index 39bd24b..0000000 --- a/lib/cpExtensions/Interaction/BaseStyle.cxx +++ /dev/null @@ -1,437 +0,0 @@ -#include - -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -long cpExtensions::Interaction::BaseStyle::_TMouseButtonEvent:: -MaxDoubleClick = 350; // ms - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -SetSetDoubleClickDelay( long delay ) -{ - Self::_TMouseButtonEvent::MaxDoubleClick = delay; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -DelegateTDxEvent( unsigned long event, void* calldata ) -{ - // TODO - std::cerr << "No TDx support at this time!" << std::endl; - std::exit( 1 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnMouseMove( ) -{ - if( this->Interactor == NULL ) - return; - - // Get modifiers - bool alt = ( this->Interactor->GetAltKey( ) == 1 ); - bool ctr = ( this->Interactor->GetControlKey( ) == 1 ); - bool sft = ( this->Interactor->GetShiftKey( ) == 1 ); - ButtonID button = this->GetButtonID( ); - - // Invoke possible generic events - auto x = this->Interactor->GetEventPosition( )[ 0 ]; - auto y = this->Interactor->GetEventPosition( )[ 1 ]; - if( button == Self::ButtonID_Right ) - { - if( !alt && !ctr && !sft ) - { - this->FindPokedRenderer( x, y ); - this->Dolly( ); - - } // fi - } - else if( button == Self::ButtonID_Middle ) - { - if( !alt && !ctr && !sft ) - { - this->FindPokedRenderer( x, y ); - this->Pan( ); - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnLeftButtonDown( ) -{ - this->m_ActiveButton = Self::ButtonID_Left; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnLeftButtonUp( ) -{ - this->m_ActiveButton = Self::ButtonID_None; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnMiddleButtonDown( ) -{ - this->m_ActiveButton = Self::ButtonID_Middle; - - // Get current position on the associated actors - if( this->Interactor == NULL ) - return; - - // Get modifiers - bool alt = ( this->Interactor->GetAltKey( ) == 1 ); - bool ctr = ( this->Interactor->GetControlKey( ) == 1 ); - bool sft = ( this->Interactor->GetShiftKey( ) == 1 ); - if( !alt && !ctr && !sft ) - this->StartPan( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnMiddleButtonUp( ) -{ - this->m_ActiveButton = Self::ButtonID_None; - - // Get current position on the associated actors - if( this->Interactor == NULL ) - return; - - switch( this->State ) - { - case VTKIS_PAN: - this->EndPan( ); - break; - default: - break; - } // hctiws -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnRightButtonDown( ) -{ - this->m_ActiveButton = Self::ButtonID_Right; - - // Get current position on the associated actors - if( this->Interactor == NULL ) - return; - - // Get modifiers - bool alt = ( this->Interactor->GetAltKey( ) == 1 ); - bool ctr = ( this->Interactor->GetControlKey( ) == 1 ); - bool sft = ( this->Interactor->GetShiftKey( ) == 1 ); - if( !alt && !ctr && !sft ) - this->StartDolly( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -OnRightButtonUp( ) -{ - this->m_ActiveButton = Self::ButtonID_None; - - // Get current position on the associated actors - if( this->Interactor == NULL ) - return; - - switch( this->State ) - { - case VTKIS_DOLLY: - this->EndDolly( ); - break; - default: - break; - } // hctiws -} - -// ------------------------------------------------------------------------- -#define cpExtensions_BaseStyle_Click( S, T ) \ - void cpExtensions::Interaction::BaseStyle:: \ - On##S##T( ) \ - { \ - if( this->Interactor == NULL ) \ - return; \ - static int idx[ 2 ]; \ - static double pos[ 3 ]; \ - if( !( this->_PickPosition( idx, pos ) ) ) \ - return; \ - auto i = this->m_Mouse##T##Commands.begin( ); \ - for( ; i != this->m_Mouse##T##Commands.end( ); ++i ) \ - i->first( \ - i->second, \ - Self::ButtonID_##S, \ - idx, pos, \ - this->Interactor->GetAltKey( ) == 1, \ - this->Interactor->GetControlKey( ) == 1, \ - this->Interactor->GetShiftKey( ) == 1 \ - ); \ - } - -cpExtensions_BaseStyle_Click( Left, Click ); -cpExtensions_BaseStyle_Click( Middle, Click ); -cpExtensions_BaseStyle_Click( Right, Click ); -cpExtensions_BaseStyle_Click( Left, DoubleClick ); -cpExtensions_BaseStyle_Click( Middle, DoubleClick ); -cpExtensions_BaseStyle_Click( Right, DoubleClick ); - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -Dolly( ) -{ - if( this->CurrentRenderer == NULL ) - return; - - vtkRenderWindowInteractor* rwi = this->GetInteractor( ); - double *center = this->CurrentRenderer->GetCenter( ); - int dy = rwi->GetEventPosition( )[ 1 ] - rwi->GetLastEventPosition( )[ 1 ]; - double dyf = this->m_MotionFactor * dy / center[ 1 ]; - this->_Dolly( std::pow( 1.1, dyf ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -Pan( ) -{ - if( this->CurrentRenderer == NULL ) - return; - - vtkRenderWindowInteractor* rwi = this->Interactor; - double viewFocus[ 4 ], focalDepth, viewPoint[ 3 ]; - double newPickPoint[ 4 ], oldPickPoint[ 4 ], motionVector[ 3 ]; - - // Calculate the focal depth since we'll be using it a lot - vtkCamera* camera = this->CurrentRenderer->GetActiveCamera( ); - camera->GetFocalPoint( viewFocus ); - this->ComputeWorldToDisplay( - viewFocus[ 0 ], viewFocus[ 1 ], viewFocus[ 2 ], viewFocus - ); - focalDepth = viewFocus[ 2 ]; - this->ComputeDisplayToWorld( - rwi->GetEventPosition( )[ 0 ], - rwi->GetEventPosition( )[ 1 ], - focalDepth, - newPickPoint - ); - - // Has to recalc old mouse point since the viewport has moved, - // so can't move it outside the loop - this->ComputeDisplayToWorld( - rwi->GetLastEventPosition( )[ 0 ], - rwi->GetLastEventPosition( )[ 1 ], - focalDepth, - oldPickPoint - ); - - // Camera motion is reversed - motionVector[ 0 ] = oldPickPoint[ 0 ] - newPickPoint[ 0 ]; - motionVector[ 1 ] = oldPickPoint[ 1 ] - newPickPoint[ 1 ]; - motionVector[ 2 ] = oldPickPoint[ 2 ] - newPickPoint[ 2 ]; - - camera->GetFocalPoint( viewFocus ); - camera->GetPosition( viewPoint ); - camera->SetFocalPoint( - motionVector[ 0 ] + viewFocus[ 0 ], - motionVector[ 1 ] + viewFocus[ 1 ], - motionVector[ 2 ] + viewFocus[ 2 ] - ); - camera->SetPosition( - motionVector[ 0 ] + viewPoint[ 0 ], - motionVector[ 1 ] + viewPoint[ 1 ], - motionVector[ 2 ] + viewPoint[ 2 ] - ); - if( rwi->GetLightFollowCamera( ) ) - this->CurrentRenderer->UpdateLightsGeometryToFollowCamera( ); - rwi->Render( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::BaseStyle:: -BaseStyle( ) - : Superclass( ), - m_MotionFactor( double( 10 ) ) -{ - this->m_LeftButtonEvent.Reset( ); - this->m_MiddleButtonEvent.Reset( ); - this->m_RightButtonEvent.Reset( ); - this->m_ActiveButton = Self::ButtonID_None; - - this->EventCallbackCommand->SetCallback( Self::_ProcessEvents ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::BaseStyle:: -~BaseStyle( ) -{ -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -_Dolly( double factor ) -{ - if( this->CurrentRenderer == NULL ) - return; - - vtkCamera* camera = this->CurrentRenderer->GetActiveCamera( ); - if( camera->GetParallelProjection( ) == 0 ) - { - camera->Dolly( factor ); - if( this->AutoAdjustCameraClippingRange ) - this->CurrentRenderer->ResetCameraClippingRange( ); - } - else - camera->SetParallelScale( camera->GetParallelScale( ) / factor ); - if( this->Interactor->GetLightFollowCamera( ) ) - this->CurrentRenderer->UpdateLightsGeometryToFollowCamera( ); - this->Interactor->Render( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::BaseStyle:: -_ProcessEvents( - vtkObject* object, - unsigned long event, - void* clientdata, - void* calldata - ) -{ - // Get active style and interactor - Self* s = reinterpret_cast< Self* >( clientdata ); - if( s == NULL ) - return; - - // Process events - switch( event ) - { - case vtkCommand::MouseMoveEvent: - { - s->OnMouseMove( ); - } - break; - case vtkCommand::LeftButtonPressEvent: - { - unsigned char nc = s->m_LeftButtonEvent.Clicks( ); - if( nc == 2 ) - s->OnLeftDoubleClick( ); - else if( nc == 1 ) - s->OnLeftClick( ); - s->OnLeftButtonDown( ); - } - break; - case vtkCommand::LeftButtonReleaseEvent: - { - s->m_LeftButtonEvent.Release( ); - s->OnLeftButtonUp( ); - } - break; - case vtkCommand::MiddleButtonPressEvent: - { - unsigned char nc = s->m_MiddleButtonEvent.Clicks( ); - if( nc == 2 ) - s->OnMiddleDoubleClick( ); - else if( nc == 1 ) - s->OnMiddleClick( ); - s->OnMiddleButtonDown( ); - } - break; - case vtkCommand::MiddleButtonReleaseEvent: - { - s->m_MiddleButtonEvent.Release( ); - s->OnMiddleButtonUp( ); - } - break; - case vtkCommand::RightButtonPressEvent: - { - unsigned char nc = s->m_RightButtonEvent.Clicks( ); - if( nc == 2 ) - s->OnRightDoubleClick( ); - else if( nc == 1 ) - s->OnRightClick( ); - s->OnRightButtonDown( ); - } - break; - case vtkCommand::RightButtonReleaseEvent: - { - s->m_RightButtonEvent.Release( ); - s->OnRightButtonUp( ); - } - break; - case vtkCommand::MouseWheelForwardEvent: - { - s->OnMouseWheelForward( ); - } - break; - case vtkCommand::MouseWheelBackwardEvent: - { - s->OnMouseWheelBackward( ); - } - break; - case vtkCommand::KeyPressEvent: - { - s->OnKeyDown( ); - s->OnKeyPress( ); - } - break; - case vtkCommand::KeyReleaseEvent: - { - s->OnKeyUp( ); - s->OnKeyRelease( ); - } - break; - case vtkCommand::CharEvent: - { - s->OnChar( ); - } - break; - case vtkCommand::ExposeEvent: - { - s->OnExpose( ); - } - break; - case vtkCommand::ConfigureEvent: - { - s->OnConfigure( ); - } - break; - case vtkCommand::EnterEvent: - { - s->OnEnter( ); - } - break; - case vtkCommand::LeaveEvent: - { - s->OnLeave( ); - } - break; - case vtkCommand::TimerEvent: - { - // Do nothing - } - break; - case vtkCommand::DeleteEvent: - { - s->SetInteractor( 0 ); - } - break; - case vtkCommand::TDxMotionEvent: - case vtkCommand::TDxButtonPressEvent: - case vtkCommand::TDxButtonReleaseEvent: - { - s->DelegateTDxEvent( event, calldata ); - } - break; - default: - break; - } // hctiws -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/BaseStyle.h b/lib/cpExtensions/Interaction/BaseStyle.h deleted file mode 100644 index cee7078..0000000 --- a/lib/cpExtensions/Interaction/BaseStyle.h +++ /dev/null @@ -1,193 +0,0 @@ -#ifndef __cpExtensions__Interaction__BaseStyle__h__ -#define __cpExtensions__Interaction__BaseStyle__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -#define cpExtensions_BaseStyle_Commands( C ) \ - protected: \ - std::map< T##C##Command, void* > m_##C##Commands; \ - public: \ - inline void Add##C##Command( T##C##Command c, void* d ) \ - { \ - if( c != NULL ) \ - { \ - this->m_##C##Commands[ c ] = d; \ - this->Modified( ); \ - } \ - } \ - inline void Remove##C##Command( T##C##Command c ) \ - { \ - std::map< T##C##Command, void* >::iterator i = \ - this->m_##C##Commands.find( c ); \ - if( i != this->m_##C##Commands.end( ) ) \ - { \ - this->m_##C##Commands.erase( i ); \ - this->Modified( ); \ - } \ - } - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Interaction - { - /** - */ - class cpExtensions_EXPORT BaseStyle - : public vtkInteractorStyle - { - public: - typedef BaseStyle Self; - vtkTypeMacro( BaseStyle, vtkInteractorStyle ); - - enum ButtonID - { - ButtonID_None = 0, - ButtonID_Left, - ButtonID_Middle, - ButtonID_Right - }; - - // Callbacks types - typedef void ( *TMouseCommand )( - void*, const ButtonID&, int*, double*, bool, bool, bool - ); - typedef TMouseCommand TMouseClickCommand; - typedef TMouseCommand TMouseDoubleClickCommand; - - // Associate callbacks for each event - cpExtensions_BaseStyle_Commands( MouseClick ); - cpExtensions_BaseStyle_Commands( MouseDoubleClick ); - - public: - static void SetSetDoubleClickDelay( long delay ); - void DelegateTDxEvent( unsigned long event, void* calldata ); - - // Possible mouse motion events - virtual void OnMouseMove( ) cpExtensions_OVERRIDE; - virtual void OnMouseWheelForward( ) cpExtensions_OVERRIDE { } - virtual void OnMouseWheelBackward( ) cpExtensions_OVERRIDE { } - - // Possible mouse click-related events - inline ButtonID GetButtonID( ) const { return( this->m_ActiveButton ); } - - virtual void OnLeftButtonDown( ) cpExtensions_OVERRIDE; - virtual void OnLeftButtonUp( ) cpExtensions_OVERRIDE; - virtual void OnMiddleButtonDown( ) cpExtensions_OVERRIDE; - virtual void OnMiddleButtonUp( ) cpExtensions_OVERRIDE; - virtual void OnRightButtonDown( ) cpExtensions_OVERRIDE; - virtual void OnRightButtonUp( ) cpExtensions_OVERRIDE; - - virtual void OnLeftClick( ); - virtual void OnLeftDoubleClick( ); - virtual void OnMiddleClick( ); - virtual void OnMiddleDoubleClick( ); - virtual void OnRightClick( ); - virtual void OnRightDoubleClick( ); - - // Keyboard-related events - virtual void OnChar( ) cpExtensions_OVERRIDE { } - virtual void OnKeyDown( ) cpExtensions_OVERRIDE { } - virtual void OnKeyUp( ) cpExtensions_OVERRIDE { } - virtual void OnKeyPress( ) cpExtensions_OVERRIDE { } - virtual void OnKeyRelease( ) cpExtensions_OVERRIDE { } - - // Other events - virtual void OnExpose( ) cpExtensions_OVERRIDE { } - virtual void OnConfigure( ) cpExtensions_OVERRIDE { } - virtual void OnEnter( ) cpExtensions_OVERRIDE { } - virtual void OnLeave( ) cpExtensions_OVERRIDE { } - - virtual void Dolly( ) cpExtensions_OVERRIDE; - virtual void Pan( ) cpExtensions_OVERRIDE; - - protected: - BaseStyle( ); - virtual ~BaseStyle( ); - - virtual void _Dolly( double factor ); - - // Extension interface - virtual bool _PickPosition( int idx[ 2 ], double pos[ 3 ] ) = 0; - - // Main event callback - static void _ProcessEvents( - vtkObject* object, - unsigned long event, - void* clientdata, - void* calldata - ); - - private: - // Purposely not implemented - BaseStyle( const Self& ); - Self& operator=( const Self& ); - - protected: - double m_MotionFactor; - - /** - * Button events - */ - struct _TMouseButtonEvent - { - static long MaxDoubleClick; - long m_LastButtonUp; - long m_LastButtonHeld; - long m_LastButtonDown; - - inline _TMouseButtonEvent( ) - { this->Reset( ); } - inline void Reset( ) - { - this->m_LastButtonUp = 0; - this->m_LastButtonHeld = 0; - this->m_LastButtonDown = -1; - } - inline void Release( ) - { - /* TODO - long c = cpExtensions_CHRONO; - this->m_LastButtonUp = c; - this->m_LastButtonHeld = c - this->m_LastButtonDown; - this->m_LastButtonDown = -1; - */ - } - inline unsigned char Clicks( ) - { - /* TODO - unsigned char n = 0; - long c = cpExtensions_CHRONO; - if( - this->m_LastButtonHeld < MaxDoubleClick && - ( c - this->m_LastButtonUp ) < MaxDoubleClick - ) - { - this->Reset( ); - n = 2; - } - else - n = 1; - if( this->m_LastButtonDown < 0 ) - this->m_LastButtonDown = c; - return( n ); - */ - return( 1 ); - } - }; - _TMouseButtonEvent m_LeftButtonEvent; - _TMouseButtonEvent m_MiddleButtonEvent; - _TMouseButtonEvent m_RightButtonEvent; - ButtonID m_ActiveButton; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Interaction__BaseStyle__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/ImageSlicePointPlacer.cxx b/lib/cpExtensions/Interaction/ImageSlicePointPlacer.cxx deleted file mode 100644 index 45c020b..0000000 --- a/lib/cpExtensions/Interaction/ImageSlicePointPlacer.cxx +++ /dev/null @@ -1,275 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -vtkCxxSetObjectMacro( - cpExtensions::Interaction::ImageSlicePointPlacer, ImageSlice, vtkImageSlice - ); - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSlicePointPlacer:: -Self* cpExtensions::Interaction::ImageSlicePointPlacer:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -ComputeWorldPosition( - vtkRenderer* ren, - double displayPos[ 2 ], - double worldPos[ 3 ], - double worldOrient[ 9 ] - ) -{ - if( !this->UpdateInternalState( ) ) - return( 0 ); - return( - this->Placer->ComputeWorldPosition( - ren, displayPos, worldPos, worldOrient - ) - ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -ComputeWorldPosition( - vtkRenderer* ren, - double displayPos[ 2 ], - double refWorldPos[ 2 ], - double worldPos[ 3 ], - double worldOrient[ 9 ] - ) -{ - if( !this->UpdateInternalState( ) ) - return( 0 ); - return( - this->Placer->ComputeWorldPosition( - ren, displayPos, refWorldPos, worldPos, worldOrient - ) - ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -ValidateWorldPosition( double worldPos[ 3 ] ) -{ - if( !this->UpdateInternalState( ) ) - return( 0 ); - return( this->Placer->ValidateWorldPosition( worldPos ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -ValidateWorldPosition( double worldPos[ 3 ], double worldOrient[ 9 ] ) -{ - if( !this->UpdateInternalState( ) ) - return( 0 ); - return( this->Placer->ValidateWorldPosition( worldPos, worldOrient ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -UpdateWorldPosition( - vtkRenderer* ren, double worldPos[ 3 ], double worldOrient[ 9 ] - ) -{ - if( !this->UpdateInternalState( ) ) - return( 0 ); - return( this->Placer->UpdateWorldPosition( ren, worldPos, worldOrient ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSlicePointPlacer:: -UpdateInternalState( ) -{ - if( !this->ImageSlice ) - return( 0 ); - - vtkImageData* input = this->ImageSlice->GetMapper( )->GetInput( ); - if( !input ) - return( 0 ); - - double spacing[ 3 ]; - input->GetSpacing( spacing ); - - double origin[ 3 ]; - input->GetOrigin( origin ); - - double b[ 6 ]; - this->ImageSlice->GetBounds( b ); - if( this->Bounds[ 0 ] != VTK_DOUBLE_MAX) - { - b[ 0 ] = ( b[ 0 ] < this->Bounds[ 0 ] )? this->Bounds[ 0 ] : b[ 0 ]; - b[ 1 ] = ( b[ 1 ] > this->Bounds[ 1 ] )? this->Bounds[ 1 ] : b[ 1 ]; - b[ 2 ] = ( b[ 2 ] < this->Bounds[ 2 ] )? this->Bounds[ 2 ] : b[ 2 ]; - b[ 3 ] = ( b[ 3 ] > this->Bounds[ 3 ] )? this->Bounds[ 3 ] : b[ 3 ]; - b[ 4 ] = ( b[ 4 ] < this->Bounds[ 4 ] )? this->Bounds[ 4 ] : b[ 4 ]; - b[ 5 ] = ( b[ 5 ] > this->Bounds[ 5 ] )? this->Bounds[ 5 ] : b[ 5 ]; - - } // fi - - int displayExtent[ 6 ] = { 0, 1, 0, 1, 0, 1 }; - input->GetExtent( displayExtent ); - auto mapper = - dynamic_cast< cpExtensions::Visualization::ImageSliceMapper* >( - this->ImageSlice->GetMapper( ) - ); - if( mapper != NULL ) - { - auto ori = mapper->GetOrientation( ); - displayExtent[ ( ori << 1 ) + 1 ] = - displayExtent[ ori << 1 ] = - mapper->GetSliceNumber( ); - - } // fi - - int axis; - double position; - if( displayExtent[ 0 ] == displayExtent[ 1 ] ) - { - axis = vtkBoundedPlanePointPlacer::XAxis; - position = origin[ 0 ] + displayExtent[ 0 ] * spacing[ 0 ]; - } - else if( displayExtent[ 2 ] == displayExtent[ 3 ] ) - { - axis = vtkBoundedPlanePointPlacer::YAxis; - position = origin[ 1 ] + displayExtent[ 2 ] * spacing[ 1 ]; - } - else if( displayExtent[ 4 ] == displayExtent[ 5 ] ) - { - axis = vtkBoundedPlanePointPlacer::ZAxis; - position = origin[ 2 ] + displayExtent[ 4 ] * spacing[ 2 ]; - } - else - { - vtkErrorMacro( "Incorrect display extent in Image Slice" ); - return( 0 ); - - } // fi - - if( - axis != this->Placer->GetProjectionNormal( ) || - position != this->Placer->GetProjectionPosition( ) || - b[ 0 ] != this->SavedBounds[ 0 ] || - b[ 1 ] != this->SavedBounds[ 1 ] || - b[ 2 ] != this->SavedBounds[ 2 ] || - b[ 3 ] != this->SavedBounds[ 3 ] || - b[ 4 ] != this->SavedBounds[ 4 ] || - b[ 5 ] != this->SavedBounds[ 5 ] - ) - { - this->SavedBounds[ 0 ] = b[ 0 ]; - this->SavedBounds[ 1 ] = b[ 1 ]; - this->SavedBounds[ 2 ] = b[ 2 ]; - this->SavedBounds[ 3 ] = b[ 3 ]; - this->SavedBounds[ 4 ] = b[ 4 ]; - this->SavedBounds[ 5 ] = b[ 5 ]; - - this->Placer->SetProjectionNormal( axis ); - this->Placer->SetProjectionPosition( position ); - - this->Placer->RemoveAllBoundingPlanes( ); - - vtkPlane* plane; - if( axis != vtkBoundedPlanePointPlacer::XAxis ) - { - plane = vtkPlane::New( ); - plane->SetOrigin( b[ 0 ], b[ 2 ], b[ 4 ] ); - plane->SetNormal( 1.0, 0.0, 0.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - plane = vtkPlane::New(); - plane->SetOrigin( b[ 1 ], b[ 3 ], b[ 5 ] ); - plane->SetNormal( -1.0, 0.0, 0.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - } // fi - - if( axis != vtkBoundedPlanePointPlacer::YAxis ) - { - plane = vtkPlane::New( ); - plane->SetOrigin( b[ 0 ], b[ 2 ], b[ 4 ] ); - plane->SetNormal( 0.0, 1.0, 0.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - plane = vtkPlane::New( ); - plane->SetOrigin( b[ 1 ], b[ 3 ], b[ 5 ] ); - plane->SetNormal( 0.0, -1.0, 0.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - } // fi - - if( axis != vtkBoundedPlanePointPlacer::ZAxis ) - { - plane = vtkPlane::New( ); - plane->SetOrigin( b[ 0 ], b[ 2 ], b[ 4 ] ); - plane->SetNormal( 0.0, 0.0, 1.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - plane = vtkPlane::New( ); - plane->SetOrigin( b[ 1 ], b[ 3 ], b[ 5 ] ); - plane->SetNormal( 0.0, 0.0, -1.0 ); - this->Placer->AddBoundingPlane( plane ); - plane->Delete( ); - - } // fi - - this->Modified( ); - - } // fi - return( 1 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSlicePointPlacer:: -SetWorldTolerance( double tol ) -{ - double t = - ( tol < 0.0 )? 0.0: ( ( tol > VTK_DOUBLE_MAX )? VTK_DOUBLE_MAX: tol ); - if( this->WorldTolerance != t ) - { - this->WorldTolerance = t; - this->Placer->SetWorldTolerance( tol ); - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSlicePointPlacer:: -ImageSlicePointPlacer( ) - : Superclass( ) -{ - this->Placer = vtkBoundedPlanePointPlacer::New( ); - this->ImageSlice = NULL; - this->SavedBounds[ 0 ] = 0.0; - this->SavedBounds[ 1 ] = 0.0; - this->SavedBounds[ 2 ] = 0.0; - this->SavedBounds[ 3 ] = 0.0; - this->SavedBounds[ 4 ] = 0.0; - this->SavedBounds[ 5 ] = 0.0; - this->Bounds[ 0 ] = this->Bounds[ 2 ] = this->Bounds[ 4 ] = VTK_DOUBLE_MAX; - this->Bounds[ 1 ] = this->Bounds[ 3 ] = this->Bounds[ 5 ] = VTK_DOUBLE_MIN; -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSlicePointPlacer:: -~ImageSlicePointPlacer( ) -{ - this->Placer->Delete( ); - this->SetImageSlice( NULL ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/ImageSlicePointPlacer.h b/lib/cpExtensions/Interaction/ImageSlicePointPlacer.h deleted file mode 100644 index e0465d9..0000000 --- a/lib/cpExtensions/Interaction/ImageSlicePointPlacer.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef __cpExtensions__Interaction__ImageSlicePointPlacer__h__ -#define __cpExtensions__Interaction__ImageSlicePointPlacer__h__ - -#include -#include - -class vtkBoundedPlanePointPlacer; -class vtkImageSlice; -class vtkRenderer; - -namespace cpExtensions -{ - namespace Interaction - { - /** - */ - class cpExtensions_EXPORT ImageSlicePointPlacer - : public vtkPointPlacer - { - public: - typedef ImageSlicePointPlacer Self; - vtkTypeMacro( ImageSlicePointPlacer, vtkPointPlacer ); - - vtkGetObjectMacro( ImageSlice, vtkImageSlice ); - vtkSetVector6Macro( Bounds, double ); - vtkGetVector6Macro( Bounds, double ); - - public: - static Self* New( ); - - int ComputeWorldPosition( - vtkRenderer* ren, - double displayPos[ 2 ], - double worldPos[ 3 ], - double worldOrient[ 9 ] - ); - int ComputeWorldPosition( - vtkRenderer* ren, - double displayPos[ 2 ], - double refWorldPos[ 2 ], - double worldPos[ 3 ], - double worldOrient[ 9 ] - ); - int ValidateWorldPosition( double worldPos[ 3 ] ); - int ValidateWorldPosition( - double worldPos[ 3 ], double worldOrient[ 9 ] - ); - int UpdateWorldPosition( - vtkRenderer* ren, double worldPos[ 3 ], double worldOrient[ 9 ] - ); - int UpdateInternalState( ); - - void SetImageSlice( vtkImageSlice* slice ); - virtual void SetWorldTolerance( double tol ); - - protected: - ImageSlicePointPlacer( ); - virtual ~ImageSlicePointPlacer( ); - - private: - // Purposely not implemented - ImageSlicePointPlacer( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkImageSlice* ImageSlice; - vtkBoundedPlanePointPlacer* Placer; - double SavedBounds[ 6 ]; - double Bounds[ 6 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Interaction__ImageSlicePointPlacer__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/ImageSliceStyle.cxx b/lib/cpExtensions/Interaction/ImageSliceStyle.cxx deleted file mode 100644 index 7b9df5a..0000000 --- a/lib/cpExtensions/Interaction/ImageSliceStyle.cxx +++ /dev/null @@ -1,414 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSliceStyle:: -Self* cpExtensions::Interaction::ImageSliceStyle:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSliceStyle:: -GetSliceNumber( ) const -{ - if( this->m_WLActor.GetPointer( ) != NULL ) - return( this->m_WLActor->GetSliceNumber( ) ); - else - return( -1 ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Interaction::ImageSliceStyle:: -GetOrientation( ) const -{ - if( this->m_WLActor.GetPointer( ) != NULL ) - return( this->m_WLActor->GetOrientation( ) ); - else - return( -1 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseMove( ) -{ - static bool cursor_visible = false; - - int idx[ 2 ]; - double pnt[ 3 ]; - if( this->_PickPointOnImageActor( idx, pnt ) ) - { - this->m_Cursor->SetCursor( pnt, false ); - this->_ShowText( pnt ); - if( !cursor_visible ) - { - this->m_Cursor->VisibilityOn( ); - this->m_Text->VisibilityOn( ); - cursor_visible = true; - - } // fi - this->Interactor->Render( ); - } - else - { - if( cursor_visible ) - { - this->m_Cursor->VisibilityOff( ); - this->m_Text->VisibilityOff( ); - cursor_visible = false; - this->Interactor->Render( ); - - } // fi - - } // fi - - this->Overclass::OnMouseMove( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseWheelForward( ) -{ - static int s = 0; - if( this->m_WLActor.GetPointer( ) == NULL ) - return; - s = this->m_WLActor->GetSliceNumber( ); - s += ( this->Interactor->GetShiftKey( ) == 1 )? 10: 1; - this->m_WLActor->SetSliceNumber( s ); - s = this->m_WLActor->GetSliceNumber( ); - if( this->m_LUTActor.GetPointer( ) != NULL ) - this->m_LUTActor->SetSliceNumber( s ); - this->InvokeEvent( vtkCommand::UserEvent + 2, &s ); - this->Interactor->Render( ); - this->OnMouseMove( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseWheelBackward( ) -{ - static int s = 0; - if( this->m_WLActor.GetPointer( ) == NULL ) - return; - s = this->m_WLActor->GetSliceNumber( ); - s -= ( this->Interactor->GetShiftKey( ) == 1 )? 10: 1; - this->m_WLActor->SetSliceNumber( s ); - s = this->m_WLActor->GetSliceNumber( ); - if( this->m_LUTActor.GetPointer( ) != NULL ) - this->m_LUTActor->SetSliceNumber( s ); - this->InvokeEvent( vtkCommand::UserEvent + 2, &s ); - this->Interactor->Render( ); - this->OnMouseMove( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnChar( ) -{ - switch( this->Interactor->GetKeyCode( ) ) - { - case 'r': case 'R': - { - this->FindPokedRenderer( - this->Interactor->GetEventPosition( )[ 0 ], - this->Interactor->GetEventPosition( )[ 1 ] - ); - this->CurrentRenderer->ResetCamera( ); - this->Interactor->Render( ); - } - break; - default: - break; - - } // hctiws -} - -/* TODO -cpExtensions::Visualization::ImageViewerActors* -cpExtensions::Interaction::ImageSliceStyle:: -GetActors( ) -{ - return( this->m_Actors ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization::ImageViewerActors* -cpExtensions::Interaction::ImageSliceStyle:: -GetActors( ) const -{ - return( this->m_Actors ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -SetActors( cpExtensions::Visualization::ImageViewerActors* actors ) -{ - this->m_Actors = actors; - if( actors != NULL ) - { - this->m_PropPicker = vtkSmartPointer< vtkPropPicker >::New( ); - this->m_PropPicker->PickFromListOn( ); - this->m_PropPicker->GetPickList( )->RemoveAllItems( ); - this->m_PropPicker-> - AddPickList( this->m_Actors->GetWindowLevelImageActor( ) ); - } - else - this->m_PropPicker = NULL; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseMove( ) -{ - this->Superclass::OnMouseMove( ); - if( this->m_Actors.GetPointer( ) == NULL ) - return; - - // Slice synch - static int idx[ 2 ]; - static double pos[ 3 ]; - if( this->_PickPosition( idx, pos ) ) - { - if( - this->Interactor->GetControlKey( ) == 1 && - this->GetButtonID( ) == Self::ButtonID_Left - ) - { - this->m_Actors->SetSuperCursor( pos, this->m_Actors->GetOrientation( ) == 2 ); - this->InvokeEvent( vtkCommand::UserEvent + 1, pos ); - } - else - this->m_Actors->SetCursor( pos, this->m_Actors->GetOrientation( ) == 2 ); - } - else - this->m_Actors->HideViewerActors( ); - this->Interactor->Render( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseWheelForward( ) -{ - static int s = 0; - if( this->m_Actors.GetPointer( ) == NULL ) - return; - s = this->m_Actors->GetSliceNumber( ); - s += ( this->Interactor->GetShiftKey( ) == 1 )? 10: 1; - this->m_Actors->SetSliceNumber( s ); - s = this->m_Actors->GetSliceNumber( ); - this->InvokeEvent( vtkCommand::UserEvent + 2, &s ); - this->Interactor->Render( ); - this->OnMouseMove( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnMouseWheelBackward( ) -{ - static int s = 0; - if( this->m_Actors.GetPointer( ) == NULL ) - return; - s = this->m_Actors->GetSliceNumber( ); - s -= ( this->Interactor->GetShiftKey( ) == 1 )? 10: 1; - this->m_Actors->SetSliceNumber( s ); - s = this->m_Actors->GetSliceNumber( ); - this->InvokeEvent( vtkCommand::UserEvent + 2, &s ); - this->Interactor->Render( ); - this->OnMouseMove( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -OnChar( ) -{ -} -*/ - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSliceStyle:: -ImageSliceStyle( ) - : Superclass( ) -{ - this->SetInteractionModeToImage2D( ); - this->m_PropPicker = vtkSmartPointer< vtkPropPicker >::New( ); - this->m_PropPicker->PickFromListOn( ); - - this->m_Cursor = vtkSmartPointer< TCursor >::New( ); - this->m_Cursor->VisibilityOff( ); - this->m_Cursor->GetProperty( 0 )->SetColor( 1, 1, 0 ); - this->m_Cursor->GetProperty( 1 )->SetColor( 1, 1, 0 ); - - // Prepare text - this->m_TextBuffer[ 0 ] = '\0'; - this->m_Text = vtkSmartPointer< vtkTextActor >::New( ); - this->m_Text->SetTextScaleModeToNone( ); - auto textprop = this->m_Text->GetTextProperty( ); - textprop->SetColor( 1, 1, 0 ); - textprop->SetFontFamilyToCourier( ); - textprop->SetFontSize( 12 ); - textprop->BoldOff( ); - textprop->ItalicOff( ); - textprop->ShadowOff( ); - textprop->SetJustificationToLeft( ); - textprop->SetVerticalJustificationToBottom( ); - auto coord = this->m_Text->GetPositionCoordinate( ); - coord->SetCoordinateSystemToNormalizedViewport( ); - coord->SetValue( 0.01, 0.02 ); - this->m_Text->VisibilityOff( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::ImageSliceStyle:: -~ImageSliceStyle( ) -{ -} - -// ------------------------------------------------------------------------- -bool cpExtensions::Interaction::ImageSliceStyle:: -_PickPointOnImageActor( int idx[ 2 ], double pnt[ 3 ] ) -{ - // Check if data is valid - if( - this->Interactor == NULL || - this->CurrentRenderer == NULL || - this->m_PropPicker.GetPointer( ) == NULL - ) - return( false ); - - // Find the renderer where the event has been raised - idx[ 0 ] = this->Interactor->GetEventPosition( )[ 0 ]; - idx[ 1 ] = this->Interactor->GetEventPosition( )[ 1 ]; - this->FindPokedRenderer( double( idx[ 0 ] ), double( idx[ 1 ] ) ); - - // Check if the image has changed - this->Interactor->GetPicker( )-> - Pick( idx[ 0 ], idx[ 1 ], 0.0, this->CurrentRenderer ); - auto picker = - vtkAbstractPropPicker::SafeDownCast( this->Interactor->GetPicker( ) ); - if( picker == NULL ) - return( false ); - TWLActor* curr_actor = dynamic_cast< TWLActor* >( picker->GetProp3D( ) ); - if( curr_actor != this->m_WLActor.GetPointer( ) && curr_actor != NULL ) - { - this->m_WLActor = curr_actor; - this->m_PropPicker->GetPickList( )->RemoveAllItems( ); - this->m_PropPicker->AddPickList( curr_actor ); - - auto props = this->CurrentRenderer->GetViewProps( ); - this->m_LUTActor = NULL; - props->InitTraversal( ); - vtkProp* prop; - while( ( ( prop = props->GetNextProp( ) ) != NULL ) && ( this->m_LUTActor.GetPointer( ) == NULL ) ) - this->m_LUTActor = dynamic_cast< TLUTActor* >( prop ); - - this->m_Cursor->SetImageBounds( curr_actor->GetImage( )->GetBounds( ) ); - this->m_Cursor->SetImageOrientation( curr_actor->GetOrientation( ) ); - this->m_Cursor->InitTraversal( ); - while( vtkProp* prop = this->m_Cursor->GetNextProp( ) ) - this->CurrentRenderer->AddViewProp( prop ); - this->CurrentRenderer->AddViewProp( this->m_Text ); - - } // fi - if( this->m_WLActor.GetPointer( ) == NULL ) - { - this->m_PropPicker->GetPickList( )->RemoveAllItems( ); - return( false ); - - } // fi - - // Pick a 3D position - int r = this->m_PropPicker->Pick( - double( idx[ 0 ] ), double( idx[ 1 ] ), double( 0 ), - this->CurrentRenderer - ); - if( r == 0 ) - return( false ); - this->m_PropPicker->GetPickPosition( pnt ); - return( true ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -_CorrectPosition( double pos[ 3 ], int ijk[ 3 ] ) -{ - if( this->m_WLActor.GetPointer( ) == NULL ) - return; - auto image = this->m_WLActor->GetImage( ); - if( image == NULL ) - return; - - // Approximate image index - double pcoords[ 3 ]; - image->ComputeStructuredCoordinates( pos, ijk, pcoords ); - - // Manually correct index - int ext[ 6 ]; - image->GetExtent( ext ); - for( int i = 0; i < 3; ++i ) - { - if( ijk[ i ] < ext[ i << 1 ] ) - ijk[ i ] = ext[ i << 1 ]; - if( ext[ ( i << 1 ) + 1 ] < ijk[ i ] ) - ijk[ i ] = ext[ ( i << 1 ) + 1 ]; - - } // rof - - // Get real coordinates - int o = this->m_WLActor->GetOrientation( ); - ijk[ o ] = this->m_WLActor->GetSliceNumber( ); - image->GetPoint( image->ComputePointId( ijk ), pos ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::ImageSliceStyle:: -_ShowText( double pos[ 3 ] ) -{ - if( this->m_WLActor.GetPointer( ) == NULL ) - return; - auto image = this->m_WLActor->GetImage( ); - if( image == NULL ) - return; - - int ijk[ 3 ]; - this->_CorrectPosition( pos, ijk ); - int o = this->m_WLActor->GetOrientation( ); - - std::stringstream buffer; - buffer << "Axis: " << char( 'X' + char( o ) ) << std::endl; - int nScl = image->GetNumberOfScalarComponents( ); - buffer - << "Pixel: [" << ijk[ 0 ] - << "," << ijk[ 1 ] - << "," << ijk[ 2 ] << "] = < " - << image->GetScalarComponentAsFloat( ijk[ 0 ], ijk[ 1 ], ijk[ 2 ], 0 ); - for( int n = 1; n < nScl; ++n ) - buffer - << " : " - << image->GetScalarComponentAsFloat( ijk[ 0 ], ijk[ 1 ], ijk[ 2 ], n ); - buffer << " >" << std::endl; - buffer - << "Point: (" - << pos[ 0 ] << ", " << pos[ 1 ] << ", " << pos[ 2 ] - << ")"; - cpExtensions_SPRINTF( this->m_TextBuffer, 1024, buffer.str( ).c_str( ) ); - this->m_Text->SetInput( this->m_TextBuffer ); - this->m_Text->VisibilityOn( ); - this->m_Text->Modified( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/ImageSliceStyle.h b/lib/cpExtensions/Interaction/ImageSliceStyle.h deleted file mode 100644 index 6d2b114..0000000 --- a/lib/cpExtensions/Interaction/ImageSliceStyle.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef __cpExtensions__Interaction__ImageSliceStyle__h__ -#define __cpExtensions__Interaction__ImageSliceStyle__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkPropPicker; -class vtkTextActor; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class CursorActors; - class LUTImageActor; - class WindowLevelImageActor; - } - namespace Interaction - { - /** - */ - class cpExtensions_EXPORT ImageSliceStyle - : public vtkInteractorStyleImage - { - public: - typedef ImageSliceStyle Self; - typedef cpExtensions::Visualization::CursorActors TCursor; - typedef cpExtensions::Visualization::LUTImageActor TLUTActor; - typedef cpExtensions::Visualization::WindowLevelImageActor TWLActor; - - public: - vtkTypeMacro( ImageSliceStyle, vtkInteractorStyleImage ); - typedef vtkInteractorStyleImage::Superclass Overclass; - - public: - static Self* New( ); - - int GetSliceNumber( ) const; - int GetOrientation( ) const; - - virtual void OnMouseMove( ) cpExtensions_OVERRIDE; - virtual void OnMouseWheelForward( ) cpExtensions_OVERRIDE; - virtual void OnMouseWheelBackward( ) cpExtensions_OVERRIDE; - virtual void OnChar( ) cpExtensions_OVERRIDE; - - - /* TODO - cpExtensions::Visualization::ImageViewerActors* GetActors( ); - const cpExtensions::Visualization::ImageViewerActors* GetActors( ) const; - void SetActors( cpExtensions::Visualization::ImageViewerActors* actors ); - - // Events - virtual void OnMouseMove( ) cpExtensions_OVERRIDE; - virtual void OnChar( ) cpExtensions_OVERRIDE; - */ - - protected: - ImageSliceStyle( ); - virtual ~ImageSliceStyle( ); - - bool _PickPointOnImageActor( int idx[ 2 ], double pnt[ 3 ] ); - void _CorrectPosition( double pos[ 3 ], int ijk[ 3 ] ); - void _ShowText( double pos[ 3 ] ); - - private: - // Purposely not implemented - ImageSliceStyle( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< vtkPropPicker > m_PropPicker; - vtkSmartPointer< TLUTActor > m_LUTActor; - vtkSmartPointer< TWLActor > m_WLActor; - vtkSmartPointer< TCursor > m_Cursor; - vtkSmartPointer< vtkTextActor > m_Text; - char m_TextBuffer[ 1024 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Interaction__ImageSliceStyle__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/SeedWidget.cxx b/lib/cpExtensions/Interaction/SeedWidget.cxx deleted file mode 100644 index 509d7c2..0000000 --- a/lib/cpExtensions/Interaction/SeedWidget.cxx +++ /dev/null @@ -1,165 +0,0 @@ -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::SeedWidget:: -Self* cpExtensions::Interaction::SeedWidget:: -New( ) -{ - return( new Self ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -SetInteractor( vtkRenderWindowInteractor* rwi ) -{ - this->Superclass::SetInteractor( rwi ); - /* TODO - if( rwi != NULL ) - { - TBaseStyle* s = - dynamic_cast< TBaseStyle* >( rwi->GetInteractorStyle( ) ); - if( s != NULL ) - { - s->AddMouseClickCommand( Self::_Click, this ); - s->AddMouseDoubleClickCommand( Self::_DoubleClick, this ); - - } // fi - - } // fi - */ -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::SeedWidget:: -SeedWidget( ) - : Superclass( ) -{ - // These are the event callbacks supported by this widget - this->CallbackMapper->SetCallbackMethod( - vtkCommand::LeftButtonPressEvent, - vtkWidgetEvent::AddPoint, - this, Self::_AddPointAction - ); - this->CallbackMapper->SetCallbackMethod( - vtkCommand::RightButtonPressEvent, - vtkWidgetEvent::Completed, - this, Self::_CompletedAction - ); - this->CallbackMapper->SetCallbackMethod( - vtkCommand::MouseMoveEvent, - vtkWidgetEvent::Move, - this, Self::_MoveAction - ); - this->CallbackMapper->SetCallbackMethod( - vtkCommand::LeftButtonReleaseEvent, - vtkWidgetEvent::EndSelect, - this, Self::_EndSelectAction - ); - this->CallbackMapper->SetCallbackMethod( - vtkCommand::KeyPressEvent, - vtkEvent::NoModifier, 127, 1, "Delete", - vtkWidgetEvent::Delete, - this, Self::_DeleteAction - ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Interaction::SeedWidget:: -~SeedWidget( ) -{ -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -_AddPointAction( vtkAbstractWidget* wdg ) -{ - Self* self = dynamic_cast< Self* >( wdg ); - if( self == NULL ) - return; - auto iren = self->GetInteractor( ); - if( iren == NULL ) - return; - int shift = iren->GetShiftKey( ); - if( shift == 1 ) - Self::AddPointAction( wdg ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -_CompletedAction( vtkAbstractWidget* wdg ) -{ - // Do nothing - Self::CompletedAction( wdg ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -_MoveAction( vtkAbstractWidget* wdg ) -{ - // Do nothing - Self::MoveAction( wdg ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -_EndSelectAction( vtkAbstractWidget* wdg ) -{ - // Do nothing - Self::EndSelectAction( wdg ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Interaction::SeedWidget:: -_DeleteAction( vtkAbstractWidget* wdg ) -{ - // Do nothing - Self::DeleteAction( wdg ); -} - -// ------------------------------------------------------------------------- -/* TODO - void cpExtensions::Interaction::SeedWidget:: - _Click( - void* data, const TBaseStyle::ButtonID& button, - int* idx, double* pos, bool alt, bool ctr, bool sft - ) - { - SeedWidget* self = reinterpret_cast< SeedWidget* >( data ); - if( self == NULL ) - return; - if( self->WidgetState == vtkSeedWidget::MovingSeed ) - return; - - int st = self->WidgetRep->ComputeInteractionState( idx[ 0 ], idx[ 1 ] ); - if( st == vtkSeedRepresentation::NearSeed ) - { - self->WidgetState = vtkSeedWidget::MovingSeed; - - // Invoke an event on ourself for the handles - self->InvokeEvent( vtkCommand::LeftButtonPressEvent, NULL ); - self->Superclass::StartInteraction( ); - self->InvokeEvent( vtkCommand::StartInteractionEvent, NULL ); - self->EventCallbackCommand->SetAbortFlag( 1 ); - self->Render( ); - - } // fi - } - - // ------------------------------------------------------------------------- - void cpExtensions::Interaction::SeedWidget:: - _DoubleClick( - void* data, const TBaseStyle::ButtonID& button, - int* idx, double* pos, bool alt, bool ctr, bool sft - ) - { - Self::AddPointAction( reinterpret_cast< vtkAbstractWidget* >( data ) ); - } -*/ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Interaction/SeedWidget.h b/lib/cpExtensions/Interaction/SeedWidget.h deleted file mode 100644 index 858218b..0000000 --- a/lib/cpExtensions/Interaction/SeedWidget.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef __cpExtensions__Interaction__SeedWidget__h__ -#define __cpExtensions__Interaction__SeedWidget__h__ - -#include -#include -#include - -namespace cpExtensions -{ - namespace Interaction - { - /** - */ - class cpExtensions_EXPORT SeedWidget - : public vtkSeedWidget - { - public: - typedef SeedWidget Self; - vtkTypeMacro( SeedWidget, vtkSeedWidget ); - - typedef cpExtensions::Interaction::BaseStyle TBaseStyle; - - public: - static Self* New( ); - - virtual void SetInteractor( - vtkRenderWindowInteractor* rwi - ) cpExtensions_OVERRIDE; - - protected: - SeedWidget( ); - virtual ~SeedWidget( ); - - static void _AddPointAction( vtkAbstractWidget* wdg ); - static void _CompletedAction( vtkAbstractWidget* wdg ); - static void _MoveAction( vtkAbstractWidget* wdg ); - static void _EndSelectAction( vtkAbstractWidget* wdg ); - static void _DeleteAction( vtkAbstractWidget* wdg ); - - /* TODO - static void _Click( - void* data, const TBaseStyle::ButtonID& button, - int* idx, double* pos, bool alt, bool ctr, bool sft - ); - static void _DoubleClick( - void* data, const TBaseStyle::ButtonID& button, - int* idx, double* pos, bool alt, bool ctr, bool sft - ); - */ - - private: - // Purposely not implemented - SeedWidget( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Interaction__SeedWidget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/ActorsWidgetInterface.h b/lib/cpExtensions/QT/ActorsWidgetInterface.h deleted file mode 100644 index 6af66ea..0000000 --- a/lib/cpExtensions/QT/ActorsWidgetInterface.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef __cpExtensions__QT__ActorsWidgetInterface__h__ -#define __cpExtensions__QT__ActorsWidgetInterface__h__ - -#include - -#include -#include - -class vtkRenderWindowInteractor; - -namespace cpExtensions -{ - namespace QT - { - /** - */ - class cpExtensions_EXPORT ActorsWidgetInterface - { - public: - typedef ActorsWidgetInterface Self; - - public: - ActorsWidgetInterface( ) { } - virtual ~ActorsWidgetInterface( ) { } - - virtual std::set< vtkRenderWindowInteractor* > GetInteractors( ) const = 0; - - virtual std::set< std::string > GetActorsNames( ) const = 0; - virtual bool IsWindowLevelImageActor( const std::string& name ) const = 0; - virtual bool IsLUTImageActor( const std::string& name ) const = 0; - virtual bool Is3DActor( const std::string& name ) const = 0; - - virtual void GetScalarRange( const std::string& name, double r[ 2 ] ) const = 0; - virtual void GetWindowLevel( const std::string& name, double wl[ 2 ] ) const = 0; - virtual double GetWindow( const std::string& name ) const = 0; - virtual double GetLevel( const std::string& name ) const = 0; - virtual char GetImageInterpolation( const std::string& name ) const = 0; - - virtual void GetColor( const std::string& name, double& r, double& g, double& b ) const = 0; - virtual double GetOpacity( const std::string& name ) const = 0; - virtual double GetPointSize( const std::string& name ) const = 0; - virtual double GetLineWidth( const std::string& name ) const = 0; - virtual int GetRepresentation( const std::string& name ) const = 0; - - virtual void SetScalarRange( const std::string& name, double r[ 2 ] ) = 0; - virtual void SetScalarRange( const std::string& name, double min, double max ) = 0; - virtual void SetWindowLevel( const std::string& name, double wl[ 2 ] ) = 0; - virtual void SetWindowLevel( const std::string& name, double w, double l ) = 0; - virtual void SetWindow( const std::string& name, double w ) = 0; - virtual void SetLevel( const std::string& name, double l ) = 0; - virtual void SetImageInterpolation( const std::string& name, char i ) = 0; - - virtual void SetColor( const std::string& name, double r, double g, double b ) = 0; - virtual void SetOpacity( const std::string& name, double o ) = 0; - virtual void SetPointSize( const std::string& name, double s ) = 0; - virtual void SetLineWidth( const std::string& name, double w ) = 0; - virtual void SetRepresentationToPoints( const std::string& name ) = 0; - virtual void SetRepresentationToSurface( const std::string& name ) = 0; - virtual void SetRepresentationToWireframe( const std::string& name ) = 0; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__ActorsWidgetInterface__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/ConfigurationChooser.cxx b/lib/cpExtensions/QT/ConfigurationChooser.cxx deleted file mode 100644 index 00c121b..0000000 --- a/lib/cpExtensions/QT/ConfigurationChooser.cxx +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::ConfigurationChooser:: -ConfigurationChooser( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - m_UI( new Ui::ConfigurationChooser ), - m_Data( NULL ) -{ - this->m_UI->setupUi( this ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::ConfigurationChooser:: -~ConfigurationChooser( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ConfigurationChooser:: -setData( ActorsWidgetInterface* data ) -{ - this->m_Data = data; - if( this->m_Data != NULL ) - { - auto actors = this->m_Data->GetActorsNames( ); - for( auto n = actors.begin( ); n != actors.end( ); ++n ) - { - if( this->m_Data->IsWindowLevelImageActor( *n ) ) - { - auto wl_wdg = new WindowLevelImageConfiguration( this ); - wl_wdg->setData( data, *n ); - this->m_UI->Configurations->addTab( wl_wdg, n->c_str( ) ); - } - else if( this->m_Data->IsLUTImageActor( *n ) ) - { - } - else if( this->m_Data->Is3DActor( *n ) ) - { - } // fi - - } // rof - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/ConfigurationChooser.h b/lib/cpExtensions/QT/ConfigurationChooser.h deleted file mode 100644 index dc908ff..0000000 --- a/lib/cpExtensions/QT/ConfigurationChooser.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef __cpExtensions__QT__ConfigurationChooser__h__ -#define __cpExtensions__QT__ConfigurationChooser__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace Ui { class ConfigurationChooser; } - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace QT - { - class ActorsWidgetInterface; - - /** - */ - class cpExtensions_EXPORT ConfigurationChooser - : public QDialog - { - Q_OBJECT; - - public: - typedef ConfigurationChooser Self; - typedef QDialog Superclass; - - public: - explicit ConfigurationChooser( QWidget* parent = NULL, Qt::WindowFlags f = 0 ); - virtual ~ConfigurationChooser( ); - - void setData( ActorsWidgetInterface* data ); - - protected: - Ui::ConfigurationChooser* m_UI; - ActorsWidgetInterface* m_Data; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__ConfigurationChooser__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/ConfigurationChooser.ui b/lib/cpExtensions/QT/ConfigurationChooser.ui deleted file mode 100644 index 4c33dfa..0000000 --- a/lib/cpExtensions/QT/ConfigurationChooser.ui +++ /dev/null @@ -1,51 +0,0 @@ - - - ConfigurationChooser - - - - 0 - 0 - 475 - 317 - - - - Dialog - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Ok - - - - - - - - - Buttons - accepted() - ConfigurationChooser - accept() - - - 248 - 254 - - - 157 - 274 - - - - - diff --git a/lib/cpExtensions/QT/ImageWidget.cxx b/lib/cpExtensions/QT/ImageWidget.cxx deleted file mode 100644 index bac5f17..0000000 --- a/lib/cpExtensions/QT/ImageWidget.cxx +++ /dev/null @@ -1,225 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::ImageWidget:: -ImageWidget( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - m_ImageName( "" ), - m_OutlineActor( NULL ) -{ - this->m_Style = vtkSmartPointer< TStyle >::New( ); - this->m_Style->SetCurrentRenderer( this->m_Renderer ); - this->SetStyle( this->m_Style ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::ImageWidget:: -~ImageWidget( ) -{ - this->Clear( ); - if( this->m_OutlineActor != NULL ) - delete this->m_OutlineActor; - for( auto a = this->m_Actors.begin( ); a != this->m_Actors.end( ); ++a ) - delete *a; - this->m_Actors.clear( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -Clear( ) -{ - this->RemoveViewProps( ); - this->m_ImageName = ""; -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -SetImage( vtkImageData* image, const std::string& name, int orientation ) -{ - if( name == "" ) - return; - if( this->m_ImageName != "" ) - this->Clear( ); - this->m_ImageName = name; - - this->m_WLActor = vtkSmartPointer< TWLActor >::New( ); - this->m_WLActor->SetImage( image ); - this->m_WLActor->SetOrientation( orientation ); - - this->m_LUTActor = vtkSmartPointer< TLUTActor >::New( ); - this->m_LUTActor->SetOrientation( orientation ); - - this->m_Outline = vtkSmartPointer< TOutline >::New( ); - this->m_Outline->SetBounds( image->GetBounds( ) ); - this->m_Outline->Update( ); - - if( this->m_OutlineActor != NULL ) - delete this->m_OutlineActor; - this->m_OutlineActor = new TActor( ); - this->m_OutlineActor->SetMesh( this->m_Outline->GetOutput( ) ); - - double cr = double( 0 ); - double cg = double( 0 ); - double cb = double( 0 ); - switch( this->m_WLActor->GetOrientation( ) ) - { - case 0: cr = double( 1 ); break; - case 1: cg = double( 1 ); break; - case 2: cb = double( 1 ); break; - default: cr = double( 1 ); break; - } // hctiws - this->m_OutlineActor->GetActor( )->GetProperty( )->SetColor( cr, cg, cb ); - - this->AddViewProp( this->m_WLActor, this->m_ImageName ); - this->AddAuxViewProp( this->m_OutlineActor->GetActor( ), this->m_ImageName ); - this->ResetCamera( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -Add( vtkDataSet* data, const std::string& name ) -{ - auto image = dynamic_cast< vtkImageData* >( data ); - auto pdata = dynamic_cast< vtkPolyData* >( data ); - if( image != NULL ) - { - this->m_LUTActor->AddImage( image ); - this->m_LUTActor->GetProperty( )->SetOpacity( 0.5 ); - this->AddViewProp( this->m_LUTActor, "__LUT_IMAGE__" ); - this->Render( ); - } - else if( pdata != NULL ) - { - TActor* actor = new TActor( ); - actor->SetMesh( pdata ); - this->m_Actors.push_back( actor ); - this->AddViewProp( actor->GetActor( ), name ); - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -ResetCamera( ) -{ - if( this->m_WLActor.GetPointer( ) != NULL ) - { - auto image = this->m_WLActor->GetImage( ); - if( image != NULL ) - { - double bounds[ 6 ]; - image->GetBounds( bounds ); - - // Compute camera properties - double center[ 3 ]; - center[ 0 ] = ( bounds[ 1 ] + bounds[ 0 ] ) / double( 2 ); - center[ 1 ] = ( bounds[ 3 ] + bounds[ 2 ] ) / double( 2 ); - center[ 2 ] = ( bounds[ 5 ] + bounds[ 4 ] ) / double( 2 ); - - int ori = this->m_WLActor->GetOrientation( ); - double pos[ 3 ] = { double( 0 ) }; - pos[ ori ] = double( 1 ); - pos[ 0 ] += center[ 0 ]; - pos[ 1 ] += center[ 1 ]; - pos[ 2 ] += center[ 2 ]; - - double up[ 3 ] = { double( 0 ) }; - if( ori == 0 ) - { - if ( this->m_Quadrant == 0 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 1 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 2 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 3 ) up[ 2 ] = double( 1 ); - } - else if( ori == 1 ) - { - if ( this->m_Quadrant == 0 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 1 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 2 ) up[ 2 ] = double( 1 ); - else if( this->m_Quadrant == 3 ) up[ 2 ] = double( 1 ); - } - else if( ori == 2 ) - { - if ( this->m_Quadrant == 0 ) up[ 1 ] = double( -1 ); - else if( this->m_Quadrant == 1 ) up[ 1 ] = double( -1 ); - else if( this->m_Quadrant == 2 ) up[ 1 ] = double( -1 ); - else if( this->m_Quadrant == 3 ) up[ 1 ] = double( -1 ); - pos[ 2 ] *= double( -1 ); - - } // fi - - // Reconfigure camera and return - auto camera = this->m_Renderer->GetActiveCamera( ); - camera->ParallelProjectionOn( ); - camera->SetFocalPoint( center ); - camera->SetPosition( pos ); - camera->SetViewUp( up ); - this->m_Renderer->ResetCamera( bounds ); - } - else - this->Superclass::ResetCamera( ); - } - else - this->Superclass::ResetCamera( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::ImageWidget:: -TWLActor* cpExtensions::QT::ImageWidget:: -GetImageActor( ) -{ - return( this->m_WLActor ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::QT::ImageWidget:: -TWLActor* cpExtensions::QT::ImageWidget:: -GetImageActor( ) const -{ - return( this->m_WLActor ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -SetColor( const std::string& name, double r, double g, double b ) -{ - auto props = this->GetViewProps( name ); - for( auto p = props.begin( ); p != props.end( ); ++p ) - { - auto actor = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( actor != NULL ) - actor->GetProperty( )->SetColor( r, g, b ); - - } // rof - this->Render( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::ImageWidget:: -SetLineWidth( const std::string& name, double w ) -{ - auto props = this->GetViewProps( name ); - for( auto p = props.begin( ); p != props.end( ); ++p ) - { - auto actor = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( actor != NULL ) - actor->GetProperty( )->SetLineWidth( w ); - - } // rof - this->Render( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/ImageWidget.h b/lib/cpExtensions/QT/ImageWidget.h deleted file mode 100644 index 18073d6..0000000 --- a/lib/cpExtensions/QT/ImageWidget.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef __cpExtensions__QT__ImageWidget__h__ -#define __cpExtensions__QT__ImageWidget__h__ - -#include - -// ------------------------------------------------------------------------- -class vtkDataSet; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class OutlineSource; - class LUTImageActor; - class WindowLevelImageActor; - class MeshActor; - } - namespace Interaction { class ImageSliceStyle; } - - namespace QT - { - /** - */ - class cpExtensions_EXPORT ImageWidget - : public RendererWidget - { - Q_OBJECT; - - public: - typedef ImageWidget Self; - typedef RendererWidget Superclass; - - typedef cpExtensions::Visualization::OutlineSource TOutline; - typedef cpExtensions::Visualization::MeshActor TActor; - typedef cpExtensions::Visualization::LUTImageActor TLUTActor; - typedef cpExtensions::Visualization::WindowLevelImageActor TWLActor; - typedef cpExtensions::Interaction::ImageSliceStyle TStyle; - - public: - explicit ImageWidget( QWidget* parent = NULL, Qt::WindowFlags f = 0 ); - virtual ~ImageWidget( ); - - void Clear( ); - void SetImage( - vtkImageData* image, const std::string& name, int orientation = 2 - ); - void Add( vtkDataSet* data, const std::string& name ); - virtual void ResetCamera( ) cpExtensions_OVERRIDE; - - TWLActor* GetImageActor( ); - const TWLActor* GetImageActor( ) const; - - void SetColor( const std::string& name, double r, double g, double b ) override; - void SetLineWidth( const std::string& name, double w ) override; - - protected: - std::string m_ImageName; - - vtkSmartPointer< TWLActor > m_WLActor; - vtkSmartPointer< TLUTActor > m_LUTActor; - vtkSmartPointer< TOutline > m_Outline; - TActor* m_OutlineActor; - std::vector< TActor* > m_Actors; - - vtkSmartPointer< TStyle > m_Style; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__ImageWidget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/MPR3DWidget.cxx b/lib/cpExtensions/QT/MPR3DWidget.cxx deleted file mode 100644 index f86992d..0000000 --- a/lib/cpExtensions/QT/MPR3DWidget.cxx +++ /dev/null @@ -1,140 +0,0 @@ -#include -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPR3DWidget:: -MPR3DWidget( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - m_ImageName( "" ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPR3DWidget:: -~MPR3DWidget( ) -{ - for( auto a = this->m_Actors.begin( ); a != this->m_Actors.end( ); ++a ) - delete *a; - this->m_Actors.clear( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPR3DWidget:: -Clear( ) -{ - this->RemoveViewProps( ); - this->m_ImageName = ""; -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPR3DWidget:: -SetImage( vtkImageData* image, const std::string& name ) -{ - if( name == "" ) - return; - if( this->m_ImageName != "" ) - this->Clear( ); - this->m_ImageName = name; - - for( unsigned int o = 0; o < 3; ++o ) - { - this->m_WLActors[ o ] = vtkSmartPointer< TWLActor >::New( ); - this->m_WLActors[ o ]->SetImage( image ); - this->m_WLActors[ o ]->SetOrientation( o ); - - this->m_OLActors[ o ] = vtkSmartPointer< TOLActor >::New( ); - this->m_OLActors[ o ]->SetBounds( - o, image->GetBounds( )[ o << 1 ], image->GetBounds( ) - ); - - this->AddViewProp( this->m_WLActors[ o ], this->m_ImageName ); - this->AddAuxViewProp( this->m_OLActors[ o ], this->m_ImageName ); - this->ResetCamera( ); - - } // rof -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPR3DWidget:: -Add( vtkDataSet* data, const std::string& name ) -{ - auto image = dynamic_cast< vtkImageData* >( data ); - auto pdata = dynamic_cast< vtkPolyData* >( data ); - if( image != NULL ) - { - /* TODO - if( this->m_ImageName != "" ) - { - } - else - this->SetImage( image, name ); - */ - } - else if( pdata != NULL ) - { - TActor* actor = new TActor( ); - actor->SetMesh( pdata ); - this->m_Actors.push_back( actor ); - this->AddViewProp( actor->GetActor( ), name ); - this->Render( ); - if( this->m_ImageName == "" ) - this->ResetCamera( ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPR3DWidget:: -TWLActor* cpExtensions::QT::MPR3DWidget:: -GetImageActor( int o ) -{ - return( this->m_WLActors[ o % 3 ] ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::QT::MPR3DWidget:: -TWLActor* cpExtensions::QT::MPR3DWidget:: -GetImageActor( int o ) const -{ - return( this->m_WLActors[ o % 3 ] ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPR3DWidget:: -SetSliceNumber( int orientation, int slice ) -{ - int o = orientation % 3; - this->m_WLActors[ o ]->SetSliceNumber( slice ); - this->m_OLActors[ o ]->SetBounds( - o, - this->m_WLActors[ o ]->GetSlicePlane( )->GetOrigin( )[ o ], - this->m_WLActors[ o ]->GetImage( )->GetBounds( ) - ); - this->Render( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPR3DWidget:: -SetSlicesNumbers( int x, int y, int z ) -{ - int s[] = { x, y, z }; - for( int o = 0; o < 3; ++o ) - { - this->m_WLActors[ o ]->SetSliceNumber( s[ o ] ); - this->m_OLActors[ o ]->SetBounds( - o, - this->m_WLActors[ o ]->GetSlicePlane( )->GetOrigin( )[ o ], - this->m_WLActors[ o ]->GetImage( )->GetBounds( ) - ); - - } // rof - this->Render( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/MPR3DWidget.h b/lib/cpExtensions/QT/MPR3DWidget.h deleted file mode 100644 index 6a0ef6e..0000000 --- a/lib/cpExtensions/QT/MPR3DWidget.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef __cpExtensions__QT__MPR3DWidget__h__ -#define __cpExtensions__QT__MPR3DWidget__h__ - -#include - -// ------------------------------------------------------------------------- -class vtkDataSet; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class ImageOutlineActor; - class MeshActor; - class WindowLevelImageActor; - } - - namespace QT - { - /** - */ - class cpExtensions_EXPORT MPR3DWidget - : public cpExtensions::QT::RendererWidget - { - Q_OBJECT; - - public: - typedef MPR3DWidget Self; - typedef cpExtensions::QT::RendererWidget Superclass; - - typedef cpExtensions::Visualization::MeshActor TActor; - typedef cpExtensions::Visualization::ImageOutlineActor TOLActor; - typedef cpExtensions::Visualization::WindowLevelImageActor TWLActor; - - public: - explicit MPR3DWidget( QWidget* parent = NULL, Qt::WindowFlags f = 0 ); - virtual ~MPR3DWidget( ); - - void Clear( ); - void SetImage( vtkImageData* image, const std::string& name ); - void Add( vtkDataSet* data, const std::string& name ); - - TWLActor* GetImageActor( int o ); - const TWLActor* GetImageActor( int o ) const; - - void SetSliceNumber( int orientation, int slice ); - void SetSlicesNumbers( int x, int y, int z ); - - protected: - std::string m_ImageName; - - vtkSmartPointer< TWLActor > m_WLActors[ 3 ]; - vtkSmartPointer< TOLActor > m_OLActors[ 3 ]; - std::vector< TActor* > m_Actors; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__MPR3DWidget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/MPRInteractionCommand.cxx b/lib/cpExtensions/QT/MPRInteractionCommand.cxx deleted file mode 100644 index 39dc19d..0000000 --- a/lib/cpExtensions/QT/MPRInteractionCommand.cxx +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPRInteractionCommand:: -Self* cpExtensions::QT::MPRInteractionCommand:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPRInteractionCommand:: -AddWidget( QWidget* w ) -{ - typedef cpExtensions::QT::ImageWidget _TImageWidget; - typedef cpExtensions::QT::MPR3DWidget _TMPR3DWidget; - - auto img = dynamic_cast< _TImageWidget* >( w ); - auto ren = dynamic_cast< _TMPR3DWidget* >( w ); - if( img != NULL ) - this->m_ImageWidgets.insert( img ); - else if( ren != NULL ) - this->m_MPR3DWidgets.insert( ren ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::MPRInteractionCommand:: -Execute( vtkObject* caller, unsigned long evId, void* data ) -{ - typedef cpExtensions::Interaction::ImageSliceStyle _TStyle; - - static const unsigned long _SuperCursor = vtkCommand::UserEvent + 1; - static const unsigned long _Slice = vtkCommand::UserEvent + 2; - - // Prepare interaction data - auto* src = dynamic_cast< _TStyle* >( caller ); - if( src == NULL || ( evId != _SuperCursor && evId != _Slice ) ) - return; - if( evId == _SuperCursor ) - { - /* TODO - auto ori = src->GetActors( )->GetOrientation( ); - auto img = src->GetActors( )->GetImage( ); - auto pos = reinterpret_cast< double* >( data ); - int ijk[ 3 ]; - double pcoords[ 3 ]; - img->ComputeStructuredCoordinates( pos, ijk, pcoords ); - - for( - auto i = this->m_ImageWidgets.begin( ); - i != this->m_ImageWidgets.end( ); - ++i - ) - if( ( *i )->GetInteractorStyle( ) != src ) - ( *i )->SetSliceNumber( ijk[ ( *i )->GetOrientation( ) ] ); - - for( - auto r = this->m_MPR3DWidgets.begin( ); - r != this->m_MPR3DWidgets.end( ); - ++r - ) - ( *r )->SetSlicesNumbers( ijk[ 0 ], ijk[ 1 ], ijk[ 2 ] ); - */ - } - else if( evId == _Slice ) - { - int slc = src->GetSliceNumber( ); - int ori = src->GetOrientation( ); - for( - auto r = this->m_MPR3DWidgets.begin( ); - r != this->m_MPR3DWidgets.end( ); - ++r - ) - ( *r )->SetSliceNumber( ori, slc ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPRInteractionCommand:: -MPRInteractionCommand( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::MPRInteractionCommand:: -~MPRInteractionCommand( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/MPRInteractionCommand.h b/lib/cpExtensions/QT/MPRInteractionCommand.h deleted file mode 100644 index 29aa5de..0000000 --- a/lib/cpExtensions/QT/MPRInteractionCommand.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef __cpExtensions__QT__MPRInteractionCommand__h__ -#define __cpExtensions__QT__MPRInteractionCommand__h__ - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace QT - { - class ImageWidget; - class MPR3DWidget; - - /** - */ - class cpExtensions_EXPORT MPRInteractionCommand - : public vtkCommand - { - public: - typedef MPRInteractionCommand Self; - - public: - vtkTypeMacro( MPRInteractionCommand, vtkCommand ); - - public: - static Self* New( ); - - void AddWidget( QWidget* w ); - - virtual void Execute( - vtkObject* caller, unsigned long evId, void* data - ) cpExtensions_OVERRIDE; - - protected: - MPRInteractionCommand( ); - virtual ~MPRInteractionCommand( ); - - private: - // Purposely not implemented - MPRInteractionCommand( const Self& ); - Self& operator=( const Self& ); - - protected: - std::set< cpExtensions::QT::ImageWidget* > m_ImageWidgets; - std::set< cpExtensions::QT::MPR3DWidget* > m_MPR3DWidgets; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__MPRInteractionCommand__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/RendererWidget.cxx b/lib/cpExtensions/QT/RendererWidget.cxx deleted file mode 100644 index 0189ef6..0000000 --- a/lib/cpExtensions/QT/RendererWidget.cxx +++ /dev/null @@ -1,990 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::RendererWidget:: -RendererWidget( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - Superclass2( ) -{ - this->m_Renderer = vtkSmartPointer< vtkRenderer >::New( ); - this->GetRenderWindow( )->AddRenderer( this->m_Renderer ); - - vtkAxesActor* axes = vtkAxesActor::New( ); - axes->AxisLabelsOff( ); - this->m_Marker = vtkSmartPointer< vtkOrientationMarkerWidget >::New( ); - this->m_Marker->SetOutlineColor( 1, 1, 1 ); - this->m_Marker->SetOrientationMarker( axes ); - this->m_Marker->SetInteractor( this->GetRenderWindow( )->GetInteractor( ) ); - this->m_Marker->EnabledOn( ); - this->m_Marker->InteractiveOff( ); - axes->Delete( ); - this->SetQuadrant( 0 ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::RendererWidget:: -~RendererWidget( ) -{ -} - -// ------------------------------------------------------------------------- -int cpExtensions::QT::RendererWidget:: -GetQuadrant( ) const -{ - return( this->m_Quadrant ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetQuadrant( int q ) -{ - this->m_Quadrant = ( q - 1 ) % 4; - if( this->m_Quadrant == 0 ) - this->m_Marker->SetViewport( 0.85, 0.00, 1.00, 0.15 ); - else if( this->m_Quadrant == 1 ) - this->m_Marker->SetViewport( 0.00, 0.00, 0.15, 0.15 ); - else if( this->m_Quadrant == 2 ) - this->m_Marker->SetViewport( 0.00, 0.85, 0.15, 1.00 ); - else if( this->m_Quadrant == 3 ) - this->m_Marker->SetViewport( 0.85, 0.85, 1.00, 1.00 ); -} - -// ------------------------------------------------------------------------- -vtkRenderer* cpExtensions::QT::RendererWidget:: -GetRenderer( ) -{ - return( this->m_Renderer ); -} - -// ------------------------------------------------------------------------- -const vtkRenderer* cpExtensions::QT::RendererWidget:: -GetRenderer( ) const -{ - return( this->m_Renderer ); -} - -// ------------------------------------------------------------------------- -vtkInteractorStyle* cpExtensions::QT::RendererWidget:: -GetStyle( ) -{ - auto iren = this->GetInteractor( ); - if( iren != NULL ) - return( - dynamic_cast< vtkInteractorStyle* >( iren->GetInteractorStyle( ) ) - ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const vtkInteractorStyle* cpExtensions::QT::RendererWidget:: -GetStyle( ) const -{ - // Ugly, but necessary :-( - Self* self = const_cast< Self* >( this ); - if( self != NULL ) - { - auto iren = self->GetInteractor( ); - if( iren != NULL ) - return( - dynamic_cast< const vtkInteractorStyle* >( - iren->GetInteractorStyle( ) - ) - ); - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetStyle( vtkInteractorStyle* style ) -{ - this->GetInteractor( )->SetInteractorStyle( style ); -} - -// ------------------------------------------------------------------------- -vtkCamera* cpExtensions::QT::RendererWidget:: -GetActiveCamera( ) -{ - return( this->m_Renderer->GetActiveCamera( ) ); -} - -// ------------------------------------------------------------------------- -const vtkCamera* cpExtensions::QT::RendererWidget:: -GetActiveCamera( ) const -{ - return( this->m_Renderer->GetActiveCamera( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -AddViewProp( vtkProp* prop, const std::string& name ) -{ - if( prop != NULL ) - { - auto i = this->m_ViewProps.find( name ); - if( i == this->m_ViewProps.end( ) ) - i = - this->m_ViewProps.insert( - TPropCollection::value_type( name, TProps( ) ) - ).first; - i->second.insert( prop ); - this->m_Renderer->AddViewProp( prop ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -AddViewProps( vtkPropCollection* props, const std::string& name ) -{ - if( props != NULL ) - { - auto i = this->m_ViewProps.find( name ); - if( i == this->m_ViewProps.end( ) ) - i = - this->m_ViewProps.insert( - TPropCollection::value_type( name, TProps( ) ) - ).first; - props->InitTraversal( ); - while( vtkProp* prop = props->GetNextProp( ) ) - { - i->second.insert( prop ); - this->m_Renderer->AddViewProp( prop ); - - } // elihw - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -AddAuxViewProp( vtkProp* prop, const std::string& name ) -{ - if( prop != NULL ) - { - auto i = this->m_AuxViewProps.find( name ); - if( i == this->m_AuxViewProps.end( ) ) - i = - this->m_AuxViewProps.insert( - TPropCollection::value_type( name, TProps( ) ) - ).first; - i->second.insert( prop ); - this->m_Renderer->AddViewProp( prop ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -AddAuxViewProps( vtkPropCollection* props, const std::string& name ) -{ - if( props != NULL ) - { - auto i = this->m_AuxViewProps.find( name ); - if( i == this->m_AuxViewProps.end( ) ) - i = - this->m_AuxViewProps.insert( - TPropCollection::value_type( name, TProps( ) ) - ).first; - props->InitTraversal( ); - while( vtkProp* prop = props->GetNextProp( ) ) - { - i->second.insert( prop ); - this->m_Renderer->AddViewProp( prop ); - - } // elhiw - - } // fi -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::RendererWidget:: -TProps& cpExtensions::QT::RendererWidget:: -GetViewProps( const std::string& name ) -{ - static TProps zero; - auto i = this->m_ViewProps.find( name ); - if( i == this->m_ViewProps.end( ) ) - { - zero.clear( ); - return( zero ); - } - else - return( i->second ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::QT::RendererWidget:: -TProps& cpExtensions::QT::RendererWidget:: -GetViewProps( const std::string& name ) const -{ - static const TProps zero; - auto i = this->m_ViewProps.find( name ); - if( i == this->m_ViewProps.end( ) ) - return( zero ); - else - return( i->second ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::RendererWidget:: -TProps& cpExtensions::QT::RendererWidget:: -GetAuxViewProps( const std::string& name ) -{ - static TProps zero; - auto i = this->m_AuxViewProps.find( name ); - if( i == this->m_AuxViewProps.end( ) ) - { - zero.clear( ); - return( zero ); - } - else - return( i->second ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::QT::RendererWidget:: -TProps& cpExtensions::QT::RendererWidget:: -GetAuxViewProps( const std::string& name ) const -{ - static const TProps zero; - auto i = this->m_AuxViewProps.find( name ); - if( i == this->m_AuxViewProps.end( ) ) - return( zero ); - else - return( i->second ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -RemoveViewProps( const std::string& name ) -{ - auto i = this->m_ViewProps.find( name ); - if( i != this->m_ViewProps.end( ) ) - { - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - this->m_Renderer->RemoveViewProp( *p ); - this->m_ViewProps.erase( i ); - - } // fi - - i = this->m_AuxViewProps.find( name ); - if( i != this->m_AuxViewProps.end( ) ) - { - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - this->m_Renderer->RemoveViewProp( *p ); - this->m_AuxViewProps.erase( i ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -RemoveViewProps( ) -{ - this->m_Renderer->RemoveAllViewProps( ); - this->m_ViewProps.clear( ); - this->m_AuxViewProps.clear( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -HideViewProps( const std::string& name ) -{ - auto i = this->m_ViewProps.find( name ); - if( i != this->m_ViewProps.end( ) ) - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - ( *p )->VisibilityOff( ); - i = this->m_AuxViewProps.find( name ); - if( i != this->m_AuxViewProps.end( ) ) - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - ( *p )->VisibilityOff( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -ShowViewProps( const std::string& name ) -{ - auto i = this->m_ViewProps.find( name ); - if( i != this->m_ViewProps.end( ) ) - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - ( *p )->VisibilityOn( ); - i = this->m_AuxViewProps.find( name ); - if( i != this->m_AuxViewProps.end( ) ) - for( auto p = i->second.begin( ); p != i->second.end( ); ++p ) - ( *p )->VisibilityOn( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -ResetCamera( ) -{ - this->m_Renderer->ResetCamera( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -Render( ) -{ - this->GetRenderWindow( )->Render( ); -} - -// ------------------------------------------------------------------------- -std::set< vtkRenderWindowInteractor* > cpExtensions::QT::RendererWidget:: -GetInteractors( ) const -{ - Self* self = const_cast< Self* >( this ); - std::set< vtkRenderWindowInteractor* > ret; - ret.insert( self->GetRenderWindow( )->GetInteractor( ) ); - return( ret ); -} - -// ------------------------------------------------------------------------- -std::set< std::string > cpExtensions::QT::RendererWidget:: -GetActorsNames( ) const -{ - std::set< std::string > names; - for( - auto p = this->m_ViewProps.begin( ); - p != this->m_ViewProps.end( ); - ++p - ) - names.insert( p->first ); - return( names ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::RendererWidget:: -IsWindowLevelImageActor( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto a = it->second.begin( ); - if( a != it->second.end( ) ) - return( dynamic_cast< TWLActor* >( a->GetPointer( ) ) != NULL ); - else - return( false ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::RendererWidget:: -IsLUTImageActor( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto a = it->second.begin( ); - if( a != it->second.end( ) ) - return( dynamic_cast< TLUTActor* >( a->GetPointer( ) ) != NULL ); - else - return( false ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::RendererWidget:: -Is3DActor( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto a = it->second.begin( ); - if( a != it->second.end( ) ) - return( dynamic_cast< vtkActor* >( a->GetPointer( ) ) != NULL ); - else - return( false ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -GetScalarRange( const std::string& name, double r[ 2 ] ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - TWLActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - a->GetRange( r ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -GetWindowLevel( const std::string& name, double wl[ 2 ] ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - TWLActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - a->GetWindowLevel( wl ); - - } // fi -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::RendererWidget:: -GetWindow( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - TWLActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetWindow( ) ); - else - return( 0 ); - } - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::RendererWidget:: -GetLevel( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - TWLActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetLevel( ) ); - else - return( 0 ); - } - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -char cpExtensions::QT::RendererWidget:: -GetImageInterpolation( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - TWLActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - { - int int_type = a->GetProperty( )->GetInterpolationType( ); - char ret = 0; - switch( int_type ) - { - case VTK_NEAREST_INTERPOLATION: ret = 'N'; break; - case VTK_LINEAR_INTERPOLATION: ret = 'L'; break; - case VTK_CUBIC_INTERPOLATION: ret = 'C'; break; - default: ret = 0; break; - } // hctiws - return( ret ); - } - else - return( 0 ); - } - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -GetColor( const std::string& name, double& r, double& g, double& b ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - vtkActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetProperty( )->GetColor( r, g, b ) ); - - } // fi -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::RendererWidget:: -GetOpacity( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - vtkActor* a = NULL; - vtkImageSlice* s = NULL; - while( a == NULL && s == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - s = dynamic_cast< vtkImageSlice* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetProperty( )->GetOpacity( ) ); - else if( s != NULL ) - return( s->GetProperty( )->GetOpacity( ) ); - else - return( 0 ); - } - return( 0 ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::RendererWidget:: -GetPointSize( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - vtkActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetProperty( )->GetPointSize( ) ); - else - return( 0 ); - } - return( 0 ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::RendererWidget:: -GetLineWidth( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - vtkActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetProperty( )->GetLineWidth( ) ); - else - return( 0 ); - } - return( 0 ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::QT::RendererWidget:: -GetRepresentation( const std::string& name ) const -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - auto p = it->second.begin( ); - vtkActor* a = NULL; - while( a == NULL && p != it->second.end( ) ) - { - a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - p++; - - } // elihw - if( a != NULL ) - return( a->GetProperty( )->GetRepresentation( ) ); - else - return( -1 ); - } - return( -1 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetScalarRange( const std::string& name, double r[ 2 ] ) -{ - this->SetScalarRange( name, r[ 0 ], r[ 1 ] ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetScalarRange( const std::string& name, double min, double max ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - TWLActor* a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->SetRange( min, max ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetWindowLevel( const std::string& name, double wl[ 2 ] ) -{ - this->SetWindowLevel( name, wl[ 0 ], wl[ 1 ] ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetWindowLevel( const std::string& name, double w, double l ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - TWLActor* a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->SetWindowLevel( w, l ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetWindow( const std::string& name, double w ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - TWLActor* a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->SetWindow( w ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetLevel( const std::string& name, double l ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - TWLActor* a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->SetLevel( l ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetImageInterpolation( const std::string& name, char i ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - TWLActor* a = dynamic_cast< TWLActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - int int_type = VTK_NEAREST_INTERPOLATION; - switch( i ) - { - case 'L': int_type = VTK_LINEAR_INTERPOLATION; break; - case 'C': int_type = VTK_CUBIC_INTERPOLATION; break; - default: int_type = VTK_NEAREST_INTERPOLATION; break; - } // hctiws - a->GetProperty( )->SetInterpolationType( int_type ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetColor( const std::string& name, double r, double g, double b ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetColor( r, g, b ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetOpacity( const std::string& name, double o ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - vtkImageSlice* s = dynamic_cast< vtkImageSlice* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetOpacity( o ); - } - else if( s != NULL ) - { - render = true; - s->GetProperty( )->SetOpacity( o ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetPointSize( const std::string& name, double s ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetPointSize( s ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetLineWidth( const std::string& name, double w ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetLineWidth( w ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetRepresentationToPoints( const std::string& name ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetRepresentationToPoints( ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetRepresentationToSurface( const std::string& name ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetRepresentationToSurface( ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::RendererWidget:: -SetRepresentationToWireframe( const std::string& name ) -{ - auto it = this->m_ViewProps.find( name ); - if( it != this->m_ViewProps.end( ) ) - { - bool render = false; - for( auto p = it->second.begin( ); p != it->second.end( ); ++p ) - { - vtkActor* a = dynamic_cast< vtkActor* >( p->GetPointer( ) ); - if( a != NULL ) - { - render = true; - a->GetProperty( )->SetRepresentationToWireframe( ); - - } // fi - - } // rof - if( render ) - this->Render( ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/RendererWidget.h b/lib/cpExtensions/QT/RendererWidget.h deleted file mode 100644 index 2a5b145..0000000 --- a/lib/cpExtensions/QT/RendererWidget.h +++ /dev/null @@ -1,138 +0,0 @@ -#ifndef __cpExtensions__QT__RendererWidget__h__ -#define __cpExtensions__QT__RendererWidget__h__ - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkCamera; -class vtkInteractorStyle; -class vtkOrientationMarkerWidget; -class vtkProp; -class vtkPropCollection; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class LUTImageActor; - class WindowLevelImageActor; - } - - namespace QT - { - /** - */ - class cpExtensions_EXPORT RendererWidget - : public cpExtensions_QVTKWidget, - public ActorsWidgetInterface - { - Q_OBJECT; - public: - typedef RendererWidget Self; - typedef cpExtensions_QVTKWidget Superclass; - typedef ActorsWidgetInterface Superclass2; - - typedef std::set< vtkSmartPointer< vtkProp > > TProps; - typedef std::map< std::string, TProps > TPropCollection; - - typedef cpExtensions::Visualization::LUTImageActor TLUTActor; - typedef cpExtensions::Visualization::WindowLevelImageActor TWLActor; - - public: - explicit RendererWidget( - QWidget* parent = NULL, Qt::WindowFlags f = 0 - ); - virtual ~RendererWidget( ); - - int GetQuadrant( ) const; - void SetQuadrant( int q ); - - vtkRenderer* GetRenderer( ); - const vtkRenderer* GetRenderer( ) const; - - vtkInteractorStyle* GetStyle( ); - const vtkInteractorStyle* GetStyle( ) const; - void SetStyle( vtkInteractorStyle* style ); - - vtkCamera* GetActiveCamera( ); - const vtkCamera* GetActiveCamera( ) const; - - void AddViewProp( vtkProp* prop, const std::string& name = "" ); - void AddViewProps( - vtkPropCollection* props, const std::string& name = "" - ); - void AddAuxViewProp( vtkProp* prop, const std::string& name = "" ); - void AddAuxViewProps( - vtkPropCollection* props, const std::string& name = "" - ); - - TProps& GetViewProps( const std::string& name ); - const TProps& GetViewProps( const std::string& name ) const; - TProps& GetAuxViewProps( const std::string& name ); - const TProps& GetAuxViewProps( const std::string& name ) const; - - void RemoveViewProps( const std::string& name ); - void RemoveViewProps( ); - - virtual void HideViewProps( const std::string& name ); - virtual void ShowViewProps( const std::string& name ); - - virtual void ResetCamera( ); - virtual void Render( ); - - virtual std::set< vtkRenderWindowInteractor* > GetInteractors( ) const cpExtensions_OVERRIDE; - virtual std::set< std::string > GetActorsNames( ) const cpExtensions_OVERRIDE; - virtual bool IsWindowLevelImageActor( const std::string& name ) const cpExtensions_OVERRIDE; - virtual bool IsLUTImageActor( const std::string& name ) const cpExtensions_OVERRIDE; - virtual bool Is3DActor( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void GetScalarRange( const std::string& name, double r[ 2 ] ) const cpExtensions_OVERRIDE; - virtual void GetWindowLevel( const std::string& name, double wl[ 2 ] ) const cpExtensions_OVERRIDE; - virtual double GetWindow( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetLevel( const std::string& name ) const cpExtensions_OVERRIDE; - virtual char GetImageInterpolation( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void GetColor( const std::string& name, double& r, double& g, double& b ) const cpExtensions_OVERRIDE; - virtual double GetOpacity( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetPointSize( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetLineWidth( const std::string& name ) const cpExtensions_OVERRIDE; - virtual int GetRepresentation( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void SetScalarRange( const std::string& name, double r[ 2 ] ) cpExtensions_OVERRIDE; - virtual void SetScalarRange( const std::string& name, double min, double max ) cpExtensions_OVERRIDE; - virtual void SetWindowLevel( const std::string& name, double wl[ 2 ] ) cpExtensions_OVERRIDE; - virtual void SetWindowLevel( const std::string& name, double w, double l ) cpExtensions_OVERRIDE; - virtual void SetWindow( const std::string& name, double w ) cpExtensions_OVERRIDE; - virtual void SetLevel( const std::string& name, double l ) cpExtensions_OVERRIDE; - virtual void SetImageInterpolation( const std::string& name, char i ) cpExtensions_OVERRIDE; - - virtual void SetColor( const std::string& name, double r, double g, double b ) cpExtensions_OVERRIDE; - virtual void SetOpacity( const std::string& name, double o ) cpExtensions_OVERRIDE; - virtual void SetPointSize( const std::string& name, double s ) cpExtensions_OVERRIDE; - virtual void SetLineWidth( const std::string& name, double w ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToPoints( const std::string& name ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToSurface( const std::string& name ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToWireframe( const std::string& name ) cpExtensions_OVERRIDE; - - protected: - vtkSmartPointer< vtkRenderer > m_Renderer; - vtkSmartPointer< vtkOrientationMarkerWidget > m_Marker; - int m_Quadrant; - - TPropCollection m_ViewProps; - TPropCollection m_AuxViewProps; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__RendererWidget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/SimpleMPRWidget.cxx b/lib/cpExtensions/QT/SimpleMPRWidget.cxx deleted file mode 100644 index 9b47dfd..0000000 --- a/lib/cpExtensions/QT/SimpleMPRWidget.cxx +++ /dev/null @@ -1,635 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::SimpleMPRWidget:: -SimpleMPRWidget( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - Superclass2( ), - m_UI( new Ui::SimpleMPRWidget ), - m_MainImageName( "" ) -{ - this->m_UI->setupUi( this ); - - // Prepare default configuration - this->m_UI->Q1->hide( ); - this->m_UI->Q2->hide( ); - this->m_UI->Q3->hide( ); - this->m_UI->Q4->hide( ); - this->m_UI->Q1->close( ); - this->m_UI->Q2->close( ); - this->m_UI->Q3->close( ); - this->m_UI->Q4->close( ); - delete this->m_UI->Q1; - delete this->m_UI->Q2; - delete this->m_UI->Q3; - delete this->m_UI->Q4; - this->m_XImage = new ImageWidget( this ); - this->m_YImage = new ImageWidget( this ); - this->m_ZImage = new ImageWidget( this ); - this->m_3DView = new MPR3DWidget( this ); - this->m_UI->Q1 = this->m_XImage; - this->m_UI->Q2 = this->m_YImage; - this->m_UI->Q3 = this->m_ZImage; - this->m_UI->Q4 = this->m_3DView; - this->Configure( 'y', 'x', 'w', 'z' ); - - // Interaction synchronizer - unsigned long ev1 = vtkCommand::UserEvent + 1; - unsigned long ev2 = vtkCommand::UserEvent + 2; - vtkSmartPointer< cpExtensions::QT::MPRInteractionCommand > cmd = - vtkSmartPointer< cpExtensions::QT::MPRInteractionCommand >::New( ); - cmd->AddWidget( this->m_XImage ); - cmd->AddWidget( this->m_YImage ); - cmd->AddWidget( this->m_ZImage ); - cmd->AddWidget( this->m_3DView ); - this->m_XImage->GetStyle( )->AddObserver( ev1, cmd ); - this->m_YImage->GetStyle( )->AddObserver( ev1, cmd ); - this->m_ZImage->GetStyle( )->AddObserver( ev1, cmd ); - this->m_XImage->GetStyle( )->AddObserver( ev2, cmd ); - this->m_YImage->GetStyle( )->AddObserver( ev2, cmd ); - this->m_ZImage->GetStyle( )->AddObserver( ev2, cmd ); - - // Connect slots - this->connect( - this->m_UI->Top, SIGNAL( splitterMoved( int, int ) ), - this, SLOT( _SyncBottom( int, int ) ) - ); - this->connect( - this->m_UI->Bottom, SIGNAL( splitterMoved( int, int ) ), - this, SLOT( _SyncTop( int, int ) ) - ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::SimpleMPRWidget:: -~SimpleMPRWidget( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -Configure( char q1, char q2, char q3, char q4 ) -{ - // Hide all widgets - this->m_UI->Q1->hide( ); - this->m_UI->Q2->hide( ); - this->m_UI->Q3->hide( ); - this->m_UI->Q4->hide( ); - this->m_UI->Q1->close( ); - this->m_UI->Q2->close( ); - this->m_UI->Q3->close( ); - this->m_UI->Q4->close( ); - - // Reorder them - if ( q1 == 'x' ) this->m_UI->Top->addWidget( this->m_XImage ); - else if( q1 == 'y' ) this->m_UI->Top->addWidget( this->m_YImage ); - else if( q1 == 'z' ) this->m_UI->Top->addWidget( this->m_ZImage ); - else if( q1 == 'w' ) this->m_UI->Top->addWidget( this->m_3DView ); - if ( q2 == 'x' ) this->m_UI->Top->addWidget( this->m_XImage ); - else if( q2 == 'y' ) this->m_UI->Top->addWidget( this->m_YImage ); - else if( q2 == 'z' ) this->m_UI->Top->addWidget( this->m_ZImage ); - else if( q2 == 'w' ) this->m_UI->Top->addWidget( this->m_3DView ); - this->m_UI->Top->update( ); - if ( q4 == 'x' ) this->m_UI->Bottom->addWidget( this->m_XImage ); - else if( q4 == 'y' ) this->m_UI->Bottom->addWidget( this->m_YImage ); - else if( q4 == 'z' ) this->m_UI->Bottom->addWidget( this->m_ZImage ); - else if( q4 == 'w' ) this->m_UI->Bottom->addWidget( this->m_3DView ); - if ( q3 == 'x' ) this->m_UI->Bottom->addWidget( this->m_XImage ); - else if( q3 == 'y' ) this->m_UI->Bottom->addWidget( this->m_YImage ); - else if( q3 == 'z' ) this->m_UI->Bottom->addWidget( this->m_ZImage ); - else if( q3 == 'w' ) this->m_UI->Bottom->addWidget( this->m_3DView ); - this->m_UI->Bottom->update( ); - - // Keep track - if ( q1 == 'x' ) this->m_UI->Q1 = this->m_XImage; - else if( q1 == 'y' ) this->m_UI->Q1 = this->m_YImage; - else if( q1 == 'z' ) this->m_UI->Q1 = this->m_ZImage; - else if( q1 == 'w' ) this->m_UI->Q1 = this->m_3DView; - if ( q2 == 'x' ) this->m_UI->Q2 = this->m_XImage; - else if( q2 == 'y' ) this->m_UI->Q2 = this->m_YImage; - else if( q2 == 'z' ) this->m_UI->Q2 = this->m_ZImage; - else if( q2 == 'w' ) this->m_UI->Q2 = this->m_3DView; - if ( q3 == 'x' ) this->m_UI->Q3 = this->m_XImage; - else if( q3 == 'y' ) this->m_UI->Q3 = this->m_YImage; - else if( q3 == 'z' ) this->m_UI->Q3 = this->m_ZImage; - else if( q3 == 'w' ) this->m_UI->Q3 = this->m_3DView; - if ( q4 == 'x' ) this->m_UI->Q4 = this->m_XImage; - else if( q4 == 'y' ) this->m_UI->Q4 = this->m_YImage; - else if( q4 == 'z' ) this->m_UI->Q4 = this->m_ZImage; - else if( q4 == 'w' ) this->m_UI->Q4 = this->m_3DView; - - // Draw all - this->m_UI->Q1->show( ); - this->m_UI->Q2->show( ); - this->m_UI->Q3->show( ); - this->m_UI->Q4->show( ); - dynamic_cast< RendererWidget* >( this->m_UI->Q1 )->SetQuadrant( 1 ); - dynamic_cast< RendererWidget* >( this->m_UI->Q2 )->SetQuadrant( 2 ); - dynamic_cast< RendererWidget* >( this->m_UI->Q3 )->SetQuadrant( 3 ); - dynamic_cast< RendererWidget* >( this->m_UI->Q4 )->SetQuadrant( 4 ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::SimpleMPRWidget:: -HasImage( ) const -{ - return( this->m_MainImage.GetPointer( ) != NULL ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetImage( vtkImageData* image, const std::string& name ) -{ - if( this->m_MainImageName != "" || image == NULL ) - { - // TODO: Clear visualization - - } // fi - this->m_MainImageName = name; - this->m_MainImage = image; - - if( this->m_MainImage != NULL && this->m_MainImageName != "" ) - { - this->m_XImage->SetImage( this->m_MainImage, name, 0 ); - this->m_YImage->SetImage( this->m_MainImage, name, 1 ); - this->m_ZImage->SetImage( this->m_MainImage, name, 2 ); - this->m_3DView->SetImage( this->m_MainImage, name ); - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::SimpleMPRWidget:: -Add( vtkDataSet* data, const std::string& name ) -{ - bool success = true; - auto image = dynamic_cast< vtkImageData* >( data ); - auto pdata = dynamic_cast< vtkPolyData* >( data ); - - if( image != NULL ) - { - if( this->m_MainImageName != "" ) - { - this->m_XImage->Add( image, name ); - this->m_YImage->Add( image, name ); - this->m_ZImage->Add( image, name ); - // TODO: this->m_3DView->Add( image, name ); - } - else - this->SetImage( image, name ); - } - else if( pdata != NULL ) - this->m_3DView->Add( pdata, name ); - else - success = false; - return( success ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::SimpleMPRWidget:: -TProps cpExtensions::QT::SimpleMPRWidget:: -GetViewProps( const std::string& name ) const -{ -/* - auto x = this->m_XImage->GetViewProps( name ); - auto y = this->m_YImage->GetViewProps( name ); - auto z = this->m_ZImage->GetViewProps( name ); - auto w = this->m_3DView->GetViewProps( name ); - - TProps props; - if( x != NULL ) props.insert( x ); - if( y != NULL ) props.insert( y ); - if( z != NULL ) props.insert( z ); - if( w != NULL ) props.insert( w ); - return( props ); -*/ - TProps props; - return( props ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::SimpleMPRWidget:: -TProps cpExtensions::QT::SimpleMPRWidget:: -GetImageProps( ) const -{ - return( this->GetViewProps( this->m_MainImageName ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetXInteractor( ) -{ - return( this->m_XImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetXInteractor( ) const -{ - return( this->m_XImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetYInteractor( ) -{ - return( this->m_YImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetYInteractor( ) const -{ - return( this->m_YImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetZInteractor( ) -{ - return( this->m_ZImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetZInteractor( ) const -{ - return( this->m_ZImage->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetWInteractor( ) -{ - return( this->m_3DView->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindowInteractor* cpExtensions::QT::SimpleMPRWidget:: -GetWInteractor( ) const -{ - return( this->m_3DView->GetInteractor( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetXRenderWindow( ) -{ - return( this->m_XImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetXRenderWindow( ) const -{ - return( this->m_XImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetYRenderWindow( ) -{ - return( this->m_YImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetYRenderWindow( ) const -{ - return( this->m_YImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetZRenderWindow( ) -{ - return( this->m_ZImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -const vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetZRenderWindow( ) const -{ - return( this->m_ZImage->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetWRenderWindow( ) -{ - return( this->m_3DView->GetRenderWindow( ) ); -} - - -// ------------------------------------------------------------------------- -const vtkRenderWindow* cpExtensions::QT::SimpleMPRWidget:: -GetWRenderWindow( ) const -{ - return( this->m_3DView->GetRenderWindow( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -ResetCameras( ) -{ - this->m_XImage->ResetCamera( ); - this->m_YImage->ResetCamera( ); - this->m_ZImage->ResetCamera( ); - this->m_3DView->ResetCamera( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -Render( ) -{ - this->m_XImage->Render( ); - this->m_YImage->Render( ); - this->m_ZImage->Render( ); - this->m_3DView->Render( ); -} - -// ------------------------------------------------------------------------- -std::set< vtkRenderWindowInteractor* > cpExtensions::QT::SimpleMPRWidget:: -GetInteractors( ) const -{ - std::set< vtkRenderWindowInteractor* > ret; - ret.insert( this->m_XImage->GetInteractor( ) ); - ret.insert( this->m_YImage->GetInteractor( ) ); - ret.insert( this->m_ZImage->GetInteractor( ) ); - ret.insert( this->m_3DView->GetInteractor( ) ); - return( ret ); -} - -// ------------------------------------------------------------------------- -std::set< std::string > cpExtensions::QT::SimpleMPRWidget:: -GetActorsNames( ) const -{ - std::set< std::string > names = this->m_XImage->GetActorsNames( ); - std::set< std::string > y = this->m_YImage->GetActorsNames( ); - std::set< std::string > z = this->m_ZImage->GetActorsNames( ); - std::set< std::string > w = this->m_3DView->GetActorsNames( ); - names.insert( y.begin( ), y.end( ) ); - names.insert( z.begin( ), z.end( ) ); - names.insert( w.begin( ), w.end( ) ); - return( names ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::SimpleMPRWidget:: -IsWindowLevelImageActor( const std::string& name ) const -{ - return( this->m_XImage->IsWindowLevelImageActor( name ) ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::SimpleMPRWidget:: -IsLUTImageActor( const std::string& name ) const -{ - return( this->m_XImage->IsLUTImageActor( name ) ); -} - -// ------------------------------------------------------------------------- -bool cpExtensions::QT::SimpleMPRWidget:: -Is3DActor( const std::string& name ) const -{ - return( - this->m_XImage->Is3DActor( name ) || this->m_3DView->Is3DActor( name ) - ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -GetScalarRange( const std::string& name, double r[ 2 ] ) const -{ - this->m_XImage->GetScalarRange( name, r ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -GetWindowLevel( const std::string& name, double wl[ 2 ] ) const -{ - this->m_XImage->GetWindowLevel( name, wl ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::SimpleMPRWidget:: -GetWindow( const std::string& name ) const -{ - return( this->m_XImage->GetWindow( name ) ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::SimpleMPRWidget:: -GetLevel( const std::string& name ) const -{ - return( this->m_XImage->GetLevel( name ) ); -} - -// ------------------------------------------------------------------------- -char cpExtensions::QT::SimpleMPRWidget:: -GetImageInterpolation( const std::string& name ) const -{ - return( this->m_XImage->GetImageInterpolation( name ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -GetColor( const std::string& name, double& r, double& g, double& b ) const -{ - this->m_XImage->GetColor( name, r, g, b ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::SimpleMPRWidget:: -GetOpacity( const std::string& name ) const -{ - return( this->m_XImage->GetOpacity( name ) ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::SimpleMPRWidget:: -GetPointSize( const std::string& name ) const -{ - return( this->m_XImage->GetPointSize( name ) ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::QT::SimpleMPRWidget:: -GetLineWidth( const std::string& name ) const -{ - return( this->m_XImage->GetLineWidth( name ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::QT::SimpleMPRWidget:: -GetRepresentation( const std::string& name ) const -{ - return( this->m_XImage->GetRepresentation( name ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetScalarRange( const std::string& name, double r[ 2 ] ) -{ - this->m_XImage->SetScalarRange( name, r ); - this->m_YImage->SetScalarRange( name, r ); - this->m_ZImage->SetScalarRange( name, r ); - this->m_3DView->SetScalarRange( name, r ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetScalarRange( const std::string& name, double min, double max ) -{ - this->m_XImage->SetScalarRange( name, min, max ); - this->m_YImage->SetScalarRange( name, min, max ); - this->m_ZImage->SetScalarRange( name, min, max ); - this->m_3DView->SetScalarRange( name, min, max ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetWindowLevel( const std::string& name, double wl[ 2 ] ) -{ - this->m_XImage->SetWindowLevel( name, wl ); - this->m_YImage->SetWindowLevel( name, wl ); - this->m_ZImage->SetWindowLevel( name, wl ); - this->m_3DView->SetWindowLevel( name, wl ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetWindowLevel( const std::string& name, double w, double l ) -{ - this->m_XImage->SetWindowLevel( name, w, l ); - this->m_YImage->SetWindowLevel( name, w, l ); - this->m_ZImage->SetWindowLevel( name, w, l ); - this->m_3DView->SetWindowLevel( name, w, l ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetWindow( const std::string& name, double w ) -{ - this->m_XImage->SetWindow( name, w ); - this->m_YImage->SetWindow( name, w ); - this->m_ZImage->SetWindow( name, w ); - this->m_3DView->SetWindow( name, w ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetLevel( const std::string& name, double l ) -{ - this->m_XImage->SetLevel( name, l ); - this->m_YImage->SetLevel( name, l ); - this->m_ZImage->SetLevel( name, l ); - this->m_3DView->SetLevel( name, l ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetImageInterpolation( const std::string& name, char i ) -{ - this->m_XImage->SetImageInterpolation( name, i ); - this->m_YImage->SetImageInterpolation( name, i ); - this->m_ZImage->SetImageInterpolation( name, i ); - this->m_3DView->SetImageInterpolation( name, i ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetColor( const std::string& name, double r, double g, double b ) -{ - this->m_XImage->SetColor( name, r, g, b ); - this->m_YImage->SetColor( name, r, g, b ); - this->m_ZImage->SetColor( name, r, g, b ); - this->m_3DView->SetColor( name, r, g, b ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetOpacity( const std::string& name, double o ) -{ - this->m_XImage->SetOpacity( name, o ); - this->m_YImage->SetOpacity( name, o ); - this->m_ZImage->SetOpacity( name, o ); - this->m_3DView->SetOpacity( name, o ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetPointSize( const std::string& name, double s ) -{ - this->m_XImage->SetPointSize( name, s ); - this->m_YImage->SetPointSize( name, s ); - this->m_ZImage->SetPointSize( name, s ); - this->m_3DView->SetPointSize( name, s ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetLineWidth( const std::string& name, double w ) -{ - this->m_XImage->SetLineWidth( name, w ); - this->m_YImage->SetLineWidth( name, w ); - this->m_ZImage->SetLineWidth( name, w ); - this->m_3DView->SetLineWidth( name, w ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetRepresentationToPoints( const std::string& name ) -{ - this->m_XImage->SetRepresentationToPoints( name ); - this->m_YImage->SetRepresentationToPoints( name ); - this->m_ZImage->SetRepresentationToPoints( name ); - this->m_3DView->SetRepresentationToPoints( name ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetRepresentationToSurface( const std::string& name ) -{ - this->m_XImage->SetRepresentationToSurface( name ); - this->m_YImage->SetRepresentationToSurface( name ); - this->m_ZImage->SetRepresentationToSurface( name ); - this->m_3DView->SetRepresentationToSurface( name ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -SetRepresentationToWireframe( const std::string& name ) -{ - this->m_XImage->SetRepresentationToWireframe( name ); - this->m_YImage->SetRepresentationToWireframe( name ); - this->m_ZImage->SetRepresentationToWireframe( name ); - this->m_3DView->SetRepresentationToWireframe( name ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -_SyncBottom( int a, int b ) -{ - this->m_UI->Bottom->setSizes( this->m_UI->Top->sizes( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::SimpleMPRWidget:: -_SyncTop( int a, int b ) -{ - this->m_UI->Top->setSizes( this->m_UI->Bottom->sizes( ) ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/SimpleMPRWidget.h b/lib/cpExtensions/QT/SimpleMPRWidget.h deleted file mode 100644 index bc07ed3..0000000 --- a/lib/cpExtensions/QT/SimpleMPRWidget.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef __cpExtensions__QT__SimpleMPRWidget__h__ -#define __cpExtensions__QT__SimpleMPRWidget__h__ - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkDataSet; -class vtkProp; -class vtkPropCollection; - -namespace Ui { class SimpleMPRWidget; } - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace QT - { - class MPR3DWidget; - class ImageWidget; - - /** - */ - class cpExtensions_EXPORT SimpleMPRWidget - : public QWidget, - public ActorsWidgetInterface - { - Q_OBJECT; - - public: - typedef SimpleMPRWidget Self; - typedef QWidget Superclass; - typedef ActorsWidgetInterface Superclass2; - - typedef vtkSmartPointer< vtkPropCollection > TProp; - typedef std::set< TProp > TProps; - - // typedef cpExtensions::Visualization::MeshActor TMeshActor; - - public: - explicit SimpleMPRWidget( QWidget* parent = NULL, Qt::WindowFlags f = 0 ); - virtual ~SimpleMPRWidget( ); - - void Configure( char q1, char q2, char q3, char q4 ); - - bool HasImage( ) const; - void SetImage( vtkImageData* image, const std::string& name ); - - bool Add( vtkDataSet* data, const std::string& name ); - - TProps GetViewProps( const std::string& name ) const; - TProps GetImageProps( ) const; - - vtkRenderWindowInteractor* GetXInteractor( ); - const vtkRenderWindowInteractor* GetXInteractor( ) const; - vtkRenderWindowInteractor* GetYInteractor( ); - const vtkRenderWindowInteractor* GetYInteractor( ) const; - vtkRenderWindowInteractor* GetZInteractor( ); - const vtkRenderWindowInteractor* GetZInteractor( ) const; - vtkRenderWindowInteractor* GetWInteractor( ); - const vtkRenderWindowInteractor* GetWInteractor( ) const; - - vtkRenderWindow* GetXRenderWindow( ); - const vtkRenderWindow* GetXRenderWindow( ) const; - vtkRenderWindow* GetYRenderWindow( ); - const vtkRenderWindow* GetYRenderWindow( ) const; - vtkRenderWindow* GetZRenderWindow( ); - const vtkRenderWindow* GetZRenderWindow( ) const; - vtkRenderWindow* GetWRenderWindow( ); - const vtkRenderWindow* GetWRenderWindow( ) const; - - void ResetCameras( ); - void Render( ); - - virtual std::set< vtkRenderWindowInteractor* > GetInteractors( ) const cpExtensions_OVERRIDE; - virtual std::set< std::string > GetActorsNames( ) const cpExtensions_OVERRIDE; - virtual bool IsWindowLevelImageActor( const std::string& name ) const cpExtensions_OVERRIDE; - virtual bool IsLUTImageActor( const std::string& name ) const cpExtensions_OVERRIDE; - virtual bool Is3DActor( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void GetScalarRange( const std::string& name, double r[ 2 ] ) const cpExtensions_OVERRIDE; - virtual void GetWindowLevel( const std::string& name, double wl[ 2 ] ) const cpExtensions_OVERRIDE; - virtual double GetWindow( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetLevel( const std::string& name ) const cpExtensions_OVERRIDE; - virtual char GetImageInterpolation( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void GetColor( const std::string& name, double& r, double& g, double& b ) const cpExtensions_OVERRIDE; - virtual double GetOpacity( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetPointSize( const std::string& name ) const cpExtensions_OVERRIDE; - virtual double GetLineWidth( const std::string& name ) const cpExtensions_OVERRIDE; - virtual int GetRepresentation( const std::string& name ) const cpExtensions_OVERRIDE; - - virtual void SetScalarRange( const std::string& name, double r[ 2 ] ) cpExtensions_OVERRIDE; - virtual void SetScalarRange( const std::string& name, double min, double max ) cpExtensions_OVERRIDE; - virtual void SetWindowLevel( const std::string& name, double wl[ 2 ] ) cpExtensions_OVERRIDE; - virtual void SetWindowLevel( const std::string& name, double w, double l ) cpExtensions_OVERRIDE; - virtual void SetWindow( const std::string& name, double w ) cpExtensions_OVERRIDE; - virtual void SetLevel( const std::string& name, double l ) cpExtensions_OVERRIDE; - virtual void SetImageInterpolation( const std::string& name, char i ) cpExtensions_OVERRIDE; - - virtual void SetColor( const std::string& name, double r, double g, double b ) cpExtensions_OVERRIDE; - virtual void SetOpacity( const std::string& name, double o ) cpExtensions_OVERRIDE; - virtual void SetPointSize( const std::string& name, double s ) cpExtensions_OVERRIDE; - virtual void SetLineWidth( const std::string& name, double w ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToPoints( const std::string& name ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToSurface( const std::string& name ) cpExtensions_OVERRIDE; - virtual void SetRepresentationToWireframe( const std::string& name ) cpExtensions_OVERRIDE; - - private slots: - void _SyncBottom( int a, int b ); - void _SyncTop( int a, int b ); - - protected: - Ui::SimpleMPRWidget* m_UI; - - ImageWidget* m_XImage; - ImageWidget* m_YImage; - ImageWidget* m_ZImage; - MPR3DWidget* m_3DView; - - std::string m_MainImageName; - vtkSmartPointer< vtkImageData > m_MainImage; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__SimpleMPRWidget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/SimpleMPRWidget.ui b/lib/cpExtensions/QT/SimpleMPRWidget.ui deleted file mode 100644 index 3f0750e..0000000 --- a/lib/cpExtensions/QT/SimpleMPRWidget.ui +++ /dev/null @@ -1,48 +0,0 @@ - - - SimpleMPRWidget - - - - 0 - 0 - 495 - 394 - - - - Form - - - - 0 - - - 0 - - - - - Qt::Vertical - - - - Qt::Horizontal - - - - - - - Qt::Horizontal - - - - - - - - - - - diff --git a/lib/cpExtensions/QT/WindowLevelImageConfiguration.cxx b/lib/cpExtensions/QT/WindowLevelImageConfiguration.cxx deleted file mode 100644 index b2baa94..0000000 --- a/lib/cpExtensions/QT/WindowLevelImageConfiguration.cxx +++ /dev/null @@ -1,231 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::QT::WindowLevelImageConfiguration:: -WindowLevelImageConfiguration( QWidget* parent, Qt::WindowFlags f ) - : Superclass( parent, f ), - m_UI( new Ui::WindowLevelImageConfiguration ), - m_Data( NULL ), - m_Name( "" ) -{ - this->m_UI->setupUi( this ); -} - -// ------------------------------------------------------------------------- -cpExtensions::QT::WindowLevelImageConfiguration:: -~WindowLevelImageConfiguration( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -setData( ActorsWidgetInterface* data, const std::string& name ) -{ - if( this->m_Data != data ) - { - this->m_Data = data; - this->m_Name = name; - - // Get data - double range[ 2 ], win_lev[ 2 ]; - this->m_Data->GetScalarRange( this->m_Name, range ); - this->m_Data->GetWindowLevel( this->m_Name, win_lev ); - - // Intensity range - this->m_UI->MinimumBox->setMinimum( -1000000 ); - this->m_UI->MinimumBox->setMaximum( 1000000 ); - this->m_UI->MaximumBox->setMinimum( -1000000 ); - this->m_UI->MaximumBox->setMaximum( 1000000 ); - this->m_UI->MinimumBox->setValue( range[ 0 ] ); - this->m_UI->MaximumBox->setValue( range[ 1 ] ); - - // Window/level - double off = range[ 1 ] - range[ 0 ]; - this->m_UI->WindowBox->setMinimum( 0 ); - this->m_UI->WindowBox->setMaximum( off ); - this->m_UI->LevelBox->setMinimum( range[ 0 ] ); - this->m_UI->LevelBox->setMaximum( range[ 1 ] ); - this->m_UI->WindowBox->setValue( win_lev[ 0 ] ); - this->m_UI->LevelBox->setValue( win_lev[ 1 ] ); - - double w = win_lev[ 0 ] / off; - w *= - double( this->m_UI->WindowSlider->maximum( ) ) - - double( this->m_UI->WindowSlider->minimum( ) ); - w += double( this->m_UI->WindowSlider->minimum( ) ); - this->m_UI->WindowSlider->setValue( w ); - - double l = ( win_lev[ 1 ] - range[ 0 ] ) / off; - l *= - double( this->m_UI->LevelSlider->maximum( ) ) - - double( this->m_UI->LevelSlider->minimum( ) ); - l += double( this->m_UI->LevelSlider->minimum( ) ); - this->m_UI->LevelSlider->setValue( l ); - - // Opacity - double o = this->m_Data->GetOpacity( this->m_Name ); - o *= - double( this->m_UI->OpacitySlider->maximum( ) ) - - double( this->m_UI->OpacitySlider->minimum( ) ); - o += double( this->m_UI->OpacitySlider->minimum( ) ); - this->m_UI->OpacitySlider->setValue( o ); - - // Interpolation mode - switch( this->m_Data->GetImageInterpolation( this->m_Name ) ) - { - case 'L': this->m_UI->InterpolatorBox->setCurrentIndex( 1 ); break; - case 'C': this->m_UI->InterpolatorBox->setCurrentIndex( 2 ); break; - default : this->m_UI->InterpolatorBox->setCurrentIndex( 0 ); break; - } // hctiws - - // Slots <-> signals - this->connect( - this->m_UI->MaximumBox, SIGNAL( valueChanged( int ) ), - this, SLOT( _maximumValue( int ) ) - ); - this->connect( - this->m_UI->MinimumBox, SIGNAL( valueChanged( int ) ), - this, SLOT( _minimumValue( int ) ) - ); - this->connect( - this->m_UI->LevelBox, SIGNAL( valueChanged( int ) ), - this, SLOT( _levelValue( int ) ) - ); - this->connect( - this->m_UI->LevelSlider, SIGNAL( valueChanged( int ) ), - this, SLOT( _levelValue( int ) ) - ); - this->connect( - this->m_UI->WindowBox, SIGNAL( valueChanged( int ) ), - this, SLOT( _windowValue( int ) ) - ); - this->connect( - this->m_UI->WindowSlider, SIGNAL( valueChanged( int ) ), - this, SLOT( _windowValue( int ) ) - ); - this->connect( - this->m_UI->OpacitySlider, SIGNAL( valueChanged( int ) ), - this, SLOT( _opacityValue( int ) ) - ); - this->connect( - this->m_UI->InterpolatorBox, SIGNAL( currentIndexChanged( int ) ), - this, SLOT( _interpolatorValue( int ) ) - ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_maximumValue( int v ) -{ - double range[ 2 ]; - range[ 0 ] = double( this->m_UI->MinimumBox->value( ) ); - range[ 1 ] = double( v ); - this->m_Data->SetScalarRange( this->m_Name, range ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_minimumValue( int v ) -{ - double range[ 2 ]; - range[ 0 ] = double( v ); - range[ 1 ] = double( this->m_UI->MaximumBox->value( ) ); - this->m_Data->SetScalarRange( this->m_Name, range ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_levelValue( int v ) -{ - double r[ 2 ]; - double l, s; - - this->m_Data->GetScalarRange( this->m_Name, r ); - if( this->sender( ) == this->m_UI->LevelSlider ) - { - s = double( v ) / double( this->m_UI->LevelSlider->maximum( ) ); - l = ( ( r[ 1 ] - r[ 0 ] ) * s ) + r[ 0 ]; - } - else - { - l = double( v ); - s = ( l - r[ 0 ] ) / ( r[ 1 ] - r[ 0 ] ); - - } // fi - s *= this->m_UI->LevelSlider->maximum( ); - - bool b = this->m_UI->LevelSlider->blockSignals( true ); - this->m_UI->LevelSlider->setValue( s ); - this->m_UI->LevelSlider->blockSignals( b ); - b = this->m_UI->LevelBox->blockSignals( true ); - this->m_UI->LevelBox->setValue( l ); - this->m_UI->LevelBox->blockSignals( b ); - - this->m_Data->SetLevel( this->m_Name, l ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_windowValue( int v ) -{ - double r[ 2 ]; - double w, s; - - this->m_Data->GetScalarRange( this->m_Name, r ); - if( this->sender( ) == this->m_UI->WindowSlider ) - { - s = double( v ) / double( this->m_UI->WindowSlider->maximum( ) ); - w = ( ( r[ 1 ] - r[ 0 ] ) * s ) + r[ 0 ]; - } - else - { - w = double( v ); - s = ( w - r[ 0 ] ) / ( r[ 1 ] - r[ 0 ] ); - - } // fi - s *= this->m_UI->WindowSlider->maximum( ); - - bool b = this->m_UI->WindowSlider->blockSignals( true ); - this->m_UI->WindowSlider->setValue( s ); - this->m_UI->WindowSlider->blockSignals( b ); - b = this->m_UI->WindowBox->blockSignals( true ); - this->m_UI->WindowBox->setValue( w ); - this->m_UI->WindowBox->blockSignals( b ); - - this->m_Data->SetWindow( this->m_Name, w ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_opacityValue( int v ) -{ - if( this->m_Data != NULL ) - { - double o = double( v ); - o -= double( this->m_UI->OpacitySlider->minimum( ) ); - o /= - double( this->m_UI->OpacitySlider->maximum( ) ) - - double( this->m_UI->OpacitySlider->minimum( ) ); - this->m_Data->SetOpacity( this->m_Name, o ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::QT::WindowLevelImageConfiguration:: -_interpolatorValue( int v ) -{ - switch( v ) - { - case 1 : this->m_Data->SetImageInterpolation( this->m_Name, 'L' ); break; - case 2 : this->m_Data->SetImageInterpolation( this->m_Name, 'C' ); break; - default : this->m_Data->SetImageInterpolation( this->m_Name, 'N' ); break; - } // hctiws -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/WindowLevelImageConfiguration.h b/lib/cpExtensions/QT/WindowLevelImageConfiguration.h deleted file mode 100644 index 1725253..0000000 --- a/lib/cpExtensions/QT/WindowLevelImageConfiguration.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef __cpExtensions__QT__WindowLevelImageConfiguration__h__ -#define __cpExtensions__QT__WindowLevelImageConfiguration__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace Ui { class WindowLevelImageConfiguration; } - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace QT - { - class ActorsWidgetInterface; - - /** - */ - class cpExtensions_EXPORT WindowLevelImageConfiguration - : public QWidget - { - Q_OBJECT; - - public: - typedef WindowLevelImageConfiguration Self; - typedef QWidget Superclass; - - public: - explicit WindowLevelImageConfiguration( - QWidget* parent = NULL, Qt::WindowFlags f = 0 - ); - virtual ~WindowLevelImageConfiguration( ); - - void setData( ActorsWidgetInterface* data, const std::string& name ); - - protected slots: - void _maximumValue( int v ); - void _minimumValue( int v ); - void _levelValue( int v ); - void _windowValue( int v ); - void _opacityValue( int v ); - void _interpolatorValue( int v ); - - protected: - Ui::WindowLevelImageConfiguration* m_UI; - ActorsWidgetInterface* m_Data; - std::string m_Name; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__QT__WindowLevelImageConfiguration__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/QT/WindowLevelImageConfiguration.ui b/lib/cpExtensions/QT/WindowLevelImageConfiguration.ui deleted file mode 100644 index 65d066e..0000000 --- a/lib/cpExtensions/QT/WindowLevelImageConfiguration.ui +++ /dev/null @@ -1,216 +0,0 @@ - - - WindowLevelImageConfiguration - - - - 0 - 0 - 313 - 322 - - - - - 313 - 322 - - - - Form - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - - - Window: - - - - - - - - - - - - 1000 - - - 100 - - - Qt::Horizontal - - - - - - - - - - - - - Level: - - - - - - - - - - - - 1000 - - - 100 - - - Qt::Horizontal - - - - - - - - - - - Minimum: - - - - - - - - - - Maximum: - - - - - - - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - 0 - - - - - - - - 16777215 - 16777215 - - - - Interpolation: - - - - - - - - Nearest - - - - - Linear - - - - - Cubic - - - - - - - - - - - - Opacity: - - - - - - - 100 - - - Qt::Horizontal - - - - - - - - - - - - label - label_2 - label_3 - label_4 - label_5 - label_6 - InterpolatorBox - WindowSlider - LevelSlider - OpacitySlider - MinimumBox - MaximumBox - WindowSlider - frame - frame_2 - - - - diff --git a/lib/cpExtensions/Visualization/CursorActors.cxx b/lib/cpExtensions/Visualization/CursorActors.cxx deleted file mode 100644 index 29dedc3..0000000 --- a/lib/cpExtensions/Visualization/CursorActors.cxx +++ /dev/null @@ -1,176 +0,0 @@ -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::CursorActors:: -Self* cpExtensions::Visualization::CursorActors:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -Modified( ) -{ - for( unsigned int i = 0; i < 2; ++i ) - { - if( this->m_Lines[ i ].GetPointer( ) != NULL ) - { - this->m_Lines[ i ]->Modified( ); - this->m_Mappers[ i ]->Modified( ); - this->m_Actors[ i ]->Modified( ); - - } // fi - - } // rof - this->Superclass::Modified( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -SetImageBounds( double* bounds ) -{ - this->m_Bounds[ 0 ] = bounds[ 0 ]; - this->m_Bounds[ 1 ] = bounds[ 1 ]; - this->m_Bounds[ 2 ] = bounds[ 2 ]; - this->m_Bounds[ 3 ] = bounds[ 3 ]; - this->m_Bounds[ 4 ] = bounds[ 4 ]; - this->m_Bounds[ 5 ] = bounds[ 5 ]; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -SetImageOrientation( int orientation ) -{ - this->m_Orientation = orientation % 3; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -SetCursor( double* pos, bool neg ) -{ - static const double _eps = 1e-3; - double pnts[ 4 ][ 3 ]; - if( this->m_Orientation == 0 ) - { - pnts[ 0 ][ 1 ] = this->m_Bounds[ 2 ]; - pnts[ 1 ][ 1 ] = this->m_Bounds[ 3 ]; - pnts[ 0 ][ 2 ] = pnts[ 1 ][ 2 ] = pos[ 2 ]; - - pnts[ 2 ][ 1 ] = pnts[ 3 ][ 1 ] = pos[ 1 ]; - pnts[ 2 ][ 2 ] = this->m_Bounds[ 4 ]; - pnts[ 3 ][ 2 ] = this->m_Bounds[ 5 ]; - - pnts[ 0 ][ 0 ] = pnts[ 1 ][ 0 ] = - pnts[ 2 ][ 0 ] = pnts[ 3 ][ 0 ] = - pos[ 0 ] + ( double( neg? -1: 1 ) * _eps ); - } - else if( this->m_Orientation == 1 ) - { - pnts[ 0 ][ 0 ] = pnts[ 1 ][ 0 ] = pos[ 0 ]; - pnts[ 0 ][ 2 ] = this->m_Bounds[ 4 ]; - pnts[ 1 ][ 2 ] = this->m_Bounds[ 5 ]; - - pnts[ 2 ][ 0 ] = this->m_Bounds[ 0 ]; - pnts[ 3 ][ 0 ] = this->m_Bounds[ 1 ]; - pnts[ 2 ][ 2 ] = pnts[ 3 ][ 2 ] = pos[ 2 ]; - - pnts[ 0 ][ 1 ] = pnts[ 1 ][ 1 ] = - pnts[ 2 ][ 1 ] = pnts[ 3 ][ 1 ] = - pos[ 1 ] + ( double( neg? -1: 1 ) * _eps ); - } - else if( this->m_Orientation == 2 ) - { - pnts[ 0 ][ 0 ] = this->m_Bounds[ 0 ]; - pnts[ 1 ][ 0 ] = this->m_Bounds[ 1 ]; - pnts[ 0 ][ 1 ] = pnts[ 1 ][ 1 ] = pos[ 1 ]; - - pnts[ 2 ][ 0 ] = pnts[ 3 ][ 0 ] = pos[ 0 ]; - pnts[ 2 ][ 1 ] = this->m_Bounds[ 2 ]; - pnts[ 3 ][ 1 ] = this->m_Bounds[ 3 ]; - - pnts[ 0 ][ 2 ] = pnts[ 1 ][ 2 ] = - pnts[ 2 ][ 2 ] = pnts[ 3 ][ 2 ] = - pos[ 2 ] + ( double( neg? -1: 1 ) * _eps ); - - } // fi - - this->m_Lines[ 0 ]->SetPoint1( pnts[ 0 ] ); - this->m_Lines[ 0 ]->SetPoint2( pnts[ 1 ] ); - this->m_Lines[ 1 ]->SetPoint1( pnts[ 2 ] ); - this->m_Lines[ 1 ]->SetPoint2( pnts[ 3 ] ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -vtkProperty* cpExtensions::Visualization::CursorActors:: -GetProperty( unsigned int i ) -{ - return( this->m_Actors[ i % 2 ]->GetProperty( ) ); -} - -// ------------------------------------------------------------------------- -const vtkProperty* cpExtensions::Visualization::CursorActors:: -GetProperty( unsigned int i ) const -{ - return( this->m_Actors[ i % 2 ]->GetProperty( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -SetVisibility( int v ) -{ - this->m_Actors[ 0 ]->SetVisibility( v ); - this->m_Actors[ 1 ]->SetVisibility( v ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -VisibilityOn( ) -{ - this->m_Actors[ 0 ]->VisibilityOn( ); - this->m_Actors[ 1 ]->VisibilityOn( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::CursorActors:: -VisibilityOff( ) -{ - this->m_Actors[ 0 ]->VisibilityOff( ); - this->m_Actors[ 1 ]->VisibilityOff( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::CursorActors:: -CursorActors( ) - : Superclass( ) -{ - this->m_Bounds[ 0 ] = this->m_Bounds[ 1 ] = this->m_Bounds[ 2 ] = - this->m_Bounds[ 3 ] = this->m_Bounds[ 4 ] = this->m_Bounds[ 5 ] = - double( 0 ); - - for( unsigned int i = 0; i < 2; ++i ) - { - this->m_Lines[ i ] = vtkSmartPointer< LineSource >::New( ); - this->m_Mappers[ i ] = vtkSmartPointer< vtkPolyDataMapper >::New( ); - this->m_Actors[ i ] = vtkSmartPointer< vtkActor >::New( ); - this->m_Mappers[ i ]->SetInputConnection( - this->m_Lines[ i ]->GetOutputPort( ) - ); - this->m_Actors[ i ]->SetMapper( this->m_Mappers[ i ] ); - this->AddItem( this->m_Actors[ i ] ); - - } // rof -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::CursorActors:: -~CursorActors( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/CursorActors.h b/lib/cpExtensions/Visualization/CursorActors.h deleted file mode 100644 index 77a6d8e..0000000 --- a/lib/cpExtensions/Visualization/CursorActors.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef __cpExtensions__Visualization__CursorActors__h__ -#define __cpExtensions__Visualization__CursorActors__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkActor; -class vtkPolyDataMapper; -class vtkProperty; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class LineSource; - - /** - */ - class cpExtensions_EXPORT CursorActors - : public vtkPropCollection - { - public: - typedef CursorActors Self; - - public: - vtkTypeMacro( CursorActors, vtkPropCollection ); - - public: - static Self* New( ); - - virtual void Modified( ) cpExtensions_OVERRIDE; - - void SetImageBounds( double* bounds ); - void SetImageOrientation( int orientation ); - void SetCursor( double* pos, bool neg ); - - vtkProperty* GetProperty( unsigned int i ); - const vtkProperty* GetProperty( unsigned int i ) const; - - void SetVisibility( int v ); - void VisibilityOn( ); - void VisibilityOff( ); - - protected: - CursorActors( ); - virtual ~CursorActors( ); - - private: - // Purposely not implemented - CursorActors( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< LineSource > m_Lines[ 2 ]; - vtkSmartPointer< vtkPolyDataMapper > m_Mappers[ 2 ]; - vtkSmartPointer< vtkActor > m_Actors[ 2 ]; - double m_Bounds[ 6 ]; - int m_Orientation; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__CursorActors__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageActor.cxx b/lib/cpExtensions/Visualization/ImageActor.cxx deleted file mode 100644 index d1f72ac..0000000 --- a/lib/cpExtensions/Visualization/ImageActor.cxx +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageActor:: -Modified( ) -{ - if( this->m_Mapper->GetNumberOfInputConnections( 0 ) > 0 ) - { - this->m_Mapper->Modified( ); - this->m_Mapper->Update( ); - this->Superclass::Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::ImageActor:: -GetOrientation( ) const -{ - return( this->m_Mapper->GetOrientation( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageActor:: -SetOrientation( int orientation ) -{ - this->m_Mapper->SetOrientation( ( orientation < 3 )? orientation: 2 ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::ImageActor:: -GetSliceNumber( ) const -{ - return( this->m_Mapper->GetSliceNumber( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageActor:: -SetSliceNumber( int slice ) -{ - static int s = 0; - auto image = this->m_Mapper->GetInput( ); - if( image != NULL ) - { - // Update slice - s = slice; - if( s < this->m_Mapper->GetSliceNumberMinValue( ) ) - s = this->m_Mapper->GetSliceNumberMinValue( ); - if( s > this->m_Mapper->GetSliceNumberMaxValue( ) ) - s = this->m_Mapper->GetSliceNumberMaxValue( ); - this->m_Mapper->SetSliceNumber( s ); - this->InvokeEvent( vtkCommand::InteractionEvent, &s ); - - // Propagate modifications - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -vtkPlane* cpExtensions::Visualization::ImageActor:: -GetSlicePlane( ) -{ - return( this->m_Mapper->GetSlicePlane( ) ); -} - -// ------------------------------------------------------------------------- -const vtkPlane* cpExtensions::Visualization::ImageActor:: -GetSlicePlane( ) const -{ - return( this->m_Mapper->GetSlicePlane( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageActor:: -ImageActor( ) - : Superclass( ) -{ - this->m_Mapper = vtkSmartPointer< ImageSliceMapper >::New( ); - this->SetMapper( this->m_Mapper ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageActor:: -~ImageActor( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageActor.h b/lib/cpExtensions/Visualization/ImageActor.h deleted file mode 100644 index c62c132..0000000 --- a/lib/cpExtensions/Visualization/ImageActor.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageActor__h__ -#define __cpExtensions__Visualization__ImageActor__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkImageAlgorithm; -class vtkImageData; -class vtkPlane; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class ImageSliceMapper; - - /** - */ - class cpExtensions_EXPORT ImageActor - : public vtkImageSlice - { - public: - typedef ImageActor Self; - - public: - vtkTypeMacro( ImageActor, vtkImageSlice ); - - public: - virtual void Modified( ) cpExtensions_OVERRIDE; - - int GetOrientation( ) const; - void SetOrientation( int orientation ); - - int GetSliceNumber( ) const; - void SetSliceNumber( int slice ); - - vtkPlane* GetSlicePlane( ); - const vtkPlane* GetSlicePlane( ) const; - - protected: - ImageActor( ); - virtual ~ImageActor( ); - - private: - // Purposely not implemented - ImageActor( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< ImageSliceMapper > m_Mapper; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageActor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.h b/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.h deleted file mode 100644 index 5129512..0000000 --- a/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.h +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__H__ -#define __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__H__ - -#include -#include - -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - template< class _TIndexes > - class ImageIndexesContainerToPolyData - : public vtkPolyDataAlgorithm - { - public: - typedef ImageIndexesContainerToPolyData Self; - - typedef _TIndexes TIndexes; - typedef typename TIndexes::ComponentType TContainer; - typedef typename TContainer::value_type TIndex; - typedef itk::ImageBase< TIndex::Dimension > TImage; - - public: - vtkTypeMacro( ImageIndexesContainerToPolyData, vtkPolyDataAlgorithm ); - - public: - static Self* New( ); - - const TIndexes* GetInput( ) const; - const TImage* GetReferenceImage( ) const; - void SetInput( const TIndexes* c ); - void SetReferenceImage( const TImage* i ); - - protected: - ImageIndexesContainerToPolyData( ); - virtual ~ImageIndexesContainerToPolyData( ); - - int RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - int RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - - private: - // Purposely not implemented - ImageIndexesContainerToPolyData( const Self& ); - void operator=( const Self& ); - - protected: - const TIndexes* m_Indexes; - const TImage* m_ReferenceImage; - }; - - } // ecapseman - -} // ecapseman - -#ifndef ITK_MANUAL_INSTANTIATION -#include -#endif // ITK_MANUAL_INSTANTIATION - -#endif // __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__H__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.hxx b/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.hxx deleted file mode 100644 index a1403ce..0000000 --- a/lib/cpExtensions/Visualization/ImageIndexesContainerToPolyData.hxx +++ /dev/null @@ -1,188 +0,0 @@ -#ifndef __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__HXX__ -#define __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__HXX__ - -#include -#include - -// ------------------------------------------------------------------------- -template< class _TIndexes > -typename cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -Self* cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -const typename cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -TIndexes* cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -GetInput( ) const -{ - return( this->m_Indexes ); -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -const typename cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -TImage* cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -GetReferenceImage( ) const -{ - return( this->m_ReferenceImage ); -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -void cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -SetInput( const TIndexes* c ) -{ - if( this->m_Indexes != c ) - { - this->m_Indexes = c; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -void cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -SetReferenceImage( const TImage* i ) -{ - if( this->m_ReferenceImage != i ) - { - this->m_ReferenceImage = i; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -ImageIndexesContainerToPolyData( ) - : vtkPolyDataAlgorithm( ), - m_Indexes( NULL ), - m_ReferenceImage( NULL ) -{ - this->SetNumberOfInputPorts( 0 ); -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -~ImageIndexesContainerToPolyData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -int cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - static const unsigned int dim = TIndex::Dimension; - - if( this->m_Indexes == NULL ) - return( 0 ); - - // Get output - vtkInformation* info = output->GetInformationObject( 0 ); - vtkPolyData* out = vtkPolyData::SafeDownCast( - info->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Get input data - auto& lst = this->m_Indexes->Get( ); - - // Prepare points - vtkPoints* points = out->GetPoints( ); - if( points == NULL ) - { - points = vtkPoints::New( ); - out->SetPoints( points ); - points->Delete( ); - - } // fi - points->SetNumberOfPoints( lst.size( ) ); - - // Prepare cells - vtkSmartPointer< vtkCellArray > verts = - vtkSmartPointer< vtkCellArray >::New( ); - - for( unsigned int i = 0; i < lst.size( ); ++i ) - { - auto idx = lst[ i ]; - if( this->m_ReferenceImage != NULL ) - { - typename TImage::PointType pnt; - this->m_ReferenceImage->TransformIndexToPhysicalPoint( idx, pnt ); - if( dim == 1 ) - points->SetPoint( i, pnt[ 0 ], 0, 0 ); - else if( dim == 2 ) - points->SetPoint( i, pnt[ 0 ], pnt[ 1 ], 0 ); - else - points->SetPoint( i, pnt[ 0 ], pnt[ 1 ], pnt[ 2 ] ); - } - else - { - if( dim == 1 ) - points->SetPoint( i, idx[ 0 ], 0, 0 ); - else if( dim == 2 ) - points->SetPoint( i, idx[ 0 ], idx[ 1 ], 0 ); - else - points->SetPoint( i, idx[ 0 ], idx[ 1 ], idx[ 2 ] ); - - } // fi - verts->InsertNextCell( 1 ); - verts->InsertCellPoint( i ); - - } // rof - out->SetPoints( points ); - out->SetVerts( verts ); - return( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TIndexes > -int -cpExtensions::Visualization::ImageIndexesContainerToPolyData< _TIndexes >:: -RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - vtkInformation* info = output->GetInformationObject( 0 ); - /* TODO - info->Set( - vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES( ), -1 - ); - */ - - if( this->m_Indexes != NULL && this->m_ReferenceImage != NULL ) - { - /* TODO - typename C::TScalar len = this->m_RGC->GetTotalLength( ); - typename C::TScalar s0 = this->m_RGC->Gets0( ); - typename C::TPoint p0 = this->m_RGC->Axis( s0 ); - typename C::TPoint p1 = this->m_RGC->Axis( s0 + len ); - - info->Set( - vtkStreamingDemandDrivenPipeline::WHOLE_BOUNDING_BOX( ), - double( p0[ 0 ] ), double( p1[ 0 ] ), - double( p0[ 1 ] ), double( p1[ 1 ] ), - double( p0[ 2 ] ), double( p1[ 2 ] ) - ); - */ - - } // fi - return( 1 ); -} - -#endif // __CPEXTENSIONS__VISUALIZATION__IMAGEINDEXESCONTAINERTOPOLYDATA__HXX__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageOutlineActor.cxx b/lib/cpExtensions/Visualization/ImageOutlineActor.cxx deleted file mode 100644 index 9cef8d1..0000000 --- a/lib/cpExtensions/Visualization/ImageOutlineActor.cxx +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -double cpExtensions::Visualization::ImageOutlineActor::Colors[ 3 ][ 3 ] = -{ - { 1, 0, 0 }, - { 0, 1, 0 }, - { 0, 0, 1 } -}; - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineActor:: -Self* cpExtensions::Visualization::ImageOutlineActor:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageOutlineActor:: -Modified( ) -{ - this->m_Outline->Modified( ); - this->m_Mapper->Modified( ); - this->Superclass::Modified( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageOutlineActor:: -SetBounds( int orientation, double step, double* bounds ) -{ - // Update geometry - this->m_Outline->SetBounds( orientation, step, bounds ); - - // Update visualization properties - int o = orientation % 3; - this->GetProperty( )->SetLineWidth( 1.5 ); - this->GetProperty( )->SetColor( - Self::Colors[ o ][ 0 ], - Self::Colors[ o ][ 1 ], - Self::Colors[ o ][ 2 ] - ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineActor:: -ImageOutlineActor( ) - : Superclass( ) -{ - this->m_Outline = vtkSmartPointer< ImageOutlineSource >::New( ); - this->m_Mapper = vtkSmartPointer< vtkPolyDataMapper >::New( ); - this->m_Mapper->SetInputConnection( this->m_Outline->GetOutputPort( ) ); - this->SetMapper( this->m_Mapper ); - - this->UseBoundsOff( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineActor:: -~ImageOutlineActor( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageOutlineActor.h b/lib/cpExtensions/Visualization/ImageOutlineActor.h deleted file mode 100644 index 5ba8c73..0000000 --- a/lib/cpExtensions/Visualization/ImageOutlineActor.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageOutlineActor__h__ -#define __cpExtensions__Visualization__ImageOutlineActor__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkPolyDataMapper; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class ImageOutlineSource; - - /** - */ - class cpExtensions_EXPORT ImageOutlineActor - : public vtkOpenGLActor - { - public: - typedef ImageOutlineActor Self; - - public: - vtkTypeMacro( ImageOutlineActor, vtkOpenGLActor ); - - public: - static Self* New( ); - - virtual void Modified( ) cpExtensions_OVERRIDE; - - void SetBounds( int orientation, double step, double* bounds ); - - protected: - ImageOutlineActor( ); - virtual ~ImageOutlineActor( ); - - private: - // Purposely not implemented - ImageOutlineActor( const Self& ); - Self& operator=( const Self& ); - - public: - static double Colors[ 3 ][ 3 ]; - - protected: - vtkSmartPointer< ImageOutlineSource > m_Outline; - vtkSmartPointer< vtkPolyDataMapper > m_Mapper; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageOutlineActor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageOutlineSource.cxx b/lib/cpExtensions/Visualization/ImageOutlineSource.cxx deleted file mode 100644 index 8fa8131..0000000 --- a/lib/cpExtensions/Visualization/ImageOutlineSource.cxx +++ /dev/null @@ -1,156 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineSource:: -Self* cpExtensions::Visualization::ImageOutlineSource:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageOutlineSource:: -SetBounds( int orientation, double step, double* bounds ) -{ - // Update geometry - int o = orientation % 3; - if( o == 0 ) - { - this->m_Bounds[ 0 ][ 0 ] = step; - this->m_Bounds[ 0 ][ 1 ] = bounds[ 2 ]; - this->m_Bounds[ 0 ][ 2 ] = bounds[ 4 ]; - - this->m_Bounds[ 1 ][ 0 ] = step; - this->m_Bounds[ 1 ][ 1 ] = bounds[ 2 ]; - this->m_Bounds[ 1 ][ 2 ] = bounds[ 5 ]; - - this->m_Bounds[ 2 ][ 0 ] = step; - this->m_Bounds[ 2 ][ 1 ] = bounds[ 3 ]; - this->m_Bounds[ 2 ][ 2 ] = bounds[ 5 ]; - - this->m_Bounds[ 3 ][ 0 ] = step; - this->m_Bounds[ 3 ][ 1 ] = bounds[ 3 ]; - this->m_Bounds[ 3 ][ 2 ] = bounds[ 4 ]; - } - else if( o == 1 ) - { - this->m_Bounds[ 0 ][ 0 ] = bounds[ 0 ]; - this->m_Bounds[ 0 ][ 1 ] = step; - this->m_Bounds[ 0 ][ 2 ] = bounds[ 4 ]; - - this->m_Bounds[ 1 ][ 0 ] = bounds[ 1 ]; - this->m_Bounds[ 1 ][ 1 ] = step; - this->m_Bounds[ 1 ][ 2 ] = bounds[ 4 ]; - - this->m_Bounds[ 2 ][ 0 ] = bounds[ 1 ]; - this->m_Bounds[ 2 ][ 1 ] = step; - this->m_Bounds[ 2 ][ 2 ] = bounds[ 5 ]; - - this->m_Bounds[ 3 ][ 0 ] = bounds[ 0 ]; - this->m_Bounds[ 3 ][ 1 ] = step; - this->m_Bounds[ 3 ][ 2 ] = bounds[ 5 ]; - } - else if( o == 2 ) - { - this->m_Bounds[ 0 ][ 0 ] = bounds[ 0 ]; - this->m_Bounds[ 0 ][ 1 ] = bounds[ 2 ]; - this->m_Bounds[ 0 ][ 2 ] = step; - - this->m_Bounds[ 1 ][ 0 ] = bounds[ 1 ]; - this->m_Bounds[ 1 ][ 1 ] = bounds[ 2 ]; - this->m_Bounds[ 1 ][ 2 ] = step; - - this->m_Bounds[ 2 ][ 0 ] = bounds[ 1 ]; - this->m_Bounds[ 2 ][ 1 ] = bounds[ 3 ]; - this->m_Bounds[ 2 ][ 2 ] = step; - - this->m_Bounds[ 3 ][ 0 ] = bounds[ 0 ]; - this->m_Bounds[ 3 ][ 1 ] = bounds[ 3 ]; - this->m_Bounds[ 3 ][ 2 ] = step; - - } // fi - this->Modified( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineSource:: -ImageOutlineSource( ) - : Superclass( ) -{ - this->SetNumberOfInputPorts( 0 ); - for( unsigned int j = 0; j < 4; ++j ) - for( unsigned int i = 0; i < 3; ++i ) - this->m_Bounds[ j ][ i ] = double( 0 ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageOutlineSource:: -~ImageOutlineSource( ) -{ -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::ImageOutlineSource:: -RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - // Get output object - vtkInformation* outInfo = outputVector->GetInformationObject( 0 ); - vtkPolyData* output = - vtkPolyData::SafeDownCast( - outInfo->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Create points - vtkPoints* points = vtkPoints::New( ); - points->SetDataType( VTK_FLOAT ); - points->Allocate( 4 ); - - // Create lines - vtkCellArray* verts = vtkCellArray::New( ); - vtkCellArray* lines = vtkCellArray::New( ); - vtkCellArray* faces = vtkCellArray::New( ); - vtkCellArray* strips = vtkCellArray::New( ); - lines->Allocate( lines->EstimateSize( 4, 2 ) ); - - // Assign points - points->InsertPoint( 0, this->m_Bounds[ 0 ] ); - points->InsertPoint( 1, this->m_Bounds[ 1 ] ); - points->InsertPoint( 2, this->m_Bounds[ 2 ] ); - points->InsertPoint( 3, this->m_Bounds[ 3 ] ); - - // Assign cells - vtkIdType cell_pts[ 4 ][ 2 ] = - { - { 0, 1 }, - { 1, 2 }, - { 2, 3 }, - { 3, 0 } - }; - lines->InsertNextCell( 2, cell_pts[ 0 ] ); - lines->InsertNextCell( 2, cell_pts[ 1 ] ); - lines->InsertNextCell( 2, cell_pts[ 2 ] ); - lines->InsertNextCell( 2, cell_pts[ 3 ] ); - - // Assign to output - output->SetPoints( points ); - output->SetVerts( verts ); - output->SetLines( lines ); - output->SetPolys( faces ); - output->SetStrips( strips ); - - // Finish and return - points->Delete( ); - verts->Delete( ); - lines->Delete( ); - faces->Delete( ); - strips->Delete( ); - return( 1 ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageOutlineSource.h b/lib/cpExtensions/Visualization/ImageOutlineSource.h deleted file mode 100644 index 5f3f7d8..0000000 --- a/lib/cpExtensions/Visualization/ImageOutlineSource.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageOutlineSource__h__ -#define __cpExtensions__Visualization__ImageOutlineSource__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT ImageOutlineSource - : public vtkPolyDataAlgorithm - { - public: - typedef ImageOutlineSource Self; - - public: - vtkTypeMacro( ImageOutlineSource, vtkPolyDataAlgorithm ); - - public: - static Self* New( ); - - void SetBounds( int orientation, double step, double* bounds ); - - protected: - ImageOutlineSource( ); - virtual ~ImageOutlineSource( ); - - virtual int RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - ImageOutlineSource( const Self& ); - Self& operator=( const Self& ); - - protected: - double m_Bounds[ 4 ][ 3 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageOutlineSource__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageSliceActors.cxx b/lib/cpExtensions/Visualization/ImageSliceActors.cxx deleted file mode 100644 index 6d67a66..0000000 --- a/lib/cpExtensions/Visualization/ImageSliceActors.cxx +++ /dev/null @@ -1,174 +0,0 @@ -#include -#include -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceActors:: -Self* cpExtensions::Visualization::ImageSliceActors:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -vtkImageData* cpExtensions::Visualization::ImageSliceActors:: -GetImage( ) -{ - if( this->m_WindowLevelImageActor.GetPointer( ) != NULL ) - return( this->m_WindowLevelImageActor->GetImage( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const vtkImageData* cpExtensions::Visualization::ImageSliceActors:: -GetImage( ) const -{ - if( this->m_WindowLevelImageActor.GetPointer( ) != NULL ) - return( this->m_WindowLevelImageActor->GetImage( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -WindowLevelImageActor* cpExtensions::Visualization::ImageSliceActors:: -GetWindowLevelImageActor( ) -{ - return( this->m_WindowLevelImageActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -WindowLevelImageActor* cpExtensions::Visualization::ImageSliceActors:: -GetWindowLevelImageActor( ) const -{ - return( this->m_WindowLevelImageActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -LUTImageActor* cpExtensions::Visualization::ImageSliceActors:: -GetLUTImageActor( ) -{ - return( this->m_LUTImageActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -LUTImageActor* cpExtensions::Visualization::ImageSliceActors:: -GetLUTImageActor( ) const -{ - return( this->m_LUTImageActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -ImageOutlineActor* cpExtensions::Visualization::ImageSliceActors:: -GetImageOutlineActor( ) -{ - return( this->m_ImageOutlineActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -ImageOutlineActor* cpExtensions::Visualization::ImageSliceActors:: -GetImageOutlineActor( ) const -{ - return( this->m_ImageOutlineActor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::ImageSliceActors:: -GetOrientation( ) const -{ - if( this->m_WindowLevelImageActor.GetPointer( ) != NULL ) - return( this->m_WindowLevelImageActor->GetOrientation( ) ); - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageSliceActors:: -SetImage( vtkImageData* image, int orientation ) -{ - this->m_WindowLevelImageActor = - vtkSmartPointer< WindowLevelImageActor >::New( ); - this->m_WindowLevelImageActor->SetImage( image ); - this->m_WindowLevelImageActor->SetOrientation( orientation ); - this->m_ImageOutlineActor = vtkSmartPointer< ImageOutlineActor >::New( ); - this->m_LUTImageActor = NULL; - - // Put an initial slice - int ext[ 6 ]; - image->GetExtent( ext ); - this->SetSliceNumber( - ext[ this->m_WindowLevelImageActor->GetOrientation( ) << 1 ] - ); - - // Update collection - this->RemoveAllItems( ); - this->AddItem( this->m_ImageOutlineActor ); - this->AddItem( this->m_WindowLevelImageActor ); -} - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Visualization::ImageSliceActors:: -AddLUTImage( vtkImageData* image ) -{ - if( this->GetImage( ) != NULL ) - { - if( this->m_LUTImageActor.GetPointer( ) == NULL ) - { - this->m_LUTImageActor = vtkSmartPointer< LUTImageActor >::New( ); - this->m_LUTImageActor->SetOrientation( this->GetOrientation( ) ); - this->AddItem( this->m_LUTImageActor ); - - } // fi - this->m_LUTImageActor->AddImage( image ); - return( this->m_LUTImageActor->GetNumberOfImages( ) ); - } - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::ImageSliceActors:: -GetSliceNumber( ) const -{ - return( this->m_WindowLevelImageActor->GetSliceNumber( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageSliceActors:: -SetSliceNumber( int slice ) -{ - this->m_WindowLevelImageActor->SetSliceNumber( slice ); - if( this->m_LUTImageActor.GetPointer( ) != NULL ) - this->m_LUTImageActor->SetSliceNumber( slice ); - - double bounds[ 6 ]; - this->m_WindowLevelImageActor->GetImage( )->GetBounds( bounds ); - int o = this->m_WindowLevelImageActor->GetOrientation( ); - double p = this->m_WindowLevelImageActor->GetSlicePlane( )->GetOrigin( )[ o ]; - this->m_ImageOutlineActor->SetBounds( o, p, bounds ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceActors:: -ImageSliceActors( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceActors:: -~ImageSliceActors( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageSliceActors.h b/lib/cpExtensions/Visualization/ImageSliceActors.h deleted file mode 100644 index 25f81f6..0000000 --- a/lib/cpExtensions/Visualization/ImageSliceActors.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageSliceActors__h__ -#define __cpExtensions__Visualization__ImageSliceActors__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkImageData; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class ImageOutlineActor; - class LUTImageActor; - class WindowLevelImageActor; - - /** - */ - class cpExtensions_EXPORT ImageSliceActors - : public vtkPropCollection - { - public: - typedef ImageSliceActors Self; - - public: - vtkTypeMacro( ImageSliceActors, vtkPropCollection ); - - public: - static Self* New( ); - - vtkImageData* GetImage( ); - const vtkImageData* GetImage( ) const; - - WindowLevelImageActor* GetWindowLevelImageActor( ); - const WindowLevelImageActor* GetWindowLevelImageActor( ) const; - - LUTImageActor* GetLUTImageActor( ); - const LUTImageActor* GetLUTImageActor( ) const; - - ImageOutlineActor* GetImageOutlineActor( ); - const ImageOutlineActor* GetImageOutlineActor( ) const; - - int GetOrientation( ) const; - - int GetSliceNumber( ) const; - virtual void SetImage( vtkImageData* image, int orientation ); - virtual unsigned int AddLUTImage( vtkImageData* image ); - virtual void SetSliceNumber( int slice ); - - protected: - ImageSliceActors( ); - virtual ~ImageSliceActors( ); - - private: - // Purposely not implemented - ImageSliceActors( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< ImageOutlineActor > m_ImageOutlineActor; - vtkSmartPointer< LUTImageActor > m_LUTImageActor; - vtkSmartPointer< WindowLevelImageActor > m_WindowLevelImageActor; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageSliceActors__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageSliceMapper.cxx b/lib/cpExtensions/Visualization/ImageSliceMapper.cxx deleted file mode 100644 index 5bf36fc..0000000 --- a/lib/cpExtensions/Visualization/ImageSliceMapper.cxx +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceMapper:: -Self* cpExtensions::Visualization::ImageSliceMapper:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceMapper:: -ImageSliceMapper( ) - : Superclass( ) -{ -#ifdef cpPlugins_OpenGL_BackEnd_OpenGL2 - // Complete polydatas to avoid bizarre rendering errors (multi-thread) - vtkActor* a[ 3 ]; - a[ 0 ] = this->PolyDataActor; - a[ 1 ] = this->BackingPolyDataActor; - a[ 2 ] = this->BackgroundPolyDataActor; - for( unsigned int i = 0; i < 3; ++i ) - { - if( a[ i ] != NULL ) - { - auto m = - dynamic_cast< vtkOpenGLPolyDataMapper* >( a[ i ]->GetMapper( ) ); - if( m != NULL ) - { - auto p = m->GetInput( ); - if( p != NULL ) - { - vtkNew< vtkCellArray > verts; - vtkNew< vtkCellArray > lines; - vtkNew< vtkCellArray > strips; - p->SetVerts( verts.Get( ) ); - p->SetLines( lines.Get( ) ); - p->SetStrips( strips.Get( ) ); - p->Modified( ); - m->Modified( ); - a[ i ]->Modified( ); - - } // fi - - } // fi - - } // fi - - } // rof -#endif // cpPlugins_OpenGL_BackEnd_OpenGL2 -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageSliceMapper:: -~ImageSliceMapper( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageSliceMapper.h b/lib/cpExtensions/Visualization/ImageSliceMapper.h deleted file mode 100644 index 10e8404..0000000 --- a/lib/cpExtensions/Visualization/ImageSliceMapper.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageSliceMapper__h__ -#define __cpExtensions__Visualization__ImageSliceMapper__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT ImageSliceMapper - : public vtkOpenGLImageSliceMapper - { - public: - typedef ImageSliceMapper Self; - - public: - vtkTypeMacro( ImageSliceMapper, vtkOpenGLImageSliceMapper ); - - public: - static Self* New( ); - - protected: - ImageSliceMapper( ); - virtual ~ImageSliceMapper( ); - - private: - // Purposely not implemented - ImageSliceMapper( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageSliceMapper__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageViewerActors.cxx b/lib/cpExtensions/Visualization/ImageViewerActors.cxx deleted file mode 100644 index 65114c8..0000000 --- a/lib/cpExtensions/Visualization/ImageViewerActors.cxx +++ /dev/null @@ -1,169 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageViewerActors:: -Self* cpExtensions::Visualization::ImageViewerActors:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -SetImage( vtkImageData* image, int orientation ) -{ - this->Superclass::SetImage( image, orientation ); - - this->m_Cursor = vtkSmartPointer< CursorActors >::New( ); - this->m_Cursor->SetImageBounds( image->GetBounds( ) ); - this->m_Cursor->SetImageOrientation( orientation ); - this->m_Cursor->GetProperty( 0 )->SetColor( 1, 1, 0 ); - this->m_Cursor->GetProperty( 1 )->SetColor( 1, 1, 0 ); - this->m_Cursor->GetProperty( 0 )->SetLineWidth( 1.5 ); - this->m_Cursor->GetProperty( 1 )->SetLineWidth( 1.5 ); - this->m_Cursor->VisibilityOff( ); - - this->m_SuperCursor = vtkSmartPointer< CursorActors >::New( ); - this->m_SuperCursor->SetImageBounds( image->GetBounds( ) ); - this->m_SuperCursor->SetImageOrientation( orientation ); - this->m_SuperCursor->GetProperty( 0 )->SetColor( 0, 1, 1 ); - this->m_SuperCursor->GetProperty( 1 )->SetColor( 0, 1, 1 ); - this->m_SuperCursor->GetProperty( 0 )->SetLineWidth( 1.5 ); - this->m_SuperCursor->GetProperty( 1 )->SetLineWidth( 1.5 ); - this->m_SuperCursor->VisibilityOff( ); - - // Prepare text - this->m_TextBuffer[ 0 ] = '\0'; - this->m_Text = vtkSmartPointer< vtkTextActor >::New( ); - this->m_Text->SetTextScaleModeToNone( ); - auto textprop = this->m_Text->GetTextProperty( ); - textprop->SetColor( 1, 1, 0 ); - textprop->SetFontFamilyToCourier( ); - textprop->SetFontSize( 18 ); - textprop->BoldOff( ); - textprop->ItalicOff( ); - textprop->ShadowOff( ); - textprop->SetJustificationToLeft( ); - textprop->SetVerticalJustificationToBottom( ); - auto coord = this->m_Text->GetPositionCoordinate( ); - coord->SetCoordinateSystemToNormalizedViewport( ); - coord->SetValue( 0.01, 0.05 ); - this->m_Text->VisibilityOff( ); - - // Update actor list - this->m_Cursor->InitTraversal( ); - while( vtkProp* prop = this->m_Cursor->GetNextProp( ) ) - this->AddItem( prop ); - this->m_SuperCursor->InitTraversal( ); - while( vtkProp* prop = this->m_SuperCursor->GetNextProp( ) ) - this->AddItem( prop ); - this->AddItem( this->m_Text ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -SetCursor( double* pos, bool neg ) -{ - this->m_Cursor->SetCursor( pos, neg ); - this->_ShowText( pos ); - this->m_Cursor->VisibilityOn( ); - this->m_Text->VisibilityOn( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -SetSuperCursor( double* pos, bool neg ) -{ - this->SetCursor( pos, neg ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -HideViewerActors( ) -{ - this->m_Cursor->VisibilityOff( ); - this->m_Text->VisibilityOff( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageViewerActors:: -ImageViewerActors( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::ImageViewerActors:: -~ImageViewerActors( ) -{ -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -_CorrectPosition( double* pos, int* ijk ) -{ - auto image = this->GetImage( ); - if( image == NULL ) - return; - - // Approximate image index - double pcoords[ 3 ]; - image->ComputeStructuredCoordinates( pos, ijk, pcoords ); - - // Manually correct index - int ext[ 6 ]; - image->GetExtent( ext ); - for( int i = 0; i < 3; ++i ) - { - if( ijk[ i ] < ext[ i << 1 ] ) - ijk[ i ] = ext[ i << 1 ]; - if( ext[ ( i << 1 ) + 1 ] < ijk[ i ] ) - ijk[ i ] = ext[ ( i << 1 ) + 1 ]; - - } // rof - - // Get real coordinates - int o = this->GetOrientation( ); - ijk[ o ] = this->GetSliceNumber( ); - image->GetPoint( image->ComputePointId( ijk ), pos ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::ImageViewerActors:: -_ShowText( double* pos ) -{ - auto image = this->GetImage( ); - if( image == NULL ) - return; - - int ijk[ 3 ]; - this->_CorrectPosition( pos, ijk ); - int o = this->GetOrientation( ); - - std::stringstream buffer; - buffer << "Axis: " << char( 'X' + char( o ) ) << std::endl; - int nScl = image->GetNumberOfScalarComponents( ); - buffer - << "Pixel: [" << ijk[ 0 ] - << "," << ijk[ 1 ] - << "," << ijk[ 2 ] << "]=(" - << image->GetScalarComponentAsFloat( ijk[ 0 ], ijk[ 1 ], ijk[ 2 ], 0 ); - for( int n = 1; n < nScl; ++n ) - buffer - << " : " - << image->GetScalarComponentAsFloat( ijk[ 0 ], ijk[ 1 ], ijk[ 2 ], n ); - buffer << ")"; - cpExtensions_SPRINTF( this->m_TextBuffer, 1024, buffer.str( ).c_str( ) ); - this->m_Text->SetInput( this->m_TextBuffer ); - this->m_Text->VisibilityOn( ); - this->m_Text->Modified( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/ImageViewerActors.h b/lib/cpExtensions/Visualization/ImageViewerActors.h deleted file mode 100644 index b12e9c8..0000000 --- a/lib/cpExtensions/Visualization/ImageViewerActors.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef __cpExtensions__Visualization__ImageViewerActors__h__ -#define __cpExtensions__Visualization__ImageViewerActors__h__ - -#include -#include - -// ------------------------------------------------------------------------- -class vtkTextActor; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class CursorActors; - - /** - */ - class cpExtensions_EXPORT ImageViewerActors - : public ImageSliceActors - { - public: - typedef ImageViewerActors Self; - - public: - vtkTypeMacro( ImageViewerActors, ImageSliceActors ); - - public: - static Self* New( ); - - virtual void SetImage( - vtkImageData* image, int orientation - ) cpExtensions_OVERRIDE; - - void SetCursor( double* pos, bool neg ); - void SetSuperCursor( double* pos, bool neg ); - void HideViewerActors( ); - - protected: - ImageViewerActors( ); - virtual ~ImageViewerActors( ); - - void _CorrectPosition( double* pos, int* ijk ); - void _ShowText( double* pos ); - - private: - // Purposely not implemented - ImageViewerActors( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< CursorActors > m_Cursor; - vtkSmartPointer< CursorActors > m_SuperCursor; - vtkSmartPointer< vtkTextActor > m_Text; - char m_TextBuffer[ 1024 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__ImageViewerActors__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/LUTImageActor.cxx b/lib/cpExtensions/Visualization/LUTImageActor.cxx deleted file mode 100644 index d377215..0000000 --- a/lib/cpExtensions/Visualization/LUTImageActor.cxx +++ /dev/null @@ -1,160 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LUTImageActor:: -Self* cpExtensions::Visualization::LUTImageActor:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Visualization::LUTImageActor:: -GetNumberOfImages( ) const -{ - return( this->m_Images.size( ) ); -} - -// ------------------------------------------------------------------------- -vtkImageData* cpExtensions::Visualization::LUTImageActor:: -GetImage( unsigned int id ) -{ - if( id < this->m_Images.size( ) ) - return( this->m_Images[ id ] ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const vtkImageData* cpExtensions::Visualization::LUTImageActor:: -GetImage( unsigned int id ) const -{ - if( id < this->m_Images.size( ) ) - return( this->m_Images[ id ] ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Visualization::LUTImageActor:: -GetImageId( vtkImageData* image ) const -{ - unsigned int i = 0; - bool f = false; - while( i < this->m_Images.size( ) && !f ) - { - if( this->m_Images[ i ].GetPointer( ) == image ) - f = true; - else - i++; - - } // elihw - return( i ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LUTImageActor:: -GetLUTColor( - unsigned int id, double& r, double& g, double& b, double& a - ) const -{ - double rgba[ 4 ]; - this->m_LUT->GetTableValue( id, rgba ); - r = rgba[ 0 ]; - g = rgba[ 1 ]; - b = rgba[ 2 ]; - a = rgba[ 3 ]; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LUTImageActor:: -GetLUTColor( - vtkImageData* image, double& r, double& g, double& b, double& a - ) const -{ - this->GetLUTColor( this->GetImageId( image ), r, g, b, a ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LUTImageActor:: -SetLUTColor( unsigned int id, double r, double g, double b, double a ) -{ - if( id >= ( unsigned int )( this->m_LUT->GetNumberOfTableValues( ) ) ) - this->m_LUT->SetNumberOfTableValues( id + 1 ); - this->m_LUT->SetTableValue( id, r, g, b, a ); - this->m_LUT->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LUTImageActor:: -SetLUTColor( vtkImageData* image, double r, double g, double b, double a ) -{ - this->SetLUTColor( this->GetImageId( image ), r, g, b, a ); -} - -// TODO: !!!!! -#include - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Visualization::LUTImageActor:: -AddImage( vtkImageData* image, double r, double g, double b, double a ) -{ - static vtkSmartPointer< vtkImageCast > cast; - cast = vtkSmartPointer< vtkImageCast >::New( ); - - if( image != NULL ) - { - cast->SetOutputScalarTypeToUnsignedChar( ); - cast->SetInputData( image ); - cast->Update( ); - - this->m_Images.push_back( image ); - this->SetLUTColor( this->m_Images.size( ), r, g, b, a ); - this->m_Blender->AddInputData( cast->GetOutput( ) ); - this->m_Blender->Update( ); - - if( this->m_Images.size( ) == 1 ) - { - this->m_ImageMap-> - SetInputConnection( this->m_Blender->GetOutputPort( ) ); - this->m_Mapper-> - SetInputConnection( this->m_ImageMap->GetOutputPort( ) ); - - } // fi - this->Modified( ); - - this->GetProperty( )->SetInterpolationTypeToNearest( ); - - } // fi - return( this->m_Images.size( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LUTImageActor:: -LUTImageActor( ) - : Superclass( ) -{ - this->m_LUT = vtkSmartPointer< vtkLookupTable >::New( ); - this->m_LUT->SetNumberOfTableValues( 1 ); - this->m_LUT->SetNanColor( 0, 0, 0, 0 ); - this->m_LUT->SetTableValue( 0, 0, 0, 0, 0 ); - - this->m_Blender = vtkSmartPointer< _TImageBlender >::New( ); - this->m_ImageMap = vtkSmartPointer< vtkImageMapToColors >::New( ); - this->m_ImageMap->SetLookupTable( this->m_LUT ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LUTImageActor:: -~LUTImageActor( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/LUTImageActor.h b/lib/cpExtensions/Visualization/LUTImageActor.h deleted file mode 100644 index 851afa5..0000000 --- a/lib/cpExtensions/Visualization/LUTImageActor.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef __cpExtensions__Visualization__LUTImageActor__h__ -#define __cpExtensions__Visualization__LUTImageActor__h__ - -#include -#include - -// ------------------------------------------------------------------------- -class vtkImageMapToColors; -class vtkLookupTable; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Algorithms { class ImageBlender; } - - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT LUTImageActor - : public ImageActor - { - public: - typedef LUTImageActor Self; - - protected: - typedef cpExtensions::Algorithms::ImageBlender _TImageBlender; - - public: - vtkTypeMacro( LUTImageActor, ImageActor ); - - public: - static Self* New( ); - - unsigned int GetNumberOfImages( ) const; - vtkImageData* GetImage( unsigned int id ); - const vtkImageData* GetImage( unsigned int id ) const; - unsigned int GetImageId( vtkImageData* image ) const; - void GetLUTColor( - unsigned int id, double& r, double& g, double& b, double& a - ) const; - void GetLUTColor( - vtkImageData* image, double& r, double& g, double& b, double& a - ) const; - void SetLUTColor( - unsigned int id, double r, double g, double b, double a - ); - void SetLUTColor( - vtkImageData* image, double r, double g, double b, double a - ); - unsigned int AddImage( - vtkImageData* image, - double r = 1, double g = 0, double b = 0, double a = 1 - ); - - protected: - LUTImageActor( ); - virtual ~LUTImageActor( ); - - private: - // Purposely not implemented - LUTImageActor( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< vtkLookupTable > m_LUT; - vtkSmartPointer< _TImageBlender > m_Blender; - vtkSmartPointer< vtkImageMapToColors > m_ImageMap; - std::vector< vtkSmartPointer< vtkImageData > > m_Images; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__LUTImageActor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/LineSource.cxx b/lib/cpExtensions/Visualization/LineSource.cxx deleted file mode 100644 index 6280cba..0000000 --- a/lib/cpExtensions/Visualization/LineSource.cxx +++ /dev/null @@ -1,119 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LineSource:: -Self* cpExtensions::Visualization::LineSource:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LineSource:: -SetPoint1( float pnt[ 3 ] ) -{ - double p[ 3 ]; - p[ 0 ] = pnt[ 0 ]; - p[ 1 ] = pnt[ 1 ]; - p[ 2 ] = pnt[ 2 ]; - this->SetPoint1( p ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::LineSource:: -SetPoint2( float pnt[ 3 ] ) -{ - double p[ 3 ]; - p[ 0 ] = pnt[ 0 ]; - p[ 1 ] = pnt[ 1 ]; - p[ 2 ] = pnt[ 2 ]; - this->SetPoint2( p ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LineSource:: -LineSource( ) - : Superclass( ) -{ - this->SetNumberOfInputPorts( 0 ); - this->Point1[ 0 ] = -double( 0.5 ); - this->Point1[ 1 ] = double( 0.0 ); - this->Point1[ 2 ] = double( 0.0 ); - this->Point2[ 0 ] = double( 0.5 ); - this->Point2[ 1 ] = double( 0.0 ); - this->Point2[ 2 ] = double( 0.0 ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::LineSource:: -~LineSource( ) -{ -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::LineSource:: -RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - // Get output object - vtkInformation* outInfo = outputVector->GetInformationObject( 0 ); - vtkPolyData* output = - vtkPolyData::SafeDownCast( - outInfo->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Create points - vtkPoints* points = vtkPoints::New( ); - points->SetDataType( VTK_FLOAT ); - points->Allocate( 2 ); - - // Create cells - vtkCellArray* verts = vtkCellArray::New( ); - vtkCellArray* lines = vtkCellArray::New( ); - vtkCellArray* faces = vtkCellArray::New( ); - vtkCellArray* strips = vtkCellArray::New( ); - lines->Allocate( lines->EstimateSize( 2, 2 ) ); - - // Assign points - points->InsertPoint( 0, this->Point1 ); - points->InsertPoint( 1, this->Point2 ); - - // Assign cells - vtkIdType cell_pts[ 2 ] = { 0, 1 }; - lines->InsertNextCell( 2, cell_pts ); - - // Assign to output - output->SetPoints( points ); - output->SetVerts( verts ); - output->SetLines( lines ); - output->SetPolys( faces ); - output->SetStrips( strips ); - - // Finish and return - points->Delete( ); - verts->Delete( ); - lines->Delete( ); - faces->Delete( ); - strips->Delete( ); - return( 1 ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::LineSource:: -RequestInformation( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - vtkInformation* outInfo = outputVector->GetInformationObject( 0 ); - outInfo->Set( CAN_HANDLE_PIECE_REQUEST(), 1 ); - return( 1 ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/LineSource.h b/lib/cpExtensions/Visualization/LineSource.h deleted file mode 100644 index c675257..0000000 --- a/lib/cpExtensions/Visualization/LineSource.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef __cpExtensions__Visualization__LineSource__h__ -#define __cpExtensions__Visualization__LineSource__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT LineSource - : public vtkPolyDataAlgorithm - { - public: - typedef LineSource Self; - - public: - vtkTypeMacro( LineSource, vtkPolyDataAlgorithm ); - - vtkSetVector3Macro( Point1, double ); - vtkSetVector3Macro( Point2, double ); - vtkGetVectorMacro( Point1, double, 3 ); - vtkGetVectorMacro( Point2, double, 3 ); - - public: - static Self* New( ); - - void SetPoint1( float pnt[ 3 ] ); - void SetPoint2( float pnt[ 3 ] ); - - protected: - LineSource( ); - virtual ~LineSource( ); - - virtual int RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) cpExtensions_OVERRIDE; - - virtual int RequestInformation( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - LineSource( const Self& ); - Self& operator=( const Self& ); - - protected: - double Point1[ 3 ]; - double Point2[ 3 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__LineSource__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/MPR3DActors.cxx b/lib/cpExtensions/Visualization/MPR3DActors.cxx deleted file mode 100644 index b3f4700..0000000 --- a/lib/cpExtensions/Visualization/MPR3DActors.cxx +++ /dev/null @@ -1,186 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::MPR3DActors:: -Self* cpExtensions::Visualization::MPR3DActors:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -vtkImageData* cpExtensions::Visualization::MPR3DActors:: -GetImage( ) -{ - return( this->m_Slices[ 0 ]->GetImage( ) ); -} - -// ------------------------------------------------------------------------- -const vtkImageData* cpExtensions::Visualization::MPR3DActors:: -GetImage( ) const -{ - return( this->m_Slices[ 0 ]->GetImage( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -WindowLevelImageActor* cpExtensions::Visualization::MPR3DActors:: -GetWindowLevelImageActor( int o ) -{ - return( this->m_Slices[ o % 3 ]->GetWindowLevelImageActor( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -WindowLevelImageActor* cpExtensions::Visualization::MPR3DActors:: -GetWindowLevelImageActor( int o ) const -{ - return( this->m_Slices[ o % 3 ]->GetWindowLevelImageActor( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -LUTImageActor* cpExtensions::Visualization::MPR3DActors:: -GetLUTImageActor( int o ) -{ - return( this->m_Slices[ o % 3 ]->GetLUTImageActor( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -LUTImageActor* cpExtensions::Visualization::MPR3DActors:: -GetLUTImageActor( int o ) const -{ - return( this->m_Slices[ o % 3 ]->GetLUTImageActor( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization:: -ImageOutlineActor* cpExtensions::Visualization::MPR3DActors:: -GetImageOutlineActor( int o ) -{ - return( this->m_Slices[ o % 3 ]->GetImageOutlineActor( ) ); -} - -// ------------------------------------------------------------------------- -const cpExtensions::Visualization:: -ImageOutlineActor* cpExtensions::Visualization::MPR3DActors:: -GetImageOutlineActor( int o ) const -{ - return( this->m_Slices[ o % 3 ]->GetImageOutlineActor( ) ); -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::MPR3DActors:: -GetSliceNumber( int o ) const -{ - return( this->m_Slices[ o % 3 ]->GetSliceNumber( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetImage( vtkImageData* image ) -{ - this->RemoveAllItems( ); - for( int i = 0; i < 3; ++i ) - { - this->m_Slices[ i ]->SetImage( image, i ); - this->m_Slices[ i ]->InitTraversal( ); - while( vtkProp* p = this->m_Slices[ i ]->GetNextProp( ) ) - this->AddItem( p ); - - } // rof -} - -// ------------------------------------------------------------------------- -unsigned int cpExtensions::Visualization::MPR3DActors:: -AddLUTImage( vtkImageData* image ) -{ - unsigned int res = 0; - for( int i = 0; i < 3; ++i ) - { - res = this->m_Slices[ i ]->AddLUTImage( image ); - this->AddItem( this->m_Slices[ i ]->GetLUTImageActor( ) ); - - } // rof - return( res ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetSliceNumber( int o, int s ) -{ - this->m_Slices[ o % 3 ]->SetSliceNumber( s ); -} - -// ------------------------------------------------------------------------- -vtkActor* cpExtensions::Visualization::MPR3DActors:: -AddMesh( vtkPolyData* mesh ) -{ - TMeshActor actor; - actor.SetMesh( mesh ); - this->m_Meshes[ mesh ] = actor; - this->AddItem( actor.GetActor( ) ); - return( actor.GetActor( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetScalarRange( double r[ 2 ] ) -{ - this->m_Slices[ 0 ]->GetWindowLevelImageActor( )->SetRange( r ); - this->m_Slices[ 1 ]->GetWindowLevelImageActor( )->SetRange( r ); - this->m_Slices[ 2 ]->GetWindowLevelImageActor( )->SetRange( r ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetWindowLevel( double wl[ 2 ] ) -{ - this->m_Slices[ 0 ]->GetWindowLevelImageActor( )->SetWindowLevel( wl ); - this->m_Slices[ 1 ]->GetWindowLevelImageActor( )->SetWindowLevel( wl ); - this->m_Slices[ 2 ]->GetWindowLevelImageActor( )->SetWindowLevel( wl ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetImageOpacity( double o ) -{ - this->m_Slices[ 0 ]->GetWindowLevelImageActor( )-> - GetProperty( )->SetOpacity( o ); - this->m_Slices[ 1 ]->GetWindowLevelImageActor( )-> - GetProperty( )->SetOpacity( o ); - this->m_Slices[ 2 ]->GetWindowLevelImageActor( )-> - GetProperty( )->SetOpacity( o ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MPR3DActors:: -SetImageInterpolation( unsigned char i ) -{ - // TODO -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::MPR3DActors:: -MPR3DActors( ) - : Superclass( ) -{ - this->m_Slices[ 0 ] = vtkSmartPointer< ImageSliceActors >::New( ); - this->m_Slices[ 1 ] = vtkSmartPointer< ImageSliceActors >::New( ); - this->m_Slices[ 2 ] = vtkSmartPointer< ImageSliceActors >::New( ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::MPR3DActors:: -~MPR3DActors( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/MPR3DActors.h b/lib/cpExtensions/Visualization/MPR3DActors.h deleted file mode 100644 index 07c41ba..0000000 --- a/lib/cpExtensions/Visualization/MPR3DActors.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef __cpExtensions__Visualization__MPR3DActors__h__ -#define __cpExtensions__Visualization__MPR3DActors__h__ - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkActor; -class vtkImageData; -class vtkPolyData; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - class ImageOutlineActor; - class ImageSliceActors; - class LUTImageActor; - class WindowLevelImageActor; - - /** - */ - class cpExtensions_EXPORT MPR3DActors - : public vtkPropCollection - { - public: - typedef MPR3DActors Self; - - typedef cpExtensions::Visualization::MeshActor TMeshActor; - - public: - vtkTypeMacro( MPR3DActors, vtkPropCollection ); - - public: - static Self* New( ); - - vtkImageData* GetImage( ); - const vtkImageData* GetImage( ) const; - - WindowLevelImageActor* GetWindowLevelImageActor( int o ); - const WindowLevelImageActor* GetWindowLevelImageActor( int o ) const; - - LUTImageActor* GetLUTImageActor( int o ); - const LUTImageActor* GetLUTImageActor( int o ) const; - - ImageOutlineActor* GetImageOutlineActor( int o ); - const ImageOutlineActor* GetImageOutlineActor( int o ) const; - - int GetSliceNumber( int o ) const; - virtual void SetImage( vtkImageData* image ); - virtual unsigned int AddLUTImage( vtkImageData* image ); - virtual void SetSliceNumber( int o, int s ); - - virtual vtkActor* AddMesh( vtkPolyData* mesh ); - - void SetScalarRange( double r[ 2 ] ); - void SetWindowLevel( double wl[ 2 ] ); - void SetImageOpacity( double o ); - void SetImageInterpolation( unsigned char i ); - - protected: - MPR3DActors( ); - virtual ~MPR3DActors( ); - - private: - // Purposely not implemented - MPR3DActors( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< ImageSliceActors > m_Slices[ 3 ]; - std::map< vtkSmartPointer< vtkPolyData >, TMeshActor > m_Meshes; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__MPR3DActors__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/MeshActor.cxx b/lib/cpExtensions/Visualization/MeshActor.cxx deleted file mode 100644 index ca6f1f9..0000000 --- a/lib/cpExtensions/Visualization/MeshActor.cxx +++ /dev/null @@ -1,56 +0,0 @@ -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::MeshActor:: -MeshActor( ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::MeshActor:: -~MeshActor( ) -{ -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::MeshActor:: -SetMesh( vtkPolyData* mesh ) -{ - static unsigned long MAX = std::numeric_limits< unsigned short >::max( ); - - this->m_Mesh = mesh; - this->m_Mapper = vtkSmartPointer< vtkPolyDataMapper >::New( ); - unsigned long c = mesh->GetNumberOfPolys( ) + mesh->GetNumberOfStrips( ); - if( c >= MAX ) - { - vtkSmartPointer< vtkQuadricLODActor > q = - vtkSmartPointer< vtkQuadricLODActor >::New( ); - q->DeferLODConstructionOff( ); - this->m_Actor = q.GetPointer( ); - } - else - this->m_Actor = vtkSmartPointer< vtkActor >::New( ); - this->m_Mapper->SetInputData( this->m_Mesh ); - this->m_Actor->SetMapper( this->m_Mapper ); -} - -// ------------------------------------------------------------------------- -vtkActor* cpExtensions::Visualization::MeshActor:: -GetActor( ) -{ - return( this->m_Actor.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -const vtkActor* cpExtensions::Visualization::MeshActor:: -GetActor( ) const -{ - return( this->m_Actor.GetPointer( ) ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/MeshActor.h b/lib/cpExtensions/Visualization/MeshActor.h deleted file mode 100644 index c26b8d7..0000000 --- a/lib/cpExtensions/Visualization/MeshActor.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef __cpExtensions__Visualization__MeshActor__h__ -#define __cpExtensions__Visualization__MeshActor__h__ - -#include -#include - -// ------------------------------------------------------------------------- -class vtkActor; -class vtkPolyData; -class vtkPolyDataMapper; - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT MeshActor - { - public: - typedef MeshActor Self; - - public: - MeshActor( ); - virtual ~MeshActor( ); - - void SetMesh( vtkPolyData* mesh ); - - vtkActor* GetActor( ); - const vtkActor* GetActor( ) const; - - protected: - vtkSmartPointer< vtkPolyData > m_Mesh; - vtkSmartPointer< vtkPolyDataMapper > m_Mapper; - vtkSmartPointer< vtkActor > m_Actor; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__MeshActor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/OutlineSource.cxx b/lib/cpExtensions/Visualization/OutlineSource.cxx deleted file mode 100644 index a00a221..0000000 --- a/lib/cpExtensions/Visualization/OutlineSource.cxx +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::OutlineSource:: -Self* cpExtensions::Visualization::OutlineSource:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::OutlineSource:: -OutlineSource( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::OutlineSource:: -~OutlineSource( ) -{ -} - -// ------------------------------------------------------------------------- -int cpExtensions::Visualization::OutlineSource:: -RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) -{ - int r = this->Superclass::RequestData( request, inputVector, outputVector ); - - // Complete polydatas to avoid bizarre rendering errors (multi-thread) - vtkInformation *outInfo = outputVector->GetInformationObject( 0 ); - vtkPolyData *output = vtkPolyData::SafeDownCast( - outInfo->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - output->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - output->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - if( this->GenerateFaces != 1 ) - output->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - return( r ); -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/OutlineSource.h b/lib/cpExtensions/Visualization/OutlineSource.h deleted file mode 100644 index 295a5b5..0000000 --- a/lib/cpExtensions/Visualization/OutlineSource.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef __cpExtensions__Visualization__OutlineSource__h__ -#define __cpExtensions__Visualization__OutlineSource__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT OutlineSource - : public vtkOutlineSource - { - public: - typedef OutlineSource Self; - - public: - vtkTypeMacro( OutlineSource, vtkOutlineSource ); - - public: - static Self* New( ); - - protected: - OutlineSource( ); - virtual ~OutlineSource( ); - - virtual int RequestData( - vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector - ) cpExtensions_OVERRIDE; - - private: - // Purposely not implemented - OutlineSource( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__OutlineSource__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.cxx b/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.cxx deleted file mode 100644 index c97fac7..0000000 --- a/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.cxx +++ /dev/null @@ -1,131 +0,0 @@ -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -typename -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -Self* -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -const typename -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -TPolyLine* -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -GetInput( ) const -{ - return( this->m_PolyLine ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -void -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -SetInput( const TPolyLine* pl ) -{ - if( this->m_PolyLine != pl ) - { - this->m_PolyLine = pl; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -PolyLineParametricPathToPolyData( ) - : vtkPolyDataAlgorithm( ), - m_PolyLine( NULL ) -{ - this->SetNumberOfInputPorts( 0 ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -~PolyLineParametricPathToPolyData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -int -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - static const unsigned int dim = _TPolyLine::PathDimension; - - if( this->m_PolyLine == NULL ) - return( 0 ); - - // Get output - vtkInformation* info = output->GetInformationObject( 0 ); - vtkPolyData* out = vtkPolyData::SafeDownCast( - info->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Prepare data - out->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - out->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - vtkPoints* points = out->GetPoints( ); - vtkCellArray* lines = out->GetLines( ); - - // Get data - for( unsigned long i = 0; i < this->m_PolyLine->GetSize( ); ++i ) - { - typename _TPolyLine::TPoint pnt = this->m_PolyLine->GetPoint( i ); - if( dim == 1 ) points->InsertNextPoint( pnt[ 0 ], 0, 0 ); - else if( dim == 2 ) points->InsertNextPoint( pnt[ 0 ], pnt[ 1 ], 0 ); - else points->InsertNextPoint( pnt[ 0 ], pnt[ 1 ], pnt[ 2 ] ); - if( i > 0 ) - { - lines->InsertNextCell( 2 ); - lines->InsertCellPoint( i - 1 ); - lines->InsertCellPoint( i ); - - } // fi - - } // rof - return( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLine > -int -cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPolyLine >:: -RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - return( 1 ); -} - -// ------------------------------------------------------------------------- -#include - -template class cpExtensions::Visualization::PolyLineParametricPathToPolyData< cpExtensions::DataStructures::PolyLineParametricPath< 1 > >; -template class cpExtensions::Visualization::PolyLineParametricPathToPolyData< cpExtensions::DataStructures::PolyLineParametricPath< 2 > >; -template class cpExtensions::Visualization::PolyLineParametricPathToPolyData< cpExtensions::DataStructures::PolyLineParametricPath< 3 > >; -template class cpExtensions::Visualization::PolyLineParametricPathToPolyData< cpExtensions::DataStructures::PolyLineParametricPath< 4 > >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.h b/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.h deleted file mode 100644 index 8e73108..0000000 --- a/lib/cpExtensions/Visualization/PolyLineParametricPathToPolyData.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef __cpExtensions__Visualization__PolyLineParametricPathToPolyData__h__ -#define __cpExtensions__Visualization__PolyLineParametricPathToPolyData__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - template< class _TPolyLine > - class cpExtensions_EXPORT PolyLineParametricPathToPolyData - : public vtkPolyDataAlgorithm - { - public: - typedef PolyLineParametricPathToPolyData Self; - typedef _TPolyLine TPolyLine; - - public: - vtkTypeMacro( PolyLineParametricPathToPolyData, vtkPolyDataAlgorithm ); - - public: - static Self* New( ); - - const TPolyLine* GetInput( ) const; - void SetInput( const TPolyLine* pl ); - - protected: - PolyLineParametricPathToPolyData( ); - virtual ~PolyLineParametricPathToPolyData( ); - - int RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - int RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - - private: - // Purposely not implemented - PolyLineParametricPathToPolyData( const Self& ); - void operator=( const Self& ); - - protected: - const TPolyLine* m_PolyLine; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__PolyLineParametricPathToPolyData__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.cxx b/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.cxx deleted file mode 100644 index 697807f..0000000 --- a/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.cxx +++ /dev/null @@ -1,119 +0,0 @@ -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TCurve > -typename cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -Self* cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -const typename cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -TCurve* cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -GetInput( ) const -{ - return( this->m_Curve ); -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -void -cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -SetInput( const TCurve* c ) -{ - if( this->m_Curve != c ) - { - this->m_Curve = c; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -Simple3DCurveToPolyData( ) - : vtkPolyDataAlgorithm( ), - m_Curve( NULL ) -{ - this->SetNumberOfInputPorts( 0 ); -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -~Simple3DCurveToPolyData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -int cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - if( this->m_Curve == NULL ) - return( 0 ); - - // Get output - vtkInformation* info = output->GetInformationObject( 0 ); - vtkPolyData* out = vtkPolyData::SafeDownCast( - info->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Prepare data - out->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - out->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - vtkPoints* points = out->GetPoints( ); - vtkCellArray* lines = out->GetLines( ); - - // Get data - for( unsigned long i = 0; i < this->m_Curve->GetNumberOfPoints( ); ++i ) - { - typename _TCurve::TPoint pnt = this->m_Curve->GetPoint( i ); - points->InsertNextPoint( pnt[ 0 ], pnt[ 1 ], pnt[ 2 ] ); - if( i > 0 ) - { - lines->InsertNextCell( 2 ); - lines->InsertCellPoint( i - 1 ); - lines->InsertCellPoint( i ); - - } // fi - - } // rof - return( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -int cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve >:: -RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - return( 1 ); -} - -// ------------------------------------------------------------------------- -#include - -template class cpExtensions::Visualization::Simple3DCurveToPolyData< cpExtensions::DataStructures::Simple3DCurve< float > >; -template class cpExtensions::Visualization::Simple3DCurveToPolyData< cpExtensions::DataStructures::Simple3DCurve< double > >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.h b/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.h deleted file mode 100644 index 7407cea..0000000 --- a/lib/cpExtensions/Visualization/Simple3DCurveToPolyData.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef __cpExtensions__Visualization__Simple3DCurveToPolyData__h__ -#define __cpExtensions__Visualization__Simple3DCurveToPolyData__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - template< class _TCurve > - class cpExtensions_EXPORT Simple3DCurveToPolyData - : public vtkPolyDataAlgorithm - { - public: - typedef Simple3DCurveToPolyData Self; - typedef _TCurve TCurve; - - public: - vtkTypeMacro( Simple3DCurveToPolyData, vtkPolyDataAlgorithm ); - - public: - static Self* New( ); - - const TCurve* GetInput( ) const; - void SetInput( const TCurve* c ); - - protected: - Simple3DCurveToPolyData( ); - virtual ~Simple3DCurveToPolyData( ); - - int RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - int RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - - private: - // Purposely not implemented - Simple3DCurveToPolyData( const Self& ); - void operator=( const Self& ); - - protected: - const TCurve* m_Curve; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__Simple3DCurveToPolyData__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/SkeletonToPolyData.cxx b/lib/cpExtensions/Visualization/SkeletonToPolyData.cxx deleted file mode 100644 index 5aa7d20..0000000 --- a/lib/cpExtensions/Visualization/SkeletonToPolyData.cxx +++ /dev/null @@ -1,147 +0,0 @@ -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -typename cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -Self* cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -const typename -cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -TSkeleton* cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -GetInput( ) const -{ - return( this->m_Skeleton ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -SetInput( const TSkeleton* sk ) -{ - if( this->m_Skeleton != sk ) - { - this->m_Skeleton = sk; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -SkeletonToPolyData( ) - : vtkPolyDataAlgorithm( ), - m_Skeleton( NULL ) -{ - this->SetNumberOfInputPorts( 0 ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -~SkeletonToPolyData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -int cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - typedef typename _TSkeleton::TPath _TPath; - static const unsigned int dim = _TPath::PathDimension; - - if( this->m_Skeleton == NULL ) - return( 0 ); - - // Get output - vtkInformation* info = output->GetInformationObject( 0 ); - vtkPolyData* out = vtkPolyData::SafeDownCast( - info->Get( vtkDataObject::DATA_OBJECT( ) ) - ); - - // Prepare data - out->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - out->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - vtkPoints* points = out->GetPoints( ); - vtkCellArray* lines = out->GetLines( ); - - // Assign all data - auto mIt = this->m_Skeleton->BeginEdgesRows( ); - for( ; mIt != this->m_Skeleton->EndEdgesRows( ); ++mIt ) - { - // TODO: mIt->first; --> this is the row index. <-- - auto rIt = mIt->second.begin( ); - for( ; rIt != mIt->second.end( ); ++rIt ) - { - // TODO: rIt->first; --> this is the column index. - auto eIt = rIt->second.begin( ); - for( ; eIt != rIt->second.end( ); ++eIt ) - { - _TPath* path = *eIt; - for( unsigned long i = 0; i < path->GetSize( ); ++i ) - { - auto pnt = path->GetPoint( i ); - if( dim == 1 ) - points->InsertNextPoint( pnt[ 0 ], 0, 0 ); - else if( dim == 2 ) - points->InsertNextPoint( pnt[ 0 ], pnt[ 1 ], 0 ); - else - points->InsertNextPoint( pnt[ 0 ], pnt[ 1 ], pnt[ 2 ] ); - if( i > 0 ) - { - lines->InsertNextCell( 2 ); - lines->InsertCellPoint( points->GetNumberOfPoints( ) - 2 ); - lines->InsertCellPoint( points->GetNumberOfPoints( ) - 1 ); - - } // fi - - } // rof - - } // rof - - } // rof - - } // rof - return( 1 ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -int cpExtensions::Visualization::SkeletonToPolyData< _TSkeleton >:: -RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ) -{ - return( 1 ); -} - -// ------------------------------------------------------------------------- -#include - -template class cpExtensions::Visualization::SkeletonToPolyData< cpExtensions::DataStructures::Skeleton< 1 > >; -template class cpExtensions::Visualization::SkeletonToPolyData< cpExtensions::DataStructures::Skeleton< 2 > >; -template class cpExtensions::Visualization::SkeletonToPolyData< cpExtensions::DataStructures::Skeleton< 3 > >; -template class cpExtensions::Visualization::SkeletonToPolyData< cpExtensions::DataStructures::Skeleton< 4 > >; - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/SkeletonToPolyData.h b/lib/cpExtensions/Visualization/SkeletonToPolyData.h deleted file mode 100644 index 1cef407..0000000 --- a/lib/cpExtensions/Visualization/SkeletonToPolyData.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef __cpExtensions__Visualization__SkeletonToPolyData__h__ -#define __cpExtensions__Visualization__SkeletonToPolyData__h__ - -#include -#include - -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - template< class _TSkeleton > - class cpExtensions_EXPORT SkeletonToPolyData - : public vtkPolyDataAlgorithm - { - public: - typedef SkeletonToPolyData Self; - typedef _TSkeleton TSkeleton; - - public: - vtkTypeMacro( SkeletonToPolyData, vtkPolyDataAlgorithm ); - - public: - static Self* New( ); - - const TSkeleton* GetInput( ) const; - void SetInput( const TSkeleton* sk ); - - protected: - SkeletonToPolyData( ); - virtual ~SkeletonToPolyData( ); - - int RequestData( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - int RequestInformation( - vtkInformation* information, - vtkInformationVector** input, - vtkInformationVector* output - ); - - private: - // Purposely not implemented - SkeletonToPolyData( const Self& ); - void operator=( const Self& ); - - protected: - const TSkeleton* m_Skeleton; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__SkeletonToPolyData__h__ - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/WindowLevelImageActor.cxx b/lib/cpExtensions/Visualization/WindowLevelImageActor.cxx deleted file mode 100644 index c7cbbd4..0000000 --- a/lib/cpExtensions/Visualization/WindowLevelImageActor.cxx +++ /dev/null @@ -1,200 +0,0 @@ -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::WindowLevelImageActor:: -Self* cpExtensions::Visualization::WindowLevelImageActor:: -New( ) -{ - return( new Self( ) ); -} - -// ------------------------------------------------------------------------- -vtkImageData* cpExtensions::Visualization::WindowLevelImageActor:: -GetImage( ) -{ - return( this->m_Mapper->GetInput( ) ); -} - -// ------------------------------------------------------------------------- -const vtkImageData* cpExtensions::Visualization::WindowLevelImageActor:: -GetImage( ) const -{ - return( this->m_Mapper->GetInput( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetImage( vtkImageData* image ) -{ - this->m_Mapper->SetInputData( image ); - this->ResetRange( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::Visualization::WindowLevelImageActor:: -GetLevel( ) const -{ - Self* self = const_cast< Self* >( this ); - return( self->GetProperty( )->GetColorLevel( ) ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::Visualization::WindowLevelImageActor:: -GetWindow( ) const -{ - Self* self = const_cast< Self* >( this ); - return( self->GetProperty( )->GetColorWindow( ) ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -GetWindowLevel( double wl[ 2 ] ) const -{ - Self* self = const_cast< Self* >( this ); - wl[ 0 ] = self->GetProperty( )->GetColorWindow( ); - wl[ 1 ] = self->GetProperty( )->GetColorLevel( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -ResetWindowLevel( ) -{ - this->SetWindowLevel( - ( this->m_Range[ 1 ] - this->m_Range[ 0 ] ), - ( this->m_Range[ 1 ] + this->m_Range[ 0 ] ) / double( 2 ) - ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetLevel( double l ) -{ - double ol = this->GetProperty( )->GetColorLevel( ); - if( l != ol && this->m_Range[ 0 ] <= l && l <= this->m_Range[ 1 ] ) - { - this->GetProperty( )->SetColorLevel( l ); - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetWindow( double w ) -{ - double mw = this->m_Range[ 1 ] - this->m_Range[ 0 ]; - double ow = this->GetProperty( )->GetColorWindow( ); - if( w != ow && double( 0 ) <= w && w <= mw ) - { - this->GetProperty( )->SetColorWindow( w ); - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetWindowLevel( double w, double l ) -{ - this->SetWindow( w ); - this->SetLevel( l ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetWindowLevel( double wl[ 2 ] ) -{ - this->SetWindow( wl[ 0 ] ); - this->SetLevel( wl[ 1 ] ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::Visualization::WindowLevelImageActor:: -GetMinimum( ) const -{ - return( this->m_Range[ 0 ] ); -} - -// ------------------------------------------------------------------------- -double cpExtensions::Visualization::WindowLevelImageActor:: -GetMaximum( ) const -{ - return( this->m_Range[ 0 ] ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -GetRange( double r[ 2 ] ) const -{ - r[ 0 ] = this->m_Range[ 0 ]; - r[ 1 ] = this->m_Range[ 1 ]; -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -ResetRange( ) -{ - this->GetImage( )->GetScalarRange( this->m_Range ); - this->ResetWindowLevel( ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetMinimum( double a ) -{ - if( this->m_Range[ 0 ] != a ) - { - this->m_Range[ 0 ] = a; - this->ResetWindowLevel( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetMaximum( double b ) -{ - if( this->m_Range[ 1 ] != b ) - { - this->m_Range[ 1 ] = b; - this->ResetWindowLevel( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetRange( double a, double b ) -{ - this->SetMinimum( a ); - this->SetMaximum( b ); -} - -// ------------------------------------------------------------------------- -void cpExtensions::Visualization::WindowLevelImageActor:: -SetRange( double r[ 2 ] ) -{ - this->SetMinimum( r[ 0 ] ); - this->SetMaximum( r[ 1 ] ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::WindowLevelImageActor:: -WindowLevelImageActor( ) - : Superclass( ) -{ - this->m_Range[ 0 ] = this->m_Range[ 1 ] = double( 0 ); -} - -// ------------------------------------------------------------------------- -cpExtensions::Visualization::WindowLevelImageActor:: -~WindowLevelImageActor( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpExtensions/Visualization/WindowLevelImageActor.h b/lib/cpExtensions/Visualization/WindowLevelImageActor.h deleted file mode 100644 index 8af3943..0000000 --- a/lib/cpExtensions/Visualization/WindowLevelImageActor.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef __cpExtensions__Visualization__WindowLevelImageActor__h__ -#define __cpExtensions__Visualization__WindowLevelImageActor__h__ - -#include - -// ------------------------------------------------------------------------- -namespace cpExtensions -{ - namespace Visualization - { - /** - */ - class cpExtensions_EXPORT WindowLevelImageActor - : public ImageActor - { - public: - typedef WindowLevelImageActor Self; - - public: - vtkTypeMacro( WindowLevelImageActor, ImageActor ); - - public: - static Self* New( ); - - vtkImageData* GetImage( ); - const vtkImageData* GetImage( ) const; - void SetImage( vtkImageData* image ); - - double GetLevel( ) const; - double GetWindow( ) const; - void GetWindowLevel( double wl[ 2 ] ) const; - void ResetWindowLevel( ); - void SetLevel( double l ); - void SetWindow( double w ); - void SetWindowLevel( double w, double l ); - void SetWindowLevel( double wl[ 2 ] ); - - double GetMinimum( ) const; - double GetMaximum( ) const; - void GetRange( double r[ 2 ] ) const; - void ResetRange( ); - void SetMinimum( double a ); - void SetMaximum( double b ); - void SetRange( double a, double b ); - void SetRange( double r[ 2 ] ); - - protected: - WindowLevelImageActor( ); - virtual ~WindowLevelImageActor( ); - - private: - // Purposely not implemented - WindowLevelImageActor( const Self& ); - Self& operator=( const Self& ); - - protected: - double m_Range[ 2 ]; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpExtensions__Visualization__WindowLevelImageActor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/BaseObjects/ITKBaseObjects.i b/lib/cpInstances/BaseObjects/ITKBaseObjects.i deleted file mode 100644 index c74dfa2..0000000 --- a/lib/cpInstances/BaseObjects/ITKBaseObjects.i +++ /dev/null @@ -1,41 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define fadims=1;2;3;4;6 -tinclude itkFixedArray:h|hxx -instances itk::FixedArray< #scalar_types#, #fadims# > - -define arrays=Array2D;Array;RGBPixel;RGBAPixel -tinclude itk#arrays#:h|hxx -instances itk::#arrays#< #scalar_types# > - -define vectors=CovariantVector;Point;Vector;SymmetricSecondRankTensor -tinclude itk#vectors#:h|hxx -tinclude itkVectorContainer:h|hxx -instances itk::#vectors#< #real_types#, #pdims# > -instances itk::VectorContainer< unsigned long, itk::#vectors#< #real_types#, #pdims# > > -instances itk::VectorContainer< unsigned long, #scalar_types# > - -tinclude itkDiffusionTensor3D:h|hxx -instances itk::DiffusionTensor3D< #real_types# > - -cinclude set -instances itk::VectorContainer< unsigned long, std::set< #scalar_types# > > - -define cout_vectors=FixedArray;Point;Vector -minstances #_export_# std::ostream& itk::operator<< < #real_types#, #pdims# >( std::ostream& a, itk::#cout_vectors#< #real_types#, #pdims# > const& b ) - -define matrices=Matrix -tinclude itk#matrices#:h|hxx -instances itk::#matrices#< #real_types#, #pdims#, #pdims# > - -define decorated=std::string;#scalar_types# -tinclude itkSimpleDataObjectDecorator:h|hxx -instances itk::SimpleDataObjectDecorator< #decorated# > - -tinclude itkVariableLengthVector:h|hxx -instances itk::VariableLengthVector< #scalar_types# > - -tinclude itkSymmetricEigenAnalysis:h|hxx -instances itk::SymmetricEigenAnalysis< itk::Matrix< #real_types#, #pdims#, #pdims# >, itk::FixedArray< #real_types#, #pdims# >, itk::Matrix< #real_types#, #pdims#, #pdims# > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/BaseObjects/ITKBoundingBoxes.i b/lib/cpInstances/BaseObjects/ITKBoundingBoxes.i deleted file mode 100644 index 9bf736e..0000000 --- a/lib/cpInstances/BaseObjects/ITKBoundingBoxes.i +++ /dev/null @@ -1,6 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkBoundingBox:h|hxx -instances itk::BoundingBox< unsigned long, #pdims#, #real_types#, itk::VectorContainer< unsigned long, itk::Point< #real_types#, #pdims# > > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/BaseObjects/ITKTransforms.i b/lib/cpInstances/BaseObjects/ITKTransforms.i deleted file mode 100644 index bc6b05d..0000000 --- a/lib/cpInstances/BaseObjects/ITKTransforms.i +++ /dev/null @@ -1,18 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define tr=AffineTransform - -tinclude itkOptimizerParameters:h|hxx -tinclude itkTransform:h|hxx -tinclude itkMatrixOffsetTransformBase:h|hxx -tinclude itk#tr#:h|hxx -tinclude itkDataObjectDecorator:h|hxx - -instances itk::OptimizerParameters< #real_types# > -instances itk::MatrixOffsetTransformBase< #real_types#, #pdims#, #pdims# > -instances itk::Transform< #real_types#, #pdims#, #pdims# > -instances itk::#tr#< #real_types#, #pdims# > -instances itk::DataObjectDecorator< itk::Transform< #real_types#, #pdims#, #pdims# > > -instances itk::DataObjectDecorator< itk::#tr#< #real_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/CMakeLists.txt b/lib/cpInstances/CMakeLists.txt deleted file mode 100644 index 2c86239..0000000 --- a/lib/cpInstances/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -## =========================================== -## == Directories containing instantiations == -## =========================================== - -SET( - _directories - BaseObjects - Images - Geometries - Extensions - ) - -## ========================= -## == Real instantiations == -## ========================= - -SET(_pfx cpInstances_) - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR}/BaseObjects - ${CMAKE_CURRENT_BINARY_DIR}/BaseObjects - ${CMAKE_CURRENT_SOURCE_DIR}/Images - ${CMAKE_CURRENT_BINARY_DIR}/Images - ) -FOREACH(_dir ${_directories}) - cpPlugins_BuildLibrary(${_pfx}${_dir} SHARED ${_dir}) -ENDFOREACH(_dir) - -## =========== -## == Links == -## =========== - -TARGET_LINK_LIBRARIES(${_pfx}BaseObjects ${ITK_LIBRARIES}) -TARGET_LINK_LIBRARIES(${_pfx}Images ${_pfx}BaseObjects ${VTK_LIBRARIES}) -TARGET_LINK_LIBRARIES(${_pfx}Geometries ${_pfx}BaseObjects) -TARGET_LINK_LIBRARIES(${_pfx}Extensions cpExtensions ${_pfx}Geometries) - -## ========================== -## == Generic data objects == -## ========================== - -cpPlugins_BuildLibrary(cpPluginsDataObjects SHARED DataObjects) -TARGET_LINK_LIBRARIES( - cpPluginsDataObjects - cpExtensions - cpPlugins - ${_pfx}Images ${_pfx}Geometries ${_pfx}Extensions - ) - -## eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/BoundingBox.cxx b/lib/cpInstances/DataObjects/BoundingBox.cxx deleted file mode 100644 index ea05810..0000000 --- a/lib/cpInstances/DataObjects/BoundingBox.cxx +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::BoundingBox:: -SetDataObject( DataObject* o ) -{ - auto i = o->GetITK< itk::LightObject >( ); - auto v = o->GetVTK< vtkObjectBase >( ); - if( v != NULL ) this->SetVTK( v ); - else if( i != NULL ) this->SetITK( i ); - this->_UpdateVTK( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::BoundingBox:: -Copy( Self* other ) -{ - this->m_Points[ 0 ] = other->m_Points[ 0 ]; - this->m_Points[ 1 ] = other->m_Points[ 1 ]; - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::BoundingBox:: -Blend( Self* other ) -{ - if( this->m_Points[ 0 ].size( ) < other->m_Points[ 0 ].size( ) ) - this->m_Points[ 0 ].resize( - other->m_Points[ 0 ].size( ), - std::numeric_limits< double >::max( ) - ); - if( this->m_Points[ 1 ].size( ) < other->m_Points[ 1 ].size( ) ) - this->m_Points[ 1 ].resize( - other->m_Points[ 1 ].size( ), - -std::numeric_limits< double >::max( ) - ); - for( unsigned int d = 0; d < this->m_Points[ 0 ].size( ); ++d ) - if( other->m_Points[ 0 ][ d ] < this->m_Points[ 0 ][ d ] ) - this->m_Points[ 0 ][ d ] = other->m_Points[ 0 ][ d ]; - for( unsigned int d = 0; d < this->m_Points[ 1 ].size( ); ++d ) - if( other->m_Points[ 1 ][ d ] > this->m_Points[ 1 ][ d ] ) - this->m_Points[ 1 ][ d ] = other->m_Points[ 1 ][ d ]; - this->Modified( ); - this->_UpdateVTK( ); -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::BoundingBox:: -BoundingBox( ) - : Superclass( ) -{ - this->m_Points[ 0 ].push_back( double( 0 ) ); - this->m_Points[ 1 ].push_back( double( 0 ) ); - this->m_Outline = vtkSmartPointer< vtkOutlineSource >::New( ); - this->_UpdateVTK( ); -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::BoundingBox:: -~BoundingBox( ) -{ -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::BoundingBox:: -_UpdateVTK( ) -{ - auto dobj = this->GetVTK< vtkDataSet >( ); - if( dobj == NULL ) - return; - - // Get bounds - double bounds[ 6 ]; - dobj->GetBounds( bounds ); - - this->m_Points[ 0 ].clear( ); - this->m_Points[ 1 ].clear( ); - this->m_Points[ 0 ].push_back( bounds[ 0 ] ); - this->m_Points[ 0 ].push_back( bounds[ 2 ] ); - this->m_Points[ 0 ].push_back( bounds[ 4 ] ); - this->m_Points[ 1 ].push_back( bounds[ 1 ] ); - this->m_Points[ 1 ].push_back( bounds[ 3 ] ); - this->m_Points[ 1 ].push_back( bounds[ 5 ] ); - - // Update vtk objects - this->m_Outline->SetBounds( bounds ); - this->m_Outline->Update( ); - this->m_VTK = this->m_Outline->GetOutput( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/BoundingBox.h b/lib/cpInstances/DataObjects/BoundingBox.h deleted file mode 100644 index dfe1300..0000000 --- a/lib/cpInstances/DataObjects/BoundingBox.h +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef __cpInstances__BoundingBox__h__ -#define __cpInstances__BoundingBox__h__ - -#define ITK_MANUAL_INSTANTIATION -#include -#include -#include -#include -#include - -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT BoundingBox - : public cpPlugins::Pipeline::DataObject - { - public: - typedef BoundingBox Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( BoundingBox, DataObject ); - cpPlugins_Id_Macro( BoundingBox, Object ); - cpPlugins_Compatibility_Macro; - - public: - void SetDataObject( DataObject* o ); - - void Copy( Self* other ); - void Blend( Self* other ); - - template< class _TPoint > - inline void SetMinimum( const _TPoint& p ) - { - this->_SetPoint( 0, p ); - } - - template< class _TPoint > - inline void SetMaximum( const _TPoint& p ) - { - this->_SetPoint( 1, p ); - } - - template< class _TPoint > - inline _TPoint GetMinimum( ) const - { - return( this->_GetPoint< _TPoint >( 0 ) ); - } - - template< class _TPoint > - inline _TPoint GetMaximum( ) const - { - return( this->_GetPoint< _TPoint >( 1 ) ); - } - - protected: - BoundingBox( ); - virtual ~BoundingBox( ); - - void _UpdateVTK( ); - - template< class _TPoint > - inline void _SetPoint( unsigned int m, const _TPoint& p ) - { - this->m_Points[ m ].clear( ); - for( unsigned int d = 0; d < _TPoint::PointDimension; ++d ) - this->m_Points[ m ].push_back( double( p[ d ] ) ); - this->_UpdateVTK( ); - this->Modified( ); - } - - template< class _TPoint > - inline _TPoint _GetPoint( unsigned int m ) const - { - unsigned int dim = this->m_Points[ m ].size( ); - dim = - ( _TPoint::PointDimension < dim )? _TPoint::PointDimension: dim; - _TPoint p; - p.Fill( 0 ); - for( unsigned int d = 0; d < dim; ++d ) - p[ d ] = this->m_Points[ m ][ d ]; - return( p ); - } - - private: - // Purposely not implemented - BoundingBox( const Self& ); - Self& operator=( const Self& ); - - protected: - std::vector< double > m_Points[ 2 ]; - vtkSmartPointer< vtkOutlineSource > m_Outline; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__BoundingBox__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Image.cxx b/lib/cpInstances/DataObjects/Image.cxx deleted file mode 100644 index 09cf834..0000000 --- a/lib/cpInstances/DataObjects/Image.cxx +++ /dev/null @@ -1,196 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Image:: -SetITK( itk::LightObject* o ) -{ - this->Superclass::SetITK( o ); - this->m_VTK = NULL; - this->m_ITKvVTK = NULL; - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Image:: -SetVTK( vtkObjectBase* o ) -{ - this->Superclass::SetVTK( o ); - this->m_ITK = NULL; - this->m_ITKvVTK = NULL; - this->Modified( ); - - /* TODO - vtkImageData* img = dynamic_cast< vtkImageData* >( o ); - this->Superclass::SetVTK( img ); - if( img == NULL ) - { - this->m_ITK = NULL; - this->m_ITKvVTK = NULL; - this->Modified( ); - return; - - } // fi - - bool success = false; - auto stype = img->GetScalarType( ); - #ifdef cpPlugins_CONFIG_INTEGER_TYPES_char - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< char >( img ); - if( stype == VTK_UNSIGNED_CHAR ) success = this->_VTK_2_ITK_0< unsigned char >( img ); - #endif // cpPlugins_CONFIG_INTEGER_TYPES_char - #ifdef cpPlugins_CONFIG_INTEGER_TYPES_short - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< short >( img ); - if( stype == VTK_UNSIGNED_CHAR ) success = this->_VTK_2_ITK_0< unsigned short >( img ); - #endif // cpPlugins_CONFIG_INTEGER_TYPES_short - #ifdef cpPlugins_CONFIG_INTEGER_TYPES_int - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< int >( img ); - if( stype == VTK_UNSIGNED_CHAR ) success = this->_VTK_2_ITK_0< unsigned int >( img ); - #endif // cpPlugins_CONFIG_INTEGER_TYPES_int - #ifdef cpPlugins_CONFIG_INTEGER_TYPES_long - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< long >( img ); - if( stype == VTK_UNSIGNED_CHAR ) success = this->_VTK_2_ITK_0< unsigned long >( img ); - #endif // cpPlugins_CONFIG_INTEGER_TYPES_long - #ifdef cpPlugins_CONFIG_REAL_TYPES_float - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< float >( img ); - #endif // cpPlugins_CONFIG_REAL_TYPES_float - #ifdef cpPlugins_CONFIG_REAL_TYPES_double - if( stype == VTK_CHAR ) success = this->_VTK_2_ITK_0< double >( img ); - #endif // cpPlugins_CONFIG_REAL_TYPES_double - */ - /* TODO - #define cpPlugins_CONFIG_COLOR_PIXELS_RGBPixel - #define cpPlugins_CONFIG_COLOR_PIXELS_RGBAPixel - #define cpPlugins_CONFIG_VECTORS_CovariantVector - #define cpPlugins_CONFIG_VECTORS_Point - #define cpPlugins_CONFIG_VECTORS_SymmetricSecondRankTensor - #define cpPlugins_CONFIG_VECTORS_Vector - #define cpPlugins_CONFIG_DIFFUSIONTENSORS_DiffusionTensor3D - #define cpPlugins_CONFIG_MATRICES_Matrix - */ - /* TODO - if( !success ) - { - this->m_ITK = NULL; - this->m_ITKvVTK = NULL; - - } // fi - this->Modified( ); - */ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Image:: -Image( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Image:: -~Image( ) -{ -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Image:: -_UpdateITK( ) const -{ - // TODO: std::cout << "Create ITK representation." << std::endl; -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Image:: -_UpdateVTK( ) const -{ - auto i = const_cast< itk::LightObject* >( this->m_ITK.GetPointer( ) ); - auto v = const_cast< vtkObjectBase* >( this->m_VTK.GetPointer( ) ); - if( i != NULL && v == NULL ) - { - cpPlugins_Demangle_Image_VisualDims_1( i, _ITK_2_VTK_0 ) - cpPlugins_Demangle_Image_DiffTensors3D_1( i, _ITK_2_VTK_1 ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpInstances::DataObjects::Image:: -_ITK_2_VTK_0( _TImage* image ) const -{ - static const unsigned int d = _TImage::ImageDimension; - cpPlugins_Demangle_Image_ScalarPixels_1( image, _ITK_2_VTK_1, d ) - cpPlugins_Demangle_Image_ColorPixels_1( image, _ITK_2_VTK_1, d ) - cpPlugins_Demangle_Image_VectorPixels_1( image, _ITK_2_VTK_1, d ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpInstances::DataObjects::Image:: -_ITK_2_VTK_1( _TImage* image ) const -{ - typedef itk::ImageToVTKImageFilter< _TImage > _TFilter; - - Self* self = const_cast< Self* >( this ); - _TFilter* f = dynamic_cast< _TFilter* >( self->m_ITKvVTK.GetPointer( ) ); - if( f == NULL ) - { - typename _TFilter::Pointer nf = _TFilter::New( ); - self->m_ITKvVTK = nf; - f = nf.GetPointer( ); - - } // fi - f->SetInput( image ); - f->Update( ); - - // Keep object track - self->m_ITK = image; - self->m_VTK = f->GetOutput( ); -} - -// ------------------------------------------------------------------------- -template< class _TPixel > -bool cpInstances::DataObjects::Image:: -_VTK_2_ITK_0( vtkImageData* image ) -{ - bool success = false; - unsigned int dim = image->GetDataDimension( ); -#ifdef cpPlugins_CONFIG_VISUAL_DIMENSIONS_2 - if( dim == 2 ) success = this->_VTK_2_ITK_1< _TPixel, 2 >( image ); -#endif // cpPlugins_CONFIG_VISUAL_DIMENSIONS_2 -#ifdef cpPlugins_CONFIG_VISUAL_DIMENSIONS_3 - if( dim == 3 ) success = this->_VTK_2_ITK_1< _TPixel, 3 >( image ); -#endif // cpPlugins_CONFIG_VISUAL_DIMENSIONS_2 - return( success ); -} - -// ------------------------------------------------------------------------- -template< class _TPixel, unsigned int _VDim > -bool cpInstances::DataObjects::Image:: -_VTK_2_ITK_1( vtkImageData* image ) -{ - typedef itk::Image< _TPixel, _VDim > _TImage; - typedef itk::VTKImageToImageFilter< _TImage > _TFilter; - _TFilter* f = dynamic_cast< _TFilter* >( this->m_ITKvVTK.GetPointer( ) ); - if( f == NULL ) - { - typename _TFilter::Pointer nf = _TFilter::New( ); - this->m_ITKvVTK = nf; - f = nf.GetPointer( ); - - } // fi - f->SetInput( image ); - f->Update( ); - - // Keep object track - this->m_VTK = image; - this->m_ITK = f->GetOutput( ); - return( true ); -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Image.d b/lib/cpInstances/DataObjects/Image.d deleted file mode 100644 index b9a2444..0000000 --- a/lib/cpInstances/DataObjects/Image.d +++ /dev/null @@ -1,27 +0,0 @@ -define all_ints=#int_types#;unsigned #int_types# -define color_pixels=RGBPixel;RGBAPixel - -ProcessDims itk::ImageBase< #pdims# > -VisualDims itk::ImageBase< #vdims# > - -IntPixels|d itk::Image< #all_ints#, d > -RealPixels|d itk::Image< #real_types#, d > -ScalarPixels|d itk::Image< #scalar_types#, d > -ComplexPixels|d itk::Image< std::complex< #real_types# >, d > -ColorPixels|d itk::Image< itk::#color_pixels#< #scalar_types# >, d > -VectorPixels|d itk::Image< itk::#vectors#< #real_types#, d >, d > -DiffTensors3D itk::Image< itk::#diff_tensors#< #real_types# >, 3 > - -IntPixels_AllDims itk::Image< #all_ints#, #pdims# > -IntPixels_VisualDims itk::Image< #all_ints#, #pdims# > -RealPixels_AllDims itk::Image< #real_types#, #pdims# > -RealPixels_VisualDims itk::Image< #real_types#, #pdims# > -ScalarPixels_AllDims itk::Image< #scalar_types#, #pdims# > -ScalarPixels_VisualDims itk::Image< #scalar_types#, #vdims# > -ColorPixels_AllDims itk::Image< itk::#color_pixels#< #scalar_types# >, #pdims# > -ColorPixels_VisualDims itk::Image< itk::#color_pixels#< #scalar_types# >, #vdims# > -VectorPixels_AllDims itk::Image< itk::#vectors#< #real_types#, #pdims# >, #pdims# > -VectorPixels_VisualDims itk::Image< itk::#vectors#< #real_types#, #vdims# >, #vdims# > -CovariantVectorPixels_AllDims itk::Image< itk::CovariantVector< #real_types#, #pdims# >, #pdims# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Image.h b/lib/cpInstances/DataObjects/Image.h deleted file mode 100644 index 7a4a387..0000000 --- a/lib/cpInstances/DataObjects/Image.h +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef __cpInstances__Image__h__ -#define __cpInstances__Image__h__ - -#define ITK_MANUAL_INSTANTIATION -#include -#include -#include -#include - -class vtkImageData; - -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT Image - : public cpPlugins::Pipeline::DataObject - { - public: - typedef Image Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( Image, cpPlugins::Pipeline::DataObject ); - cpPlugins_Id_Macro( Image, Object ); - cpPlugins_Compatibility_Macro; - - public: - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - Image( ); - virtual ~Image( ); - - virtual void _UpdateITK( ) const override; - virtual void _UpdateVTK( ) const override; - - template< class _TImage > - inline void _ITK_2_VTK_0( _TImage* image ) const; - - template< class _TImage > - inline void _ITK_2_VTK_1( _TImage* image ) const; - - template< class _TPixel > - inline bool _VTK_2_ITK_0( vtkImageData* image ); - - template< class _TPixel, unsigned int _VDim > - inline bool _VTK_2_ITK_1( vtkImageData* image ); - - private: - // Purposely not implemented - Image( const Self& ); - Self& operator=( const Self& ); - - protected: - itk::ProcessObject::Pointer m_ITKvVTK; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__Image__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Mesh.cxx b/lib/cpInstances/DataObjects/Mesh.cxx deleted file mode 100644 index 2118301..0000000 --- a/lib/cpInstances/DataObjects/Mesh.cxx +++ /dev/null @@ -1,180 +0,0 @@ -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Mesh:: -SetITK( itk::LightObject* o ) -{ - this->Superclass::SetITK( o ); - cpPlugins_Demangle_Mesh_AllMeshes_1( o, _ITK_2_VTK ) - { - this->m_VTK = NULL; - } - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Mesh:: -SetVTK( vtkObjectBase* o ) -{ - vtkPolyData* mesh = dynamic_cast< vtkPolyData* >( o ); - if( mesh == NULL ) - { - this->m_ITK = NULL; - this->Modified( ); - return; - - } // fi - - if( this->m_VTK.GetPointer( ) != mesh ) - { - this->m_VTK = mesh; -#ifdef cpPlugins_PROCESS_DIMS_3 - typedef itk::Mesh< double, 3 > _TMesh; - typedef _TMesh::CellType _TCell; - typedef _TCell::CellAutoPointer _TCellAutoPointer; - typedef itk::LineCell< _TCell > _TLine; - typedef itk::TriangleCell< _TCell > _TTriangle; - typedef itk::PolygonCell< _TCell > _TPolygon; - - // Copy points - _TMesh::Pointer imesh = _TMesh::New( ); - double point[ 3 ]; - for( long i = 0; i < mesh->GetNumberOfPoints( ); ++i ) - { - mesh->GetPoint( i, point ); - _TMesh::PointType ipoint; - ipoint[ 0 ] = point[ 0 ]; - ipoint[ 1 ] = point[ 1 ]; - ipoint[ 2 ] = point[ 2 ]; - imesh->SetPoint( i, ipoint ); - - } // rof - - // Copy cells - vtkCellArray* arrays[ 4 ]; - arrays[ 0 ] = mesh->GetLines( ); - arrays[ 1 ] = mesh->GetPolys( ); - arrays[ 2 ] = NULL; // TODO: mesh->GetStrips( ); - arrays[ 3 ] = mesh->GetVerts( ); - - for( unsigned int c = 0; c < 4; c++ ) - { - if( arrays[ c ] != NULL ) - { - vtkSmartPointer< vtkIdList > ids = - vtkSmartPointer< vtkIdList >::New( ); - arrays[ c ]->InitTraversal( ); - while( arrays[ c ]->GetNextCell( ids ) == 1 ) - { - long nPoints = ids->GetNumberOfIds( ); - _TCellAutoPointer icell; - if( nPoints == 2 ) - { - icell.TakeOwnership( new _TLine ); - icell->SetPointId( 0, ids->GetId( 0 ) ); - icell->SetPointId( 1, ids->GetId( 1 ) ); - } - else if( nPoints == 3 ) - { - icell.TakeOwnership( new _TTriangle ); - icell->SetPointId( 0, ids->GetId( 0 ) ); - icell->SetPointId( 1, ids->GetId( 1 ) ); - icell->SetPointId( 2, ids->GetId( 2 ) ); - } - else if( nPoints > 3 ) - { - _TPolygon* polygon = new _TPolygon( ); - for( long j = 0; j < nPoints; ++j ) - polygon->AddPointId( ids->GetId( j ) ); - icell.TakeOwnership( polygon ); - - } // fi - imesh->SetCell( imesh->GetNumberOfCells( ), icell ); - - } // elihw - - } // fi - - } // rof - this->m_ITK = imesh; -#endif // cpPlugins_PROCESS_DIMS_3 - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Mesh:: -Mesh( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Mesh:: -~Mesh( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TMesh > -void cpInstances::DataObjects::Mesh:: -_ITK_2_VTK( _TMesh* mesh ) -{ - long numPoints = mesh->GetNumberOfPoints( ); - if( numPoints == 0 ) - return; - - vtkSmartPointer< vtkPoints > vpoints = - vtkSmartPointer< vtkPoints >::New( ); - vpoints->SetNumberOfPoints( numPoints ); - auto points = mesh->GetPoints( ); - - // Copy points - vtkIdType VTKId = 0; - std::map< vtkIdType, long > IndexMap; - for( auto i = points->Begin( ); i != points->End( ); ++i, VTKId++ ) - { - IndexMap[ VTKId ] = i->Index( ); - if( _TMesh::PointDimension == 2 ) - vpoints->SetPoint( - VTKId, - i->Value( )[ 0 ], i->Value( )[ 1 ], 0 - ); - else if( _TMesh::PointDimension == 3 ) - vpoints->SetPoint( - VTKId, - i->Value( )[ 0 ], i->Value( )[ 1 ], i->Value( )[ 2 ] - ); - - } // rof - - // Copy cells - vtkSmartPointer< vtkCellArray > vcells = - vtkSmartPointer< vtkCellArray >::New( ); - auto cells = mesh->GetCells( ); - for( auto j = cells->Begin( ); j != cells->End( ); ++j ) - { - auto cell = j->Value( ); - vcells->InsertNextCell( cell->GetNumberOfPoints( ) ); - for( auto k = cell->PointIdsBegin( ); k != cell->PointIdsEnd( ); ++k ) - vcells->InsertCellPoint( IndexMap[ *k ] ); - - } // rof - - // Final assignations - vtkSmartPointer< vtkPolyData > vmesh = - vtkSmartPointer< vtkPolyData >::New( ); - vmesh->SetPoints( vpoints ); - vmesh->SetPolys( vcells ); - this->m_VTK = vmesh; - this->Modified( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Mesh.d b/lib/cpInstances/DataObjects/Mesh.d deleted file mode 100644 index 8f98aca..0000000 --- a/lib/cpInstances/DataObjects/Mesh.d +++ /dev/null @@ -1,4 +0,0 @@ -AllMeshes itk::Mesh< #real_types#, #vdims# > -Meshes|d itk::Mesh< #real_types#, d > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Mesh.h b/lib/cpInstances/DataObjects/Mesh.h deleted file mode 100644 index f15c1b4..0000000 --- a/lib/cpInstances/DataObjects/Mesh.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef __cpInstances__Mesh__h__ -#define __cpInstances__Mesh__h__ - -#define ITK_MANUAL_INSTANTIATION -#include -#include -#include - -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT Mesh - : public cpPlugins::Pipeline::DataObject - { - public: - typedef Mesh Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( Mesh, DataObject ); - cpPlugins_Id_Macro( Mesh, Object ); - cpPlugins_Compatibility_Macro; - - public: - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - Mesh( ); - virtual ~Mesh( ); - - template< class _TMesh > - inline void _ITK_2_VTK( _TMesh* mesh ); - - private: - // Purposely not implemented - Mesh( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__Mesh__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/PolyLineParametricPath.cxx b/lib/cpInstances/DataObjects/PolyLineParametricPath.cxx deleted file mode 100644 index 623233f..0000000 --- a/lib/cpInstances/DataObjects/PolyLineParametricPath.cxx +++ /dev/null @@ -1,39 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::PolyLineParametricPath:: -SetITK( itk::LightObject* o ) -{ - this->Superclass::SetITK( o ); - /* TODO - cpPlugins_Demangle_PolyLineParametricPath_VisualDims_1( o, _ITK_2_VTK_0 ) - cpPlugins_Demangle_PolyLineParametricPath_DiffTensors3D_1( o, _ITK_2_VTK_1 ) - { - this->m_VTK = NULL; - this->m_ITKvVTK = NULL; - - } // fi - */ - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::PolyLineParametricPath:: -SetVTK( vtkObjectBase* o ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::PolyLineParametricPath:: -PolyLineParametricPath( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::PolyLineParametricPath:: -~PolyLineParametricPath( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/PolyLineParametricPath.d b/lib/cpInstances/DataObjects/PolyLineParametricPath.d deleted file mode 100644 index e13c77f..0000000 --- a/lib/cpInstances/DataObjects/PolyLineParametricPath.d +++ /dev/null @@ -1,4 +0,0 @@ -All cpExtensions::DataStructures::PolyLineParametricPath< #pdims# > -Dim|d cpExtensions::DataStructures::PolyLineParametricPath< d > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/PolyLineParametricPath.h b/lib/cpInstances/DataObjects/PolyLineParametricPath.h deleted file mode 100644 index fff6b6b..0000000 --- a/lib/cpInstances/DataObjects/PolyLineParametricPath.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef __cpInstances__PolyLineParametricPath__h__ -#define __cpInstances__PolyLineParametricPath__h__ - -#include -#include -#include -#include - -class vtkPolyLineParametricPathData; - -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT PolyLineParametricPath - : public cpPlugins::Pipeline::DataObject - { - public: - typedef PolyLineParametricPath Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( PolyLineParametricPath, cpPlugins::Pipeline::DataObject ); - cpPlugins_Id_Macro( PolyLineParametricPath, Object ); - cpPlugins_Compatibility_Macro; - - public: - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - PolyLineParametricPath( ); - virtual ~PolyLineParametricPath( ); - - private: - // Purposely not implemented - PolyLineParametricPath( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__PolyLineParametricPath__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Simple3DCurve.cxx b/lib/cpInstances/DataObjects/Simple3DCurve.cxx deleted file mode 100644 index 659efff..0000000 --- a/lib/cpInstances/DataObjects/Simple3DCurve.cxx +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Simple3DCurve:: -SetVTK( vtkObjectBase* o ) -{ - // Do nothing -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Simple3DCurve:: -Simple3DCurve( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Simple3DCurve:: -~Simple3DCurve( ) -{ -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Simple3DCurve:: -_UpdateVTK( ) const -{ - auto i = const_cast< itk::LightObject* >( this->m_ITK.GetPointer( ) ); - auto v = const_cast< vtkObjectBase* >( this->m_VTK.GetPointer( ) ); - if( i != NULL && v == NULL ) - { - cpPlugins_Demangle_Simple3DCurve_All_1( i, _ITK_2_VTK ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TCurve > -void cpInstances::DataObjects::Simple3DCurve:: -_ITK_2_VTK( _TCurve* curve ) const -{ - typedef - cpExtensions::Visualization::Simple3DCurveToPolyData< _TCurve > - _TFilter; - - Self* self = const_cast< Self* >( this ); - _TFilter* f = dynamic_cast< _TFilter* >( self->m_ITKvVTK.GetPointer( ) ); - if( f == NULL ) - { - _TFilter* nf = _TFilter::New( ); - self->m_ITKvVTK = nf; - f = nf; - - } // fi - f->SetInput( curve ); - f->Update( ); - - // Keep object track - self->m_ITK = curve; - self->m_VTK = f->GetOutput( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Simple3DCurve.d b/lib/cpInstances/DataObjects/Simple3DCurve.d deleted file mode 100644 index 2ba68a1..0000000 --- a/lib/cpInstances/DataObjects/Simple3DCurve.d +++ /dev/null @@ -1 +0,0 @@ -All cpExtensions::DataStructures::Simple3DCurve< #real_types# > diff --git a/lib/cpInstances/DataObjects/Simple3DCurve.h b/lib/cpInstances/DataObjects/Simple3DCurve.h deleted file mode 100644 index e1e7ab5..0000000 --- a/lib/cpInstances/DataObjects/Simple3DCurve.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef __cpInstances__DataObjects__Simple3DCurve__h__ -#define __cpInstances__DataObjects__Simple3DCurve__h__ - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkPolyDataAlgorithm; - -// ------------------------------------------------------------------------- -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT Simple3DCurve - : public cpPlugins::Pipeline::DataObject - { - public: - typedef Simple3DCurve Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( Simple3DCurve, cpPlugins::Pipeline::DataObject ); - cpPlugins_Id_Macro( Simple3DCurve, Object ); - cpPlugins_Compatibility_Macro; - - public: - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - Simple3DCurve( ); - virtual ~Simple3DCurve( ); - - virtual void _UpdateVTK( ) const override; - - template< class _TCurve > - inline void _ITK_2_VTK( _TCurve* curve ) const; - - private: - // Purposely not implemented - Simple3DCurve( const Self& ); - Self& operator=( const Self& ); - - protected: - vtkSmartPointer< vtkPolyDataAlgorithm > m_ITKvVTK; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__Simple3DCurve__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Skeleton.cxx b/lib/cpInstances/DataObjects/Skeleton.cxx deleted file mode 100644 index 1c30186..0000000 --- a/lib/cpInstances/DataObjects/Skeleton.cxx +++ /dev/null @@ -1,39 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Skeleton:: -SetITK( itk::LightObject* o ) -{ - this->Superclass::SetITK( o ); - /* TODO - cpPlugins_Demangle_Skeleton_VisualDims_1( o, _ITK_2_VTK_0 ) - cpPlugins_Demangle_Skeleton_DiffTensors3D_1( o, _ITK_2_VTK_1 ) - { - this->m_VTK = NULL; - this->m_ITKvVTK = NULL; - - } // fi - */ - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpInstances::DataObjects::Skeleton:: -SetVTK( vtkObjectBase* o ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Skeleton:: -Skeleton( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpInstances::DataObjects::Skeleton:: -~Skeleton( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpInstances/DataObjects/Skeleton.d b/lib/cpInstances/DataObjects/Skeleton.d deleted file mode 100644 index 99e6261..0000000 --- a/lib/cpInstances/DataObjects/Skeleton.d +++ /dev/null @@ -1 +0,0 @@ -All cpExtensions::DataStructures::Skeleton< #pdims# > diff --git a/lib/cpInstances/DataObjects/Skeleton.h b/lib/cpInstances/DataObjects/Skeleton.h deleted file mode 100644 index 18d4731..0000000 --- a/lib/cpInstances/DataObjects/Skeleton.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef __cpInstances__DataObjects__Skeleton__h__ -#define __cpInstances__DataObjects__Skeleton__h__ - -#include -#include -#include -#include - -namespace cpInstances -{ - namespace DataObjects - { - /** - */ - class cpPluginsDataObjects_EXPORT Skeleton - : public cpPlugins::Pipeline::DataObject - { - public: - typedef Skeleton Self; - typedef cpPlugins::Pipeline::DataObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( Skeleton, cpPlugins::Pipeline::DataObject ); - cpPlugins_Id_Macro( Skeleton, Object ); - cpPlugins_Compatibility_Macro; - - public: - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - Skeleton( ); - virtual ~Skeleton( ); - - private: - // Purposely not implemented - Skeleton( const Self& ); - Self& operator=( const Self& ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpInstances__Skeleton__h__ - -// eof - $RCSfile$ diff --git a/lib/cpInstances/Extensions/Paths.i b/lib/cpInstances/Extensions/Paths.i deleted file mode 100644 index 1533e1a..0000000 --- a/lib/cpInstances/Extensions/Paths.i +++ /dev/null @@ -1,11 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude cpExtensions/Algorithms/BezierCurveFunction:h|hxx -tinclude cpExtensions/DataStructures/PolyLineParametricPath:h|hxx -tinclude itkVectorContainer:h|hxx - -instances itk::VectorContainer< unsigned int, itk::ContinuousIndex< #real_types#, #pdims# > > -instances cpExtensions::Algorithms::BezierCurveFunction< itk::Vector< #real_types#, #pdims# > > -instances cpExtensions::DataStructures::PolyLineParametricPath< #pdims# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Extensions/Skeleton.i b/lib/cpInstances/Extensions/Skeleton.i deleted file mode 100644 index ed1ec99..0000000 --- a/lib/cpInstances/Extensions/Skeleton.i +++ /dev/null @@ -1,8 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude cpExtensions/DataStructures/Skeleton:h|hxx -cinclude cpExtensions/DataStructures/Graph.hxx - -instances cpExtensions::DataStructures::Skeleton< #pdims# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Geometries/ITKMeshes.i b/lib/cpInstances/Geometries/ITKMeshes.i deleted file mode 100644 index 70b0c54..0000000 --- a/lib/cpInstances/Geometries/ITKMeshes.i +++ /dev/null @@ -1,16 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define meshes=PointSet;Mesh -tinclude itk#meshes#:h|hxx -cinclude itkMapContainer.hxx -cinclude itkVectorContainer.hxx -instances itk::#meshes#< #real_types#, #vdims# > - -define cells=Vertex;Line;Triangle;Polygon -tinclude itk#cells#Cell:h|hxx -tinclude itkCellInterface:h|hxx -instances itk::CellInterface< #real_types#, itk::CellTraitsInfo< #vdims#, float, float, unsigned long, unsigned long, unsigned long, itk::Point< float, #vdims# >, itk::VectorContainer< unsigned long, itk::Point< float, #vdims# > >, std::set< unsigned long > > > -instances itk::VectorContainer< unsigned long, itk::CellInterface< #real_types#, itk::CellTraitsInfo< #vdims#, float, float, unsigned long, unsigned long, unsigned long, itk::Point< float, #vdims# >, itk::VectorContainer< unsigned long, itk::Point< float, #vdims# > >, std::set< unsigned long > > >* > -instances itk::#cells#Cell< itk::CellInterface< #real_types#, itk::CellTraitsInfo< #vdims#, float, float, unsigned long, unsigned long, unsigned long, itk::Point< float, #vdims# >, itk::VectorContainer< unsigned long, itk::Point< float, #vdims# > >, std::set< unsigned long > > > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Geometries/ITKPaths.i b/lib/cpInstances/Geometries/ITKPaths.i deleted file mode 100644 index d2b413f..0000000 --- a/lib/cpInstances/Geometries/ITKPaths.i +++ /dev/null @@ -1,11 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkPath:h|hxx -tinclude itkParametricPath:h|hxx -tinclude itkPolyLineParametricPath:h|hxx -cinclude itkVectorContainer.hxx -instances itk::Path< double, itk::ContinuousIndex< double, #pdims# >, #pdims# > -define paths=itk::ParametricPath;itk::PolyLineParametricPath -instances #paths#< #pdims# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITK2VTKImageFilters.i b/lib/cpInstances/Images/ITK2VTKImageFilters.i deleted file mode 100644 index a248963..0000000 --- a/lib/cpInstances/Images/ITK2VTKImageFilters.i +++ /dev/null @@ -1,20 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define color_pixels=RGBPixel;RGBAPixel -define vector_pixels=CovariantVector;Point;Vector -define matrices=Matrix -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# > - -cinclude itkImage.h -cinclude itk#color_pixels#.h -cinclude itkFixedArray.h -cinclude itk#vector_pixels#.h -cinclude itk#matrices#.h - -define filters=VTKImageImport;VTKImageExport;ImageToVTKImageFilter;VTKImageToImageFilter -tinclude itk#filters#:h|hxx -instances itk::#filters#< itk::Image< #pixels#, #vdims# > > -instances itk::#filters#< itk::Image< itk::FixedArray< #scalar_types#, #vdims# >, #vdims# > > -instances itk::#filters#< itk::Image< itk::#vector_pixels#< #real_types#, #vdims# >, #vdims# > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITKBoxImageFilters.i b/lib/cpInstances/Images/ITKBoxImageFilters.i deleted file mode 100644 index 69f40fd..0000000 --- a/lib/cpInstances/Images/ITKBoxImageFilters.i +++ /dev/null @@ -1,10 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define i_scalars=#scalar_types# -define o_scalars=#scalar_types# - -tinclude itkBoxImageFilter:h|hxx - -instances itk::BoxImageFilter< itk::Image< #i_scalars# , #pdims# >, itk::Image< #o_scalars#, #pdims# > > - -** eof - $RCSfile$ \ No newline at end of file diff --git a/lib/cpInstances/Images/ITKImageFunctions.i b/lib/cpInstances/Images/ITKImageFunctions.i deleted file mode 100644 index 8b4cbdb..0000000 --- a/lib/cpInstances/Images/ITKImageFunctions.i +++ /dev/null @@ -1,13 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define i_reals=#real_types# -define o_reals=#real_types# -define p_reals=#real_types# - -tinclude itkImageFunction:h|hxx -cinclude itkImage.h - -instances itk::ImageFunction< itk::Image< #scalar_types#, #pdims# >, #i_reals#, #o_reals# > -instances itk::ImageFunction< itk::Image< itk::FixedArray< #i_reals#, #pdims# >, #pdims# >, itk::FixedArray< #o_reals#, #pdims# >, #p_reals# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITKImageInterpolators.i b/lib/cpInstances/Images/ITKImageInterpolators.i deleted file mode 100644 index cee831b..0000000 --- a/lib/cpInstances/Images/ITKImageInterpolators.i +++ /dev/null @@ -1,23 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define v=FixedArray -define i_real=#real_types# -define o_real=#real_types# -define interp=Linear - -tinclude itk#interp#InterpolateImageFunction:h|hxx -tinclude itkVectorLinearInterpolateImageFunction:h|hxx - -cinclude itk#v#.h -cinclude itkImage.h - -instances itk::#interp#InterpolateImageFunction< itk::Image< #scalar_types#, #pdims# >, #real_types# > - -instances itk::VectorLinearInterpolateImageFunction< itk::Image< itk::#v#< #i_real#, #pdims# >, #pdims# >, #o_real# > - -tinclude itkBSplineDecompositionImageFilter:h|hxx -tinclude itkBSplineInterpolateImageFunction:h|hxx -instances itk::BSplineInterpolateImageFunction< itk::Image< #scalar_types#, #pdims# >, #real_types#, #real_types# > -instances itk::BSplineDecompositionImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #real_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITKImages.i b/lib/cpInstances/Images/ITKImages.i deleted file mode 100644 index 33f5852..0000000 --- a/lib/cpInstances/Images/ITKImages.i +++ /dev/null @@ -1,41 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkImportImageContainer:h|hxx -tinclude itkImage:h|hxx - -define base_objects=ImageRegion;ImageBase -tinclude itk#base_objects#:h|hxx -instances itk::#base_objects#< #pdims# > - -minstances #_export_# std::ostream& itk::operator<< < #pdims# >( std::ostream& a, itk::ImageRegion< #pdims# > const& b ) - -define color_pixels=RGBPixel;RGBAPixel -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# >;std::complex< #real_types# >;#sint_types# -cinclude itk#color_pixels#.h -cinclude complex -instances itk::ImportImageContainer< unsigned long, #pixels# > -instances itk::Image< #pixels#, #pdims# > - -cinclude itkFixedArray.h -instances itk::ImportImageContainer< unsigned long, itk::FixedArray< #scalar_types#, #pdims# > > -instances itk::Image< itk::FixedArray< #scalar_types#, #pdims# >, #pdims# > - -define vector_pixels=CovariantVector;Point;Vector;SymmetricSecondRankTensor -cinclude itk#vector_pixels#.h -instances itk::ImportImageContainer< unsigned long, itk::#vector_pixels#< #real_types#, #pdims# > > -instances itk::Image< itk::#vector_pixels#< #real_types#, #pdims# >, #pdims# > - -define matrices=Matrix -cinclude itk#matrices#.h -instances itk::ImportImageContainer< unsigned long, itk::#matrices#< #real_types#, #pdims#, #pdims# > > -instances itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > - -cinclude itkOffset.h -instances itk::ImportImageContainer< unsigned long, itk::Offset< #pdims# > > -instances itk::Image< itk::Offset< #pdims# >, #pdims# > - -cinclude itkDiffusionTensor3D.h -instances itk::ImportImageContainer< unsigned long, itk::DiffusionTensor3D< #real_types# > > -instances itk::Image< itk::DiffusionTensor3D< #real_types# >, 3 > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITKImagesBaseFilters.i b/lib/cpInstances/Images/ITKImagesBaseFilters.i deleted file mode 100644 index f29b580..0000000 --- a/lib/cpInstances/Images/ITKImagesBaseFilters.i +++ /dev/null @@ -1,58 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define color_pixels=RGBPixel;RGBAPixel -define vector_pixels=CovariantVector;Point;Vector;SymmetricSecondRankTensor -define matrices=Matrix -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# >;std::complex< #real_types# > - -cinclude complex -cinclude itkImage.h -cinclude itk#color_pixels#.h -cinclude itkFixedArray.h -cinclude itk#vector_pixels#.h -cinclude itk#matrices#.h -cinclude itkDiffusionTensor3D.h - -tinclude itkImageSource:h|hxx -instances itk::ImageSource< itk::Image< #pixels#, #pdims# > > -instances itk::ImageSource< itk::Image< itk::FixedArray< #scalar_types#, #pdims# >, #pdims# > > -instances itk::ImageSource< itk::Image< itk::#vector_pixels#< #real_types#, #pdims# >, #pdims# > > -instances itk::ImageSource< itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > > -instances itk::ImageSource< itk::Image< itk::Offset< #pdims# >, #pdims# > > -instances itk::ImageSource< itk::Image< itk::DiffusionTensor3D< #real_types# >, 3 > > - -define i_pixels=#pixels# -define o_pixels=#pixels# -define i_scalar_types=#scalar_types# -define o_scalar_types=#scalar_types# -define i_real_types=#real_types# -define o_real_types=#real_types# -define filters=ImageToImageFilter;InPlaceImageFilter -tinclude itk#filters#:h|hxx -instances itk::#filters#< itk::Image< #i_pixels#, #pdims# >, itk::Image< #o_pixels#, #pdims# > > -instances itk::#filters#< itk::Image< itk::FixedArray< #i_scalar_types#, #pdims# >, #pdims# >, itk::Image< itk::FixedArray< #o_scalar_types#, #pdims# >, #pdims# > > -instances itk::#filters#< itk::Image< itk::#vector_pixels#< #i_real_types#, #pdims# >, #pdims# >, itk::Image< itk::#vector_pixels#< #o_real_types#, #pdims# >, #pdims# > > -instances itk::#filters#< itk::Image< itk::#matrices#< #i_real_types#, #pdims#, #pdims# >, #pdims# >, itk::Image< itk::#matrices#< #o_real_types#, #pdims#, #pdims# >, #pdims# > > - -define i_dims=#pdims# -define o_dims=#pdims# -instances itk::#filters#< itk::Image< #pixels#, #i_dims# >, itk::Image< #pixels#, #o_dims# > > - -tinclude itkImageAlgorithm:h|hxx -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< #i_scalar_types#, #pdims# >, itk::Image< #o_scalar_types#, #pdims# > >( itk::Image< #i_scalar_types#, #pdims# > const*, itk::Image< #o_scalar_types#, #pdims# >*, itk::Image< #i_scalar_types#, #pdims# >::RegionType const&, itk::Image< #o_scalar_types#, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< std::complex< #i_real_types# >, #pdims# >, itk::Image< std::complex< #o_real_types# >, #pdims# > >( itk::Image< std::complex< #i_real_types# >, #pdims# > const*, itk::Image< std::complex< #o_real_types# >, #pdims# >*, itk::Image< std::complex< #i_real_types# >, #pdims# >::RegionType const&, itk::Image< std::complex< #o_real_types# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::#color_pixels#< #i_scalar_types# >, #pdims# >, itk::Image< itk::#color_pixels#< #o_scalar_types# >, #pdims# > >( itk::Image< itk::#color_pixels#< #i_scalar_types# >, #pdims# > const*, itk::Image< itk::#color_pixels#< #o_scalar_types# >, #pdims# >*, itk::Image< itk::#color_pixels#< #i_scalar_types# >, #pdims# >::RegionType const&, itk::Image< itk::#color_pixels#< #o_scalar_types# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::FixedArray< #i_scalar_types#, #pdims# >, #pdims# >, itk::Image< itk::FixedArray< #o_scalar_types#, #pdims# >, #pdims# > >( itk::Image< itk::FixedArray< #i_scalar_types#, #pdims# >, #pdims# > const*, itk::Image< itk::FixedArray< #o_scalar_types#, #pdims# >, #pdims# >*, itk::Image< itk::FixedArray< #i_scalar_types#, #pdims# >, #pdims# >::RegionType const&, itk::Image< itk::FixedArray< #o_scalar_types#, #pdims# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::#vector_pixels#< #i_real_types#, #pdims# >, #pdims# >, itk::Image< itk::#vector_pixels#< #o_real_types#, #pdims# >, #pdims# > >( itk::Image< itk::#vector_pixels#< #i_real_types#, #pdims# >, #pdims# > const*, itk::Image< itk::#vector_pixels#< #o_real_types#, #pdims# >, #pdims# >*, itk::Image< itk::#vector_pixels#< #i_real_types#, #pdims# >, #pdims# >::RegionType const&, itk::Image< itk::#vector_pixels#< #o_real_types#, #pdims# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# >, itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > >( itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > const*, itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# >*, itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# >::RegionType const&, itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::Offset< #pdims# >, #pdims# >, itk::Image< itk::Offset< #pdims# >, #pdims# > >( itk::Image< itk::Offset< #pdims# >, #pdims# > const*, itk::Image< itk::Offset< #pdims# >, #pdims# >*, itk::Image< itk::Offset< #pdims# >, #pdims# >::RegionType const&, itk::Image< itk::Offset< #pdims# >, #pdims# >::RegionType const&, std::integral_constant< bool, true > ) - -minstances void #_export_# itk::ImageAlgorithm::DispatchedCopy< itk::Image< itk::DiffusionTensor3D< #i_real_types# >, 3 >, itk::Image< itk::DiffusionTensor3D< #o_real_types# >, 3 > >( itk::Image< itk::DiffusionTensor3D< #i_real_types# >, 3 > const*, itk::Image< itk::DiffusionTensor3D< #o_real_types# >, 3 >*, itk::Image< itk::DiffusionTensor3D< #i_real_types# >, 3 >::RegionType const&, itk::Image< itk::DiffusionTensor3D< #o_real_types# >, 3 >::RegionType const&, std::integral_constant< bool, true > ) - -** eof - $RCSfile$ \ No newline at end of file diff --git a/lib/cpInstances/Images/ITKImagesNeighborhoodIterators.i b/lib/cpInstances/Images/ITKImagesNeighborhoodIterators.i deleted file mode 100644 index e18b3b9..0000000 --- a/lib/cpInstances/Images/ITKImagesNeighborhoodIterators.i +++ /dev/null @@ -1,38 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define color_pixels=RGBPixel;RGBAPixel -define vector_pixels=CovariantVector;Point;Vector;SymmetricSecondRankTensor -define matrices=Matrix -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# > - -cinclude itkImage.h -cinclude itk#color_pixels#.h -cinclude itkFixedArray.h -cinclude itk#vector_pixels#.h -cinclude itk#matrices#.h - -define it=ConstNeighborhoodIterator;NeighborhoodIterator;ConstShapedNeighborhoodIterator;ShapedNeighborhoodIterator -define co=ZeroFluxNeumannBoundaryCondition -define pi=#scalar_types#;#sint_types# -define op=Neighborhood;NeighborhoodOperator;DerivativeOperator - -tinclude itk#co#:h|hxx -tinclude itk#op#:h|hxx -tinclude itk#it#:h|hxx - -instances itk::NeighborhoodAllocator< #scalar_types#* > -instances itk::NeighborhoodAllocator< #pi# > -instances itk::Neighborhood< #scalar_types#*, #pdims#, itk::NeighborhoodAllocator< #scalar_types#* > > -instances itk::Neighborhood< signed char*, #pdims#, itk::NeighborhoodAllocator< signed char* > > - -instances itk::#op#< #pi#, #pdims#, itk::NeighborhoodAllocator< #pi# > > -instances itk::#co#< itk::Image< #pi#, #pdims# >, itk::Image< #pi#, #pdims# > > -instances itk::#it#< itk::Image< #pi#, #pdims# >, itk::#co#< itk::Image< #pi#, #pdims# >, itk::Image< #pi#, #pdims# > > > - -tinclude itkNeighborhoodAlgorithm:h|hxx -instances itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< itk::Image< #pi#, #pdims# > > - -tinclude itkNeighborhoodInnerProduct:h|hxx -instances itk::NeighborhoodInnerProduct< itk::Image< #pi#, #pdims# >, #pi#, #pi# > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/ITKImagesSimpleIterators.i b/lib/cpInstances/Images/ITKImagesSimpleIterators.i deleted file mode 100644 index e787093..0000000 --- a/lib/cpInstances/Images/ITKImagesSimpleIterators.i +++ /dev/null @@ -1,27 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define color_pixels=RGBPixel;RGBAPixel -define vector_pixels=CovariantVector;Point;Vector;SymmetricSecondRankTensor -define matrices=Matrix -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# >;std::complex< #real_types# >;#sint_types# - -cinclude itkImage.h -cinclude itk#color_pixels#.h -cinclude itkFixedArray.h -cinclude itk#vector_pixels#.h -cinclude itk#matrices#.h -cinclude itkDiffusionTensor3D.h - -define it=ImageRegionConstIterator;ImageRegionIterator;ImageScanlineConstIterator;ImageScanlineIterator;ImageConstIteratorWithIndex;ImageIteratorWithIndex;ImageRegionConstIteratorWithIndex;ImageRegionIteratorWithIndex;ImageLinearConstIteratorWithIndex;ImageLinearIteratorWithIndex - -tinclude itk#it#:h|hxx - -tinclude itk#it#:h|hxx -instances itk::#it#< itk::Image< #pixels#, #pdims# > > -instances itk::#it#< itk::Image< itk::FixedArray< #scalar_types#, #pdims# >, #pdims# > > -instances itk::#it#< itk::Image< itk::#vector_pixels#< #real_types#, #pdims# >, #pdims# > > -instances itk::#it#< itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > > -instances itk::#it#< itk::Image< itk::Offset< #pdims# >, #pdims# > > -instances itk::#it#< itk::Image< itk::DiffusionTensor3D< #real_types# >, 3 > > - -** eof - $RCSfile$ diff --git a/lib/cpInstances/Images/itkImageToVTKImageFilter.h b/lib/cpInstances/Images/itkImageToVTKImageFilter.h deleted file mode 100644 index 9390eb8..0000000 --- a/lib/cpInstances/Images/itkImageToVTKImageFilter.h +++ /dev/null @@ -1,111 +0,0 @@ -/*========================================================================= - * - * Copyright Insight Software Consortium - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0.txt - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - *=========================================================================*/ -#ifndef itkImageToVTKImageFilter_h -#define itkImageToVTKImageFilter_h - -#include "itkVTKImageExport.h" -#include "vtkImageImport.h" -#include "vtkImageData.h" - -namespace itk -{ - -/** \class ImageToVTKImageFilter - * \brief Converts an ITK image into a VTK image and plugs a - * itk data pipeline to a VTK datapipeline. - * - * This class puts together an itkVTKImageExporter and a vtkImageImporter. - * It takes care of the details related to the connection of ITK and VTK - * pipelines. The User will perceive this filter as an adaptor to which - * an itk::Image can be plugged as input and a vtkImage is produced as - * output. - * - * \ingroup ITKVtkGlue - * - * \wiki - * \wikiexample{IO/ImageToVTKImageFilter,Display an ITK image} - * \wikiexample{IO/itkVtkImageConvertDICOM,Uses a custom user matrix to align the image with DICOM physical space} - * \endwiki - */ -template -class ImageToVTKImageFilter : public ProcessObject -{ -public: - /** Standard class typedefs. */ - typedef ImageToVTKImageFilter Self; - typedef ProcessObject Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(ImageToVTKImageFilter, ProcessObject); - - /** Some typedefs. */ - typedef TInputImage InputImageType; - typedef typename InputImageType::ConstPointer InputImagePointer; - - typedef VTKImageExport< InputImageType> ExporterFilterType; - typedef typename ExporterFilterType::Pointer ExporterFilterPointer; - - /** Get the output in the form of a vtkImage. - This call is delegated to the internal vtkImageImporter filter */ - vtkImageData * GetOutput() const; - - /** Set the input in the form of an itk::Image */ - using Superclass::SetInput; - void SetInput( const InputImageType * ); - InputImageType * GetInput(); - - /** Return the internal VTK image importer filter. - This is intended to facilitate users the access - to methods in the importer */ - vtkImageImport * GetImporter() const; - - /** Return the internal ITK image exporter filter. - This is intended to facilitate users the access - to methods in the exporter */ - ExporterFilterType * GetExporter() const; - - /** This call delegates the update to the importer */ - virtual void Update() ITK_OVERRIDE; - - /** This call delegates the update to the importer */ - virtual void UpdateLargestPossibleRegion() ITK_OVERRIDE; - -protected: - ImageToVTKImageFilter(); - virtual ~ImageToVTKImageFilter(); - -private: - ImageToVTKImageFilter(const Self&) ITK_DELETE_FUNCTION; - void operator=(const Self&) ITK_DELETE_FUNCTION; - - ExporterFilterPointer m_Exporter; - vtkImageImport * m_Importer; -}; - -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkImageToVTKImageFilter.hxx" -#endif - -#endif diff --git a/lib/cpInstances/Images/itkImageToVTKImageFilter.hxx b/lib/cpInstances/Images/itkImageToVTKImageFilter.hxx deleted file mode 100644 index e134b3f..0000000 --- a/lib/cpInstances/Images/itkImageToVTKImageFilter.hxx +++ /dev/null @@ -1,141 +0,0 @@ -/*========================================================================= - * - * Copyright Insight Software Consortium - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0.txt - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - *=========================================================================*/ -#ifndef itkImageToVTKImageFilter_hxx -#define itkImageToVTKImageFilter_hxx - -#include "itkImageToVTKImageFilter.h" - -namespace itk -{ - -/** - * Constructor - */ -template -ImageToVTKImageFilter -::ImageToVTKImageFilter() -{ - m_Importer = vtkImageImport::New(); - m_Exporter = ExporterFilterType::New(); - - m_Importer->SetUpdateInformationCallback(m_Exporter->GetUpdateInformationCallback()); - m_Importer->SetPipelineModifiedCallback(m_Exporter->GetPipelineModifiedCallback()); - m_Importer->SetWholeExtentCallback(m_Exporter->GetWholeExtentCallback()); - m_Importer->SetSpacingCallback(m_Exporter->GetSpacingCallback()); - m_Importer->SetOriginCallback(m_Exporter->GetOriginCallback()); - m_Importer->SetScalarTypeCallback(m_Exporter->GetScalarTypeCallback()); - m_Importer->SetNumberOfComponentsCallback(m_Exporter->GetNumberOfComponentsCallback()); - m_Importer->SetPropagateUpdateExtentCallback(m_Exporter->GetPropagateUpdateExtentCallback()); - m_Importer->SetUpdateDataCallback(m_Exporter->GetUpdateDataCallback()); - m_Importer->SetDataExtentCallback(m_Exporter->GetDataExtentCallback()); - m_Importer->SetBufferPointerCallback(m_Exporter->GetBufferPointerCallback()); - m_Importer->SetCallbackUserData(m_Exporter->GetCallbackUserData()); - -} - -/** - * Destructor - */ -template -ImageToVTKImageFilter -::~ImageToVTKImageFilter() -{ - if( m_Importer ) - { - m_Importer->Delete(); - m_Importer = 0; - } -} - -/** - * Set an itk::Image as input - */ -template -void -ImageToVTKImageFilter -::SetInput( const InputImageType * inputImage ) -{ - m_Exporter->SetInput( inputImage ); -} - -template -typename ImageToVTKImageFilter::InputImageType * -ImageToVTKImageFilter -::GetInput() -{ - return m_Exporter->GetInput(); -} - -/** - * Get a vtkImage as output - */ -template -vtkImageData * -ImageToVTKImageFilter -::GetOutput() const -{ - return m_Importer->GetOutput(); -} - -/** - * Get the importer filter - */ -template -vtkImageImport * -ImageToVTKImageFilter -::GetImporter() const -{ - return m_Importer; -} - -/** - * Get the exporter filter - */ -template -typename ImageToVTKImageFilter::ExporterFilterType * -ImageToVTKImageFilter -::GetExporter() const -{ - return m_Exporter.GetPointer(); -} - -/** - * Delegate the Update to the importer - */ -template -void -ImageToVTKImageFilter -::Update() -{ - m_Importer->Update(); -} - -/** - * Delegate the UpdateLargestPossibleRegion to the importer - */ -template -void -ImageToVTKImageFilter -::UpdateLargestPossibleRegion() -{ - m_Importer->UpdateWholeExtent(); -} - -} // end namespace itk - -#endif diff --git a/lib/cpInstances/Images/itkVTKImageToImageFilter.h b/lib/cpInstances/Images/itkVTKImageToImageFilter.h deleted file mode 100644 index b4427c8..0000000 --- a/lib/cpInstances/Images/itkVTKImageToImageFilter.h +++ /dev/null @@ -1,100 +0,0 @@ -/*========================================================================= - * - * Copyright Insight Software Consortium - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0.txt - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - *=========================================================================*/ - -#ifndef itkVTKImageToImageFilter_h -#define itkVTKImageToImageFilter_h - -#include "itkVTKImageImport.h" -#include "vtkImageExport.h" -#include "vtkImageData.h" -#include "vtkSmartPointer.h" - -#ifndef vtkFloatingPointType -#define vtkFloatingPointType float -#endif - -namespace itk -{ - -/** \class VTKImageToImageFilter - * \brief Converts a VTK image into an ITK image and plugs a - * VTK data pipeline to an ITK datapipeline. - * - * This class puts together an itk::VTKImageImport and a vtk::ImageExport. - * It takes care of the details related to the connection of ITK and VTK - * pipelines. The User will perceive this filter as an adaptor to which - * a vtkImageData can be plugged as input and an itk::Image is produced as - * output. - * - * \ingroup ITKVtkGlue - */ -template -class VTKImageToImageFilter : public VTKImageImport< TOutputImage > -{ -public: - /** Standard class typedefs. */ - typedef VTKImageToImageFilter Self; - typedef VTKImageImport< TOutputImage > Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(VTKImageToImageFilter, VTKImageImport); - - /** Some typedefs. */ - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::ConstPointer OutputImagePointer; - - /** Set the input in the form of a vtkImageData */ - void SetInput( vtkImageData * ); - using Superclass::SetInput; - - /** Return the internal VTK image exporter filter. - This is intended to facilitate users the access - to methods in the exporter */ - vtkImageExport * GetExporter() const; - - /** Return the internal ITK image importer filter. - This is intended to facilitate users the access - to methods in the importer. - */ - const Superclass * GetImporter() const; - -protected: - VTKImageToImageFilter(); - virtual ~VTKImageToImageFilter(); - -private: - VTKImageToImageFilter(const Self&) ITK_DELETE_FUNCTION; - void operator=(const Self&) ITK_DELETE_FUNCTION; - - typedef vtkSmartPointer ImageExportPointer; - ImageExportPointer m_Exporter; - -}; - -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkVTKImageToImageFilter.hxx" -#endif - -#endif diff --git a/lib/cpInstances/Images/itkVTKImageToImageFilter.hxx b/lib/cpInstances/Images/itkVTKImageToImageFilter.hxx deleted file mode 100644 index 334b02b..0000000 --- a/lib/cpInstances/Images/itkVTKImageToImageFilter.hxx +++ /dev/null @@ -1,107 +0,0 @@ -/*========================================================================= - * - * Copyright Insight Software Consortium - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0.txt - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - *=========================================================================*/ - -#ifndef itkVTKImageToImageFilter_hxx -#define itkVTKImageToImageFilter_hxx - -#include "itkVTKImageToImageFilter.h" - -#include "vtkVersion.h" - -namespace itk -{ - -/** - * Constructor - */ -template -VTKImageToImageFilter -::VTKImageToImageFilter() -{ - - m_Exporter = vtkImageExport::New(); - - this->SetUpdateInformationCallback( m_Exporter->GetUpdateInformationCallback()); - this->SetPipelineModifiedCallback( m_Exporter->GetPipelineModifiedCallback()); - this->SetWholeExtentCallback( m_Exporter->GetWholeExtentCallback()); - this->SetSpacingCallback( m_Exporter->GetSpacingCallback()); - this->SetOriginCallback( m_Exporter->GetOriginCallback()); - this->SetScalarTypeCallback( m_Exporter->GetScalarTypeCallback()); - this->SetNumberOfComponentsCallback( m_Exporter->GetNumberOfComponentsCallback()); - this->SetPropagateUpdateExtentCallback( m_Exporter->GetPropagateUpdateExtentCallback()); - this->SetUpdateDataCallback( m_Exporter->GetUpdateDataCallback()); - this->SetDataExtentCallback( m_Exporter->GetDataExtentCallback()); - this->SetBufferPointerCallback( m_Exporter->GetBufferPointerCallback()); - this->SetCallbackUserData( m_Exporter->GetCallbackUserData()); - -} - -/** - * Destructor - */ -template -VTKImageToImageFilter -::~VTKImageToImageFilter() -{ - if( m_Exporter ) - { - m_Exporter->Delete(); - m_Exporter = 0; - } -} - -/** - * Set a vtkImageData as input - */ -template -void -VTKImageToImageFilter -::SetInput( vtkImageData * inputImage ) -{ -#if VTK_MAJOR_VERSION <= 5 - m_Exporter->SetInput( inputImage ); -#else - m_Exporter->SetInputData( inputImage ); -#endif -} - -/** - * Get the exporter filter - */ -template -vtkImageExport * -VTKImageToImageFilter -::GetExporter() const -{ - return m_Exporter; -} - -/** - * Get the importer filter - */ -template -const typename VTKImageToImageFilter::Superclass * -VTKImageToImageFilter -::GetImporter() const -{ - return this; -} - -} // end namespace itk - -#endif diff --git a/lib/cpPlugins/Config.h.in b/lib/cpPlugins/Config.h.in deleted file mode 100644 index 4e58a1d..0000000 --- a/lib/cpPlugins/Config.h.in +++ /dev/null @@ -1,134 +0,0 @@ -#ifndef __cpPlugins__Config__h__ -#define __cpPlugins__Config__h__ - -#include -#include -#include - -/* - * ========================================================================= - * Identify OS - * ========================================================================= - */ -#define cpPlugins_OS_@CMAKE_SYSTEM_NAME@ -#ifdef cpPlugins_OS_Windows -# define cpPlugins_LIB_PREFIX "" -# define cpPlugins_ENV_SEPARATOR ";" -# define cpPlugins_PATH_SEPARATOR '\\' -# define cpPlugins_LIB_EXT ".dll" -#else // cpPlugins_OS_Windows -# define cpPlugins_LIB_PREFIX "lib" -# define cpPlugins_ENV_SEPARATOR ":" -# define cpPlugins_PATH_SEPARATOR '/' -# ifdef cpPlugins_OS_Linux -# define cpPlugins_LIB_EXT ".so" -# else // cpPlugins_OS_Linux -# define cpPlugins_LIB_EXT ".dylib" -# endif // cpPlugins_OS_Linux -#endif // cpPlugins_OS_Windows - -#ifdef cpPlugins_OS_Windows -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif // WIN32_LEAN_AND_MEAN -# define NOMINMAX -# include -# include -#endif // cpPlugins_OS_Windows - -/* - * ========================================================================= - * Some global values - * ========================================================================= - */ -#define cpPlugins_PATHS "cpPlugins_PATHS" -#define cpPlugins_CONFIG "cpPlugins_Libraries.config" - -#define cpPlugins_QT4_@QT4_FOUND@ -#ifdef cpPlugins_QT4_TRUE -# ifndef cpPlugins_QT4 -# define cpPlugins_QT4 -# endif // cpPlugins_QT4 -#else // cpPlugins_QT4_TRUE -# undef cpPlugins_QT4 -#endif // cpPlugins_QT4_TRUE - -/* - * ========================================================================= - * Version numbers and strings - * ========================================================================= - */ -#define cpPlugins_MAJOR_VERSION @prj_MAJ_VER@ -#define cpPlugins_MINOR_VERSION @prj_MIN_VER@ -#define cpPlugins_RELEASE_VERSION @prj_REL_VER@ -#define cpPlugins_VERSION "@prj_VERSION@" -#define cpPlugins_SHORT_VERSION "@prj_SHORT_VERSION@" -#define cpPlugins_OpenGL_BackEnd_@VTK_RENDERING_BACKEND@ - -/* - * ========================================================================= - * Language related macros - * ========================================================================= - */ -/* TODO - #if __cplusplus >= 201103L - # define override override - # define cpPlugins_DELETE_FUNCTION =delete - # define cpPlugins_NULLPTR nullptr - # define cpPlugins_NOEXCEPT noexcept - # define cpPlugins_HAS_CXX11_STATIC_ASSERT - # define cpPlugins_HAS_CXX11_RVREF - #else // __cplusplus >= 201103L - # define override - # define cpPlugins_DELETE_FUNCTION - # define cpPlugins_NULLPTR NULL - # define cpPlugins_NOEXCEPT throw() - #endif // __cplusplus >= 201103L -*/ - -/* - * ========================================================================= - * Some macros - * ========================================================================= - */ - -#define cpPlugins_Id_Macro( _class, _category ) \ - public: \ - virtual const char* GetClassName( ) const override \ - { return( #_class ); } \ - virtual const char* GetClassCategory( ) const override \ - { return( #_category ); } - -#define cpPluginsObject( _cls, _scls, _cat ) \ - public: \ - typedef _cls Self; \ - typedef _scls Superclass; \ - typedef itk::SmartPointer< Self > Pointer; \ - typedef itk::SmartPointer< const Self > ConstPointer; \ - public: \ - itkNewMacro( Self ); \ - itkTypeMacro( _cls, _scls ); \ - public: \ - virtual const char* GetClassName( ) const override \ - { return( #_cls ); } \ - virtual const char* GetClassCategory( ) const override \ - { return( #_cat ); } \ - protected: \ - _cls( ); \ - virtual ~_cls( ); \ - virtual void _GenerateData( ) override; \ - private: \ - _cls( const Self& ); \ - Self& operator=( const Self& ) - -#define cpPlugins_Compatibility_Macro \ - virtual bool IsCompatible( \ - const DataObject* other \ - ) const override \ - { \ - return( dynamic_cast< const Self* >( other ) != NULL ); \ - } - -#endif // __cpPlugins__Config__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Interface/Loader.cxx b/lib/cpPlugins/Interface/Loader.cxx deleted file mode 100644 index dfb9bfb..0000000 --- a/lib/cpPlugins/Interface/Loader.cxx +++ /dev/null @@ -1,278 +0,0 @@ -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -// Static attributes initialization -// ------------------------------------------------------------------------- - -cpPlugins::Interface::Loader::TLibraries -cpPlugins::Interface::Loader::m_Libraries; - -cpPlugins::Interface::Loader::TFiltersToLibrariesReferences -cpPlugins::Interface::Loader::m_References; - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Loader:: -Loader( ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Loader:: -~Loader( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -Register( const std::string& filename ) -{ - // Canonicalize path - std::string path = cpPlugins::OS::FileSystem::CanonicalPath( filename ); - if( path == "" ) - { - throw std::runtime_error( "Unknown library file \"" + filename + "\"." ); - return; - - } // fi - - // Ignore if the library is already loaded - if( Self::m_Libraries.find( path ) != Self::m_Libraries.end( ) ) - return; - - // Try to open library - void* hnd = NULL; - try - { - hnd = cpPlugins::OS::DLLManager::Open( path ); - } - catch( std::exception& err ) - { - throw std::runtime_error( err.what( ) ); - - } // yrt - if( hnd == NULL ) - throw std::runtime_error( "Unknown file type for \"" + filename + "\"." ); - - // Get interfacing functions - TContentsFunc contents_func = NULL; - try - { - contents_func = reinterpret_cast< TContentsFunc >( - cpPlugins::OS::DLLManager::Sym( hnd, "cpPlugins_Contents" ) - ); - } - catch( std::exception& err ) - { - cpPlugins::OS::DLLManager::Close( hnd ); - throw std::runtime_error( "Library \"" + filename + "\" is not recognized as a cpPlugins library (i.e. \"cpPlugins_Contents\" function not found)." ); - - } // yrt - - TCreatorFunc creator_func = NULL; - try - { - creator_func = reinterpret_cast< TCreatorFunc >( - cpPlugins::OS::DLLManager::Sym( hnd, "cpPlugins_Creator" ) - ); - } - catch( std::exception& err ) - { - cpPlugins::OS::DLLManager::Close( hnd ); - throw std::runtime_error( "Library \"" + filename + "\" is not recognized as a cpPlugins library (i.e. \"cpPlugins_Creator\" function not found)." ); - - } // yrt - - // Keep track of handlers - Self::m_Libraries[ path ] = THandlers( hnd, contents_func, creator_func ); - - // Get library contents - std::vector< std::string > contents; - contents_func( &contents ); - - // Register contents - for( auto c : contents ) - { - std::vector< std::string > t = cpPlugins::OS::String::Tokenize( c, "@" ); - if( t.size( ) == 2 ) - Self::m_References[ t[ 1 ] ][ t[ 0 ] ] = path; - - } // rof -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -RegisterFromDirectory( const std::string& dirname ) -{ - std::string patt = "*"; - patt += cpPlugins_LIB_EXT; - std::set< std::string > files = - cpPlugins::OS::FileSystem::LoadDirContents( - dirname, false, patt - ); - for( auto f : files ) - { - try - { - Register( f ); - } - catch( ... ) - { - // Do nothing - - } // yrt - - } // rof -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -GuessEnvironment( const std::string& dirname ) -{ - std::stringstream fname; - fname << dirname << cpPlugins_PATH_SEPARATOR << cpPlugins_PATHS; - std::string buffer; - if( cpPlugins::OS::FileSystem::Read( buffer, fname.str( ) ) ) - { - std::istringstream input( buffer ); - for( std::string line; std::getline( input, line ); ) - Self::RegisterFromDirectory( line ); - } - else - Self::RegisterFromDirectory( dirname ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -SaveEnvironment( const std::string& dirname ) -{ - std::set< std::string > locations; - for( auto lIt : Self::m_Libraries ) - locations.insert( - cpPlugins::OS::FileSystem::SplitPath( lIt.first ).first - ); - std::stringstream buffer; - for( auto loc : locations ) - buffer << loc << std::endl; - std::stringstream fname; - fname << dirname << cpPlugins_PATH_SEPARATOR << cpPlugins_PATHS; - cpPlugins::OS::FileSystem::Write( buffer.str( ), fname.str( ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -UnRegister( const std::string& filename ) -{ - // Canonicalize path - std::string path = cpPlugins::OS::FileSystem::CanonicalPath( filename ); - if( path == "" ) - return; - - auto lIt = Self::m_Libraries.find( path ); - if( lIt != Self::m_Libraries.end( ) ) - { - // Unload handlers - cpPlugins::OS::DLLManager::Close( std::get< 0 >( lIt->second ) ); - Self::m_Libraries.erase( lIt ); - - // Erase references - auto cIt = Self::m_References.begin( ); - while( cIt != Self::m_References.end( ) ) - { - auto fIt = cIt->second.begin( ); - while( fIt != cIt->second.end( ) ) - { - if( fIt->second == path ) - { - cIt->second.erase( fIt ); - fIt = cIt->second.begin( ); - } - else - ++fIt; - - } // elihw - if( cIt->second.size( ) == 0 ) - { - Self::m_References.erase( cIt ); - cIt = Self::m_References.begin( ); - } - else - ++cIt; - - } // elihw - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Loader:: -UnRegisterAll( ) -{ - for( auto lIt : Self::m_Libraries ) - cpPlugins::OS::DLLManager::Close( std::get< 0 >( lIt.second ) ); - Self::m_Libraries.clear( ); - Self::m_References.clear( ); -} - -// ------------------------------------------------------------------------- -std::map< std::string, std::set< std::string > > -cpPlugins::Interface::Loader:: -GetFilters( ) const -{ - std::map< std::string, std::set< std::string > > filters; - for( auto ref : Self::m_References ) - for( auto fil : ref.second ) - filters[ ref.first ].insert( fil.first ); - return( filters ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject::Pointer cpPlugins::Interface::Loader:: -CreateFilter( - const std::string& category, const std::string& filter, - const std::string& name - ) -{ - cpPlugins::Pipeline::ProcessObject::Pointer ptr = NULL; - auto cIt = Self::m_References.find( category ); - if( cIt != Self::m_References.end( ) ) - { - auto fIt = cIt->second.find( filter ); - if( fIt != cIt->second.end( ) ) - { - auto lIt = Self::m_Libraries.find( fIt->second ); - if( lIt != Self::m_Libraries.end( ) ) - { - auto creator_func = std::get< 2 >( lIt->second ); - if( creator_func != NULL ) - { - itk::LightObject::Pointer l_ptr; - creator_func( l_ptr, category, filter ); - ptr = - dynamic_cast< cpPlugins::Pipeline::ProcessObject* >( - l_ptr.GetPointer( ) - ); - - } // fi - - } // fi - - } // fi - - } // fi - - if( ptr.IsNotNull( ) ) - { - if( name == "" ) - ptr->SetName( filter + "@" + category ); - else - ptr->SetName( name ); - - } // fi - return( ptr ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Interface/Loader.h b/lib/cpPlugins/Interface/Loader.h deleted file mode 100644 index 84a1819..0000000 --- a/lib/cpPlugins/Interface/Loader.h +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef __cpPlugins__Interface__Loader__h__ -#define __cpPlugins__Interface__Loader__h__ - -#include -#include -#include -#include -#include - -namespace cpPlugins -{ - namespace Interface - { - /** - */ - class cpPlugins_EXPORT Loader - { - public: - typedef Loader Self; - - public: - typedef void ( *TContentsFunc )( std::vector< std::string >* ); - typedef void ( *TCreatorFunc )( itk::LightObject::Pointer& ptr, const std::string& c, const std::string& f ); - typedef std::tuple< void*, TContentsFunc, TCreatorFunc > THandlers; - typedef std::map< std::string, THandlers > TLibraries; - typedef std::map< std::string, std::map< std::string, std::string > > TFiltersToLibrariesReferences; - - public: - Loader( ); - virtual ~Loader( ); - - void Register( const std::string& filename ); - void RegisterFromDirectory( const std::string& dirname ); - void GuessEnvironment( const std::string& dirname ); - void SaveEnvironment( const std::string& dirname ); - void UnRegister( const std::string& filename ); - void UnRegisterAll( ); - - std::map< std::string, std::set< std::string > > GetFilters( ) const; - - cpPlugins::Pipeline::ProcessObject::Pointer CreateFilter( - const std::string& category, const std::string& filter, - const std::string& name = "" - ); - - protected: - static TLibraries m_Libraries; - static TFiltersToLibrariesReferences m_References; - - public: - friend std::ostream& operator<<( std::ostream& o, const Loader& l ) - { - o << "cpPlugins:" << std::endl; - for( auto c : l.m_References ) - { - o << " + " << c.first << std::endl; - for( auto f : c.second ) - o << " |--> " << f.first << " (" << f.second << ")" << std::endl; - - } // rof - return( o ); - } - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Interface__Loader__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Interface/Workspace.cxx b/lib/cpPlugins/Interface/Workspace.cxx deleted file mode 100644 index 4fbcb2b..0000000 --- a/lib/cpPlugins/Interface/Workspace.cxx +++ /dev/null @@ -1,638 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Clear( ) -{ - this->m_Filters.clear( ); -} - -// ------------------------------------------------------------------------- -std::vector< std::string > cpPlugins::Interface::Workspace:: -GetFiltersNames( ) const -{ - std::vector< std::string > n; - for( auto i : this->m_Filters ) - n.push_back( i.first ); - return( n ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -TFilter* cpPlugins::Interface::Workspace:: -GetFilter( const std::string& name ) -{ - auto i = this->m_Filters.find( name ); - if( i != this->m_Filters.end( ) ) - return( i->second.GetPointer( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Interface::Workspace:: -TFilter* cpPlugins::Interface::Workspace:: -GetFilter( const std::string& name ) const -{ - auto i = this->m_Filters.find( name ); - if( i != this->m_Filters.end( ) ) - return( i->second.GetPointer( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -TWidget* cpPlugins::Interface::Workspace:: -GetWidget( const std::string& name ) -{ - TFilter* process = this->GetFilter( name ); - return( dynamic_cast< TWidget* >( process ) ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Interface::Workspace:: -TWidget* cpPlugins::Interface::Workspace:: -GetWidget( const std::string& name ) const -{ - const TFilter* process = this->GetFilter( name ); - return( dynamic_cast< const TWidget* >( process ) ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -HasFilter( const std::string& name ) const -{ - return( this->m_Filters.find( name ) != this->m_Filters.end( ) ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -HasWidget( const std::string& name ) const -{ - const TWidget* wdg = this->GetWidget( name ); - return( wdg != NULL ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -TFilter* cpPlugins::Interface::Workspace:: -CreateFilter( - const std::string& category, const std::string& filter, - const std::string& name - ) -{ - typedef cpPlugins::Pipeline::Widget _TWidget; - - TFilter::Pointer o = this->m_Loader.CreateFilter( category, filter ); - if( o.IsNotNull( ) ) - { - // Choose a name - std::string real_name = name; - while( this->GetFilter( real_name ) != NULL ) - real_name += std::string( "_" ); - o->SetPrintExecution( this->m_PrintExecution ); - o->SetName( real_name ); - - // Interactors - for( - auto i = this->m_Interactors.begin( ); - i != this->m_Interactors.end( ); - ++i - ) - o->AddInteractor( *i ); - - // Finish association - this->m_Filters[ real_name ] = o; - - } // fi - return( o.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -TFilter* cpPlugins::Interface::Workspace:: -CreateFilter( const std::string& category, const std::string& filter ) -{ - return( this->CreateFilter( category, filter, filter ) ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -RenameFilter( const std::string& old_name, const std::string& new_name ) -{ - auto o = this->m_Filters.find( old_name ); - auto n = this->m_Filters.find( new_name ); - if( o != this->m_Filters.end( ) && n == this->m_Filters.end( ) ) - { - // Rename filter - o->second->SetName( new_name ); - this->m_Filters[ new_name ] = o->second; - this->m_Filters.erase( o ); - - // Rename exposed ports - /* TODO - auto e = this->m_ExposedInputs.begin( ); - for( ; e != this->m_ExposedInputs.end( ); ++e ) - if( e->second.first == old_name ) - e->second.first = new_name; - e = this->m_ExposedOutputs.begin( ); - for( ; e != this->m_ExposedOutputs.end( ); ++e ) - if( e->second.first == old_name ) - e->second.first = new_name; - */ - - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -RemoveFilter( const std::string& name ) -{ - auto i = this->m_Filters.find( name ); - if( i != this->m_Filters.end( ) ) - { - i->second->Disconnect( ); - this->m_Filters.erase( i ); - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -SetPrintExecution( bool b ) -{ - this->m_PrintExecution = b; - for( auto i = this->m_Filters.begin( ); i != this->m_Filters.end( ); ++i ) - i->second->SetPrintExecution( b ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -PrintExecutionOn( ) -{ - this->SetPrintExecution( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -PrintExecutionOff( ) -{ - this->SetPrintExecution( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -AddInteractor( vtkRenderWindowInteractor* iren ) -{ - if( iren != NULL ) - { - this->m_Interactors.insert( iren ); - for( auto f : this->m_Filters ) - f.second->AddInteractor( iren ); - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -Connect( - const std::string& origin_filter, - const std::string& origin_output, - const std::string& destination_filter, - const std::string& destination_input - ) -{ - // Get filters and check pertinence - TFilter* origin = this->GetFilter( origin_filter ); - TFilter* destination = this->GetFilter( destination_filter ); - if( origin == NULL || destination == NULL ) - return( false ); - if( !( destination->HasInput( destination_input ) ) ) - return( false ); - if( !( origin->HasOutput( origin_output ) ) ) - return( false ); - - // Check if there is room for a new connection - bool ok = true; - if( destination->IsInputMultiple( destination_input ) ) - { - for( - unsigned int i = 0; - i < destination->GetInputSize( destination_input ); - ++i - ) - if( - destination->GetInput( destination_input, i )->GetSource( ) == origin - ) - ok = false; - } - else - ok = ( destination->GetInput( destination_input ) == NULL ); - if( ok ) - destination->AddInput( - destination_input, - origin->GetOutput( origin_output ) - ); - return( ok ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -Connect( - TDataObject* input, - const std::string& destination_filter, - const std::string& destination_input - ) -{ - // Get filters and check pertinence - if( input == NULL ) - return( false ); - TFilter* destination = this->GetFilter( destination_filter ); - if( destination == NULL ) - return( false ); - if( !( destination->HasInput( destination_input ) ) ) - return( false ); - - // Check if there is room for a new connection - bool ok = true; - if( destination->IsInputMultiple( destination_input ) ) - { - for( - unsigned int i = 0; - i < destination->GetInputSize( destination_input ); - ++i - ) - if( - destination->GetInput( destination_input, i )->GetSource( ) == - input->GetSource( ) - ) - ok = false; - } - else - ok = ( destination->GetInput( destination_input ) == NULL ); - if( ok ) - destination->AddInput( - destination_input, - input - ); - return( ok ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -Disconnect( - const std::string& origin_filter, - const std::string& origin_output, - const std::string& destination_filter, - const std::string& destination_input - ) -{ - // Get filters and check pertinence - TFilter* origin = this->GetFilter( origin_filter ); - TFilter* destination = this->GetFilter( destination_filter ); - if( origin == NULL || destination == NULL ) - return( false ); - if( !( destination->HasInput( destination_input ) ) ) - return( false ); - if( !( origin->HasOutput( origin_output ) ) ) - return( false ); - - // Check if there is room for a new connection - bool ok = false; - unsigned int del_id = 0; - for( - unsigned int i = 0; - i < destination->GetInputSize( destination_input ); - ++i - ) - if( - destination->GetInput( destination_input, i )->GetSource( ) == origin - ) - { - ok = true; - del_id = i; - - } // fi - if( ok ) - destination->DisconnectInput( destination_input, del_id ); - return( ok ); -} - -// ------------------------------------------------------------------------- -/* -const cpPlugins::Interface::Workspace:: -TExposedPorts& cpPlugins::Interface::Workspace:: -GetExposedInputs( ) const -{ - return( this->m_ExposedInputs ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Interface::Workspace:: -TExposedPorts& cpPlugins::Interface::Workspace:: -GetExposedOutputs( ) const -{ - return( this->m_ExposedOutputs ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::DataObject* cpPlugins::Interface::Workspace:: -GetExposedOutput( const std::string& name ) -{ - auto i = this->m_ExposedOutputs.find( name ); - if( i != this->m_ExposedOutputs.end( ) ) - { - auto f = this->GetFilter( i->second.first ); - if( f != NULL ) - return( f->GetOutput( i->second.second ) ); - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::DataObject* cpPlugins::Interface::Workspace:: -GetExposedOutput( const std::string& name ) const -{ - auto i = this->m_ExposedOutputs.find( name ); - if( i != this->m_ExposedOutputs.end( ) ) - { - auto f = this->GetFilter( i->second.first ); - if( f != NULL ) - return( f->GetOutput( i->second.second ) ); - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -ExposeInput( - const std::string& name, - const std::string& filter, const std::string& filter_input - ) -{ - auto i = this->m_ExposedInputs.find( name ); - if( i == this->m_ExposedInputs.end( ) ) - { - this->m_ExposedInputs[ name ] = - std::pair< std::string, std::string >( filter, filter_input ); - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -ExposeOutput( - const std::string& name, - const std::string& filter, const std::string& filter_output - ) -{ - auto i = this->m_ExposedOutputs.find( name ); - if( i == this->m_ExposedOutputs.end( ) ) - { - this->m_ExposedOutputs[ name ] = - std::pair< std::string, std::string >( filter, filter_output ); - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -HideInput( const std::string& name ) -{ - auto i = this->m_ExposedInputs.find( name ); - if( i != this->m_ExposedInputs.end( ) ) - this->m_ExposedInputs.erase( i ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -HideOutput( const std::string& name ) -{ - auto i = this->m_ExposedOutputs.find( name ); - if( i != this->m_ExposedOutputs.end( ) ) - this->m_ExposedOutputs.erase( i ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -RenameExposedInput( - const std::string& old_name, const std::string& new_name - ) -{ - auto o = this->m_ExposedInputs.find( old_name ); - auto n = this->m_ExposedInputs.find( new_name ); - if( o != this->m_ExposedInputs.end( ) && n == this->m_ExposedInputs.end( ) ) - { - this->m_ExposedInputs[ new_name ] = o->second; - this->m_ExposedInputs.erase( o ); - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Interface::Workspace:: -RenameExposedOutput( - const std::string& old_name, const std::string& new_name - ) -{ - auto o = this->m_ExposedOutputs.find( old_name ); - auto n = this->m_ExposedOutputs.find( new_name ); - if( - o != this->m_ExposedOutputs.end( ) && n == this->m_ExposedOutputs.end( ) - ) - { - this->m_ExposedOutputs[ new_name ] = o->second; - this->m_ExposedOutputs.erase( o ); - return( true ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -std::vector< std::pair< std::string, std::string > > -cpPlugins::Interface::Workspace:: -GetConnections( - const std::string& origin, const std::string& destination - ) const -{ - std::vector< std::pair< std::string, std::string > > conns; - auto orig = this->GetFilter( origin ); - auto dest = this->GetFilter( destination ); - if( orig != NULL && dest != NULL ) - { - auto outs = orig->GetOutputsNames( ); - auto ins = dest->GetInputsNames( ); - for( auto o = outs.begin( ); o != outs.end( ); ++o ) - { - for( auto i = ins.begin( ); i != ins.end( ); ++i ) - { - unsigned int nInputs = dest->GetInputSize( *i ); - for( unsigned j = 0; j < nInputs; ++j ) - { - auto od = orig->GetOutput( *o ); - auto id = dest->GetInput( *i, j ); - if( od != NULL && od == id ) - conns.push_back( - std::pair< std::string, std::string >( *o, *i ) - ); - - } // rof - - } // rof - - } // rof - - } // fi - return( conns ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Connect( - const std::string& orig_filter, const std::string& dest_filter, - const std::string& output_name, const std::string& input_name - ) -{ - auto o = this->GetFilter( orig_filter ); - auto d = this->GetFilter( dest_filter ); - if( o != NULL && d != NULL ) - { - try - { - d->AddInput( input_name, o->GetOutput( output_name ) ); - } - catch( std::exception& err ) - { - throw std::logic_error( - std::string( "Error connecting \"" ) + - output_name + std::string( "@" ) + orig_filter + - std::string( "\" with \"" ) + - input_name + std::string( "@" ) + dest_filter + - std::string( "\": " ) + - err.what( ) - ); - - } // yrt - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Connect( - cpPlugins::Pipeline::DataObject* output, - const std::string& dest_filter, const std::string& input_name - ) -{ - auto d = this->GetFilter( dest_filter ); - if( d != NULL ) - d->AddInput( input_name, output ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Connect( - cpPlugins::Pipeline::DataObject* output, - const std::string& exposed_input_name - ) -{ - auto i = this->m_ExposedInputs.find( exposed_input_name ); - if( i != this->m_ExposedInputs.end( ) ) - this->Connect( output, i->second.first, i->second.second ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Disconnect( - const std::string& orig_filter, const std::string& dest_filter, - const std::string& output_name, const std::string& input_name - ) -{ - auto orig = this->GetFilter( orig_filter ); - auto dest = this->GetFilter( dest_filter ); - if( orig != NULL && dest != NULL ) - { - auto out = orig->GetOutput( output_name ); - auto in = dest->GetInput( input_name ); - if( out != NULL && out == in ) - dest->SetInput( - input_name, ( cpPlugins::Pipeline::DataObject* )( NULL ) - ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Disconnect( - const std::string& dest_filter, const std::string& input_name - ) -{ - throw std::logic_error( "Disconnect 1" ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Disconnect( const std::string& dest_filter ) -{ - throw std::logic_error( "Disconnect 2" ); -} -*/ - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Update( ) -{ - for( auto f = this->m_Filters.begin( ); f != this->m_Filters.end( ); ++f ) - f->second->Update( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Update( const std::string& name ) -{ - auto filter = this->GetFilter( name ); - if( filter != NULL ) - filter->Update( ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -Workspace( ) - : Superclass( ), - m_PrintExecution( false ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Interface::Workspace:: -~Workspace( ) -{ - /* TODO - this->m_ExposedOutputs.clear( ); - this->m_ExposedInputs.clear( ); - */ - this->m_Filters.clear( ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Interface/Workspace.h b/lib/cpPlugins/Interface/Workspace.h deleted file mode 100644 index fd9847b..0000000 --- a/lib/cpPlugins/Interface/Workspace.h +++ /dev/null @@ -1,156 +0,0 @@ -#ifndef __cpPlugins__Interface__Workspace__h__ -#define __cpPlugins__Interface__Workspace__h__ - -#include -#include -#include -#include -#include - -class vtkRenderWindowInteractor; - -namespace cpPlugins -{ - namespace Interface - { - /** \brief A complex pipeline - */ - class cpPlugins_EXPORT Workspace - : public itk::Object - { - public: - typedef Workspace Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - typedef cpPlugins::Pipeline::DataObject TDataObject; - typedef cpPlugins::Pipeline::ProcessObject TFilter; - typedef cpPlugins::Pipeline::Widget TWidget; - typedef cpPlugins::Interface::Loader TLoader; - - typedef std::map< std::string, TFilter::Pointer > TFilters; - - /* TODO - typedef - std::map< std::string, std::pair< std::string, std::string > > - TExposedPorts; - */ - - public: - itkNewMacro( Self ); - itkTypeMacro( Workspace, itk::Object ); - - public: - // Workspace IO - void Load( const std::string& fname ); - void Save( const std::string& fname ) const; - - // Memory management - void Clear( ); - - // Filter management - std::vector< std::string > GetFiltersNames( ) const; - TFilter* GetFilter( const std::string& name ); - const TFilter* GetFilter( const std::string& name ) const; - TWidget* GetWidget( const std::string& name ); - const TWidget* GetWidget( const std::string& name ) const; - bool HasFilter( const std::string& name ) const; - bool HasWidget( const std::string& name ) const; - TFilter* CreateFilter( - const std::string& category, const std::string& filter, - const std::string& name - ); - TFilter* CreateFilter( - const std::string& category, const std::string& filter - ); - bool RenameFilter( - const std::string& old_name, const std::string& new_name - ); - bool RemoveFilter( const std::string& name ); - - void SetPrintExecution( bool b ); - void PrintExecutionOn( ); - void PrintExecutionOff( ); - - // Interactors - void AddInteractor( vtkRenderWindowInteractor* iren ); - - // Connection management - bool Connect( - const std::string& origin_filter, - const std::string& origin_output, - const std::string& destination_filter, - const std::string& destination_input - ); - bool Connect( - TDataObject* input, - const std::string& destination_filter, - const std::string& destination_input - ); - bool Disconnect( - const std::string& origin_filter, - const std::string& origin_output, - const std::string& destination_filter, - const std::string& destination_input - ); - - /* TODO - std::vector< std::pair< std::string, std::string > > GetConnections( - const std::string& origin, const std::string& destination - ) const; - void Connect( - const std::string& orig_filter, const std::string& dest_filter, - const std::string& output_name, const std::string& input_name - ); - void Connect( - cpPlugins::Pipeline::DataObject* output, - const std::string& dest_filter, const std::string& input_name - ); - void Connect( - cpPlugins::Pipeline::DataObject* output, - const std::string& exposed_input_name - ); - void Disconnect( - const std::string& orig_filter, const std::string& dest_filter, - const std::string& output_name, const std::string& input_name - ); - void Disconnect( - const std::string& dest_filter, const std::string& input_name - ); - void Disconnect( const std::string& dest_filter ); - */ - - // Pipeline execution - void Update( ); - void Update( const std::string& name ); - - protected: - Workspace( ); - virtual ~Workspace( ); - - private: - // Purposely not implemented - Workspace( const Self& other ); - Self& operator=( const Self& other ); - - protected: - TLoader m_Loader; - TFilters m_Filters; - bool m_PrintExecution; - - /* TODO - TExposedPorts m_ExposedInputs; - TExposedPorts m_ExposedOutputs; - */ - - std::set< vtkRenderWindowInteractor* > m_Interactors; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Interface__Workspace__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Interface/WorkspaceIO.cxx b/lib/cpPlugins/Interface/WorkspaceIO.cxx deleted file mode 100644 index 7b73c43..0000000 --- a/lib/cpPlugins/Interface/WorkspaceIO.cxx +++ /dev/null @@ -1,315 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Load( const std::string& fname ) -{ - this->Clear( ); - - // Read from disk - tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument( ); - doc->LoadFile( fname.c_str( ) ); - tinyxml2::XMLElement* root = doc->RootElement( ); - if( root == NULL ) - { - delete doc; - throw std::runtime_error( "cpPlugins::Workspace: No valid file" ); - - } // fi - if( std::string( root->Value( ) ) != "cpPlugins_Workspace" ) - { - delete doc; - throw std::runtime_error( "cpPlugins::Workspace: Not a valid workspace" ); - - } // fi - - // Read filters - std::stringstream err; - tinyxml2::XMLElement* filter = root->FirstChildElement( "Filter" ); - while( filter != NULL ) - { - const char* category_value = filter->Attribute( "Category" ); - const char* class_value = filter->Attribute( "Class" ); - const char* name_value = filter->Attribute( "Name" ); - float viewX = float( 0 ), viewY = float( 0 ); - filter->QueryFloatAttribute( "ViewX", &viewX ); - filter->QueryFloatAttribute( "ViewY", &viewY ); - int explicit_execution = 0; - filter->QueryIntAttribute( - "ExplicitExecution", &explicit_execution - ); - if( class_value != NULL && name_value != NULL ) - { - auto new_filter = this->CreateFilter( category_value, class_value ); - if( new_filter != NULL ) - { - this->RenameFilter( new_filter->GetName( ), name_value ); - new_filter->SetViewCoords( viewX, viewY ); - new_filter->SetExplicitExecution( explicit_execution == 1 ); - new_filter->GetParameters( )->FromXML( filter ); - } - else - err - << "No valid class \"" << class_value << "\" with name \"" - << name_value << "\"" << std::endl; - } - else - err << "Incomplete data." << std::endl; - filter = filter->NextSiblingElement( "Filter" ); - - } // elihw - - // Read connections - tinyxml2::XMLElement* connection = root->FirstChildElement( "Connection" ); - while( connection != NULL ) - { - tinyxml2::XMLElement* orig = connection->FirstChildElement( "Origin" ); - tinyxml2::XMLElement* dest = connection->FirstChildElement( "Destination" ); - if( orig != NULL && dest != NULL ) - { - const char* orig_filter = orig->Attribute( "Filter" ); - const char* dest_filter = dest->Attribute( "Filter" ); - const char* orig_name = orig->Attribute( "Name" ); - const char* dest_name = dest->Attribute( "Name" ); - if( - orig_filter != NULL && dest_filter != NULL && - orig_name != NULL && dest_name != NULL - ) - { - try - { - this->Connect( orig_filter, orig_name, dest_filter, dest_name ); - } - catch( std::exception& exc ) - { - err << exc.what( ) << std::endl; - - } // yrt - - } // fi - - } // fi - connection = connection->NextSiblingElement( "Connection" ); - - } // elihw - - // Read exposed inputs - /* TODO - tinyxml2::XMLElement* port = root->FirstChildElement( "ExposedInput" ); - while( port != NULL ) - { - this->ExposeInput( - port->Attribute( "Name" ), - port->Attribute( "Filter" ), - port->Attribute( "Input" ) - ); - port = port->NextSiblingElement( "ExposedInput" ); - - } // elihw - - // Read exposed outputs - port = root->FirstChildElement( "ExposedOutput" ); - while( port != NULL ) - { - this->ExposeOutput( - port->Attribute( "Name" ), - port->Attribute( "Filter" ), - port->Attribute( "Output" ) - ); - port = port->NextSiblingElement( "ExposedOutput" ); - - } // elihw - */ - - // Throw errors - std::string err_str = err.str( ); - if( err_str != "" ) - { - delete doc; - throw std::runtime_error( - std::string( "cpPlugins::Workspace " ) + err_str - ); - - } // fi - - // Finish - delete doc; -} - -// ------------------------------------------------------------------------- -void cpPlugins::Interface::Workspace:: -Save( const std::string& fname ) const -{ - tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument( ); - tinyxml2::XMLElement* root = doc->NewElement( "cpPlugins_Workspace" ); - std::set< std::string > used_plugins; - - // Save filter data - for( auto i = this->m_Filters.begin( ); i != this->m_Filters.end( ); ++i ) - { - auto filter = i->second; - used_plugins.insert( filter->GetPluginName( ) ); - tinyxml2::XMLElement* e = doc->NewElement( "Filter" ); - e->SetAttribute( "Category", filter->GetClassCategory( ) ); - e->SetAttribute( "Class", filter->GetClassName( ) ); - e->SetAttribute( "Name", filter->GetName( ) ); - e->SetAttribute( "ViewX", filter->GetViewX( ) ); - e->SetAttribute( "ViewY", filter->GetViewY( ) ); - e->SetAttribute( - "ExplicitExecution", ( filter->GetExplicitExecution( ) )? 1: 0 - ); - - auto params = filter->GetParameters( ); - params->ToXML( doc, e ); - root->LinkEndChild( e ); - - } // rof - - // Save used plugins - /* TODO - tinyxml2::XMLElement* plugins = doc->NewElement( "Plugins" ); - for( auto pIt = used_plugins.begin( ); pIt != used_plugins.end( ); ++pIt ) - { - tinyxml2::XMLElement* e = doc->NewElement( "Plugin" ); - e->SetAttribute( "Name", pIt->c_str( ) ); - plugins->LinkEndChild( e ); - - } // rof - root->LinkEndChild( plugins ); - */ - - // Save connections - for( auto i = this->m_Filters.begin( ); i != this->m_Filters.end( ); ++i ) - { - auto orig = i->second; - auto outputs = orig->GetOutputsNames( ); - if( outputs.size( ) == 0 ) - continue; - for( auto j = this->m_Filters.begin( ); j != this->m_Filters.end( ); ++j ) - { - if( i == j ) - continue; - auto dest = j->second; - auto inputs = dest->GetInputsNames( ); - if( inputs.size( ) == 0 ) - continue; - - for( auto oIt = outputs.begin( ); oIt != outputs.end( ); ++oIt ) - { - auto od = orig->GetOutput( *oIt ); - for( auto iIt = inputs.begin( ); iIt != inputs.end( ); ++iIt ) - { - unsigned int nInputs = dest->GetInputSize( *iIt ); - for( unsigned int k = 0; k < nInputs; ++k ) - { - auto id = dest->GetInput( *iIt, k ); - if( od != NULL && od == id ) - { - tinyxml2::XMLElement* e_conn = doc->NewElement( "Connection" ); - tinyxml2::XMLElement* e_orig = doc->NewElement( "Origin" ); - tinyxml2::XMLElement* e_dest = doc->NewElement( "Destination" ); - e_orig->SetAttribute( "Filter", orig->GetName( ) ); - e_orig->SetAttribute( "Name", oIt->c_str( ) ); - e_dest->SetAttribute( "Filter", dest->GetName( ) ); - e_dest->SetAttribute( "Name", iIt->c_str( ) ); - e_conn->LinkEndChild( e_orig ); - e_conn->LinkEndChild( e_dest ); - root->LinkEndChild( e_conn ); - - } // fi - - } // rof - - } // rof - - } // rof - - } // rof - - } // rof - - // Save exposed ports - /* TODO - auto eipIt = this->m_ExposedInputs.begin( ); - for( ; eipIt != this->m_ExposedInputs.end( ); ++eipIt ) - { - tinyxml2::XMLElement* port = doc->NewElement( "ExposedInput" ); - port->SetAttribute( "Name", eipIt->first.c_str( ) ); - port->SetAttribute( "Filter", eipIt->second.first.c_str( ) ); - port->SetAttribute( "Input", eipIt->second.second.c_str( ) ); - root->LinkEndChild( port ); - - } // rof - - auto eopIt = this->m_ExposedOutputs.begin( ); - for( ; eopIt != this->m_ExposedOutputs.end( ); ++eopIt ) - { - tinyxml2::XMLElement* port = doc->NewElement( "ExposedOutput" ); - port->SetAttribute( "Name", eopIt->first.c_str( ) ); - port->SetAttribute( "Filter", eopIt->second.first.c_str( ) ); - port->SetAttribute( "Output", eopIt->second.second.c_str( ) ); - root->LinkEndChild( port ); - - } // rof - */ - - // Physical write and return - doc->LinkEndChild( root ); - auto error = doc->SaveFile( fname.c_str( ) ); - delete doc; - if( error != tinyxml2::XML_SUCCESS ) - { - std::string m; - switch( error ) - { - case tinyxml2::XML_NO_ATTRIBUTE: - m = "No attribute."; break; - case tinyxml2::XML_WRONG_ATTRIBUTE_TYPE: - m = "Wrong attribute."; break; - case tinyxml2::XML_ERROR_FILE_NOT_FOUND: - m = "File not found."; break; - case tinyxml2::XML_ERROR_FILE_COULD_NOT_BE_OPENED: - m = "File not opened."; break; - case tinyxml2::XML_ERROR_FILE_READ_ERROR: - m = "File not read."; break; - case tinyxml2::XML_ERROR_ELEMENT_MISMATCH: - m = "Element mismatch."; break; - case tinyxml2::XML_ERROR_PARSING_ELEMENT: - m = "Parsing element."; break; - case tinyxml2::XML_ERROR_PARSING_ATTRIBUTE: - m = "Parsing attribute."; break; - case tinyxml2::XML_ERROR_IDENTIFYING_TAG: - m = "Tag Id."; break; - case tinyxml2::XML_ERROR_PARSING_TEXT: - m = "Parsing text."; break; - case tinyxml2::XML_ERROR_PARSING_CDATA: - m = "Parsing cdata."; break; - case tinyxml2::XML_ERROR_PARSING_COMMENT: - m = "Parsing comment."; break; - case tinyxml2::XML_ERROR_PARSING_DECLARATION: - m = "Parsing declaration."; break; - case tinyxml2::XML_ERROR_PARSING_UNKNOWN: - m = "Parsing unknown."; break; - case tinyxml2::XML_ERROR_EMPTY_DOCUMENT: - m = "Empty document."; break; - case tinyxml2::XML_ERROR_MISMATCHED_ELEMENT: - m = "Mismatched element."; break; - case tinyxml2::XML_ERROR_PARSING: - m = "Parsing."; break; - case tinyxml2::XML_CAN_NOT_CONVERT_TEXT: - m = "Cannot convert."; break; - case tinyxml2::XML_NO_TEXT_NODE: - m = "No text."; break; - default: - m = "Unknown error."; break; - } // hctiws - throw std::runtime_error( - std::string( "cpPlugins::Workspace: Error while saving \"" ) + - fname + std::string( "\": " ) + m - ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/Chrono.h b/lib/cpPlugins/OS/Chrono.h deleted file mode 100644 index e012406..0000000 --- a/lib/cpPlugins/OS/Chrono.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef __cpPlugins__OS__Chrono__h__ -#define __cpPlugins__OS__Chrono__h__ - -#include -#include - -// ------------------------------------------------------------------------- -#define cpPlugins_CHRONO \ - std::chrono::duration_cast< std::chrono::milliseconds >( \ - std::chrono::system_clock::now( ).time_since_epoch( ) \ - ).count( ) - -#endif // __cpPlugins__OS__Chrono__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/DLLManager.cxx b/lib/cpPlugins/OS/DLLManager.cxx deleted file mode 100644 index ba13b36..0000000 --- a/lib/cpPlugins/OS/DLLManager.cxx +++ /dev/null @@ -1,50 +0,0 @@ -#include -#ifdef cpExtensions_OS_Windows -#else // cpExtensions_OS_Windows -# include -#endif // cpExtensions_OS_Windows - -// ------------------------------------------------------------------------- -void* cpPlugins::OS::DLLManager:: -Open( const std::string& filename ) -{ - void* hnd = NULL; -#ifdef cpExtensions_OS_Windows -#else // cpExtensions_OS_Windows - hnd = dlopen( filename.c_str( ), RTLD_NOW | RTLD_GLOBAL ); - char* error = dlerror( ); - if( error != NULL ) - throw std::runtime_error( error ); -#endif // cpExtensions_OS_Windows - return( hnd ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::OS::DLLManager:: -Close( void* hnd ) -{ -#ifdef cpExtensions_OS_Windows -#else // cpExtensions_OS_Windows - /* TODO: why this clashes with VTK? -> Unregistering of factories. - dlclose( hnd ); - dlerror( ); - */ -#endif // cpExtensions_OS_Windows -} - -// ------------------------------------------------------------------------- -void* cpPlugins::OS::DLLManager:: -Sym( void* hnd, const std::string& symbol ) -{ - void* sym = NULL; -#ifdef cpExtensions_OS_Windows -#else // cpExtensions_OS_Windows - sym = dlsym( hnd, symbol.c_str( ) ); - char* error = dlerror( ); - if( error != NULL ) - throw std::runtime_error( error ); -#endif // cpExtensions_OS_Windows - return( sym ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/DLLManager.h b/lib/cpPlugins/OS/DLLManager.h deleted file mode 100644 index 9e6460b..0000000 --- a/lib/cpPlugins/OS/DLLManager.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef __cpPlugins__OS__DLLManager__h__ -#define __cpPlugins__OS__DLLManager__h__ - -#include -#include - -namespace cpPlugins -{ - namespace OS - { - /** - */ - class cpPlugins_EXPORT DLLManager - { - public: - static void* Open( const std::string& filename ); - static void Close( void* hnd ); - static void* Sym( void* hnd, const std::string& symbol ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__OS__DLLManager__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/FileSystem.cxx b/lib/cpPlugins/OS/FileSystem.cxx deleted file mode 100644 index 334bf2a..0000000 --- a/lib/cpPlugins/OS/FileSystem.cxx +++ /dev/null @@ -1,202 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -std::string cpPlugins::OS::FileSystem:: -CanonicalPath( const std::string& path ) -{ - std::string ret = ""; -#ifdef cpExtensions_OS_Windows - TCHAR buffer[ 4096 ] = TEXT( "" ); - TCHAR** lppPart = { NULL }; - GetFullPathName( path.c_str( ), 4096, buffer, lppPart ); - ret = std::string( buffer ); -#else // cpExtensions_OS_Windows - char* canonical_path = realpath( path.c_str( ), NULL ); - if( canonical_path != NULL ) - { - ret = canonical_path; - free( canonical_path ); - - } // fi -#endif // cpExtensions_OS_Windows - return( ret ); -} - -// ------------------------------------------------------------------------- -std::pair< std::string, std::string > cpPlugins::OS::FileSystem:: -SplitPath( const std::string& path ) -{ - size_t found = path.find_last_of( "/\\" ); - return( - std::pair< std::string, std::string >( - path.substr( 0, found + 1 ), path.substr( found + 1 ) - ) - ); -} - -// ------------------------------------------------------------------------- -std::set< std::string > cpPlugins::OS::FileSystem:: -LoadDirContents( - const std::string& path, bool recursive, - const std::string& pattern - ) -{ - // Prepare inputs and outputs - std::stringstream path_stream; - path_stream << path << cpPlugins_PATH_SEPARATOR; - std::string path_str = path_stream.str( ); - std::set< std::string > output; - - // Process data - tinydir_dir dir; - if( tinydir_open_sorted( &dir, path.c_str( ) ) != -1 ) - { - for( auto i = 0; i < dir.n_files; i++ ) - { - tinydir_file file; - if( tinydir_readfile_n( &dir, &file , i ) != -1 ) - { - std::string fname = path_str + file.name; - if( file.is_dir ) - { - if( recursive ) - { - if( fname != "." && fname != ".." ) - { - auto tmp = Self::LoadDirContents( fname, true ); - output.insert( tmp.begin( ), tmp.end( ) ); - - } // fi - - } // fi - } - else - { - if( pattern != "" ) - { - if( Self::Glob( fname, path_str + pattern ) ) - output.insert( fname ); - } - else - output.insert( fname ); - - } // fi - - } // fi - - } // rof - - } // fi - tinydir_close( &dir ); - return( output ); -} - -// ------------------------------------------------------------------------- -int cpPlugins::OS::FileSystem:: -GlobMatch( const char* target, const char* pattern ) -{ - char* pat = const_cast< char* >( pattern ); - char* end = strchr( pat, ']' ); - char* ptr; - if( *pat == '[' && end != NULL ) - { - if( end == pat + 1 ) - { - end = strchr( pat + 2, ']' ); - if( end == NULL ) - return( 0 ); - - } // fi - - if( end - pat == 4 && pat[ 2 ] == '-' && pat[ 1 ] <= pattern[ 3 ] ) - { - if( *target >= pat[ 1 ] && *target <= pat[ 3 ] ) - return( 5 ); - else - return( 0 ); - - } // fi - - ptr = strchr( pat + 1, *target ); - if( ptr != NULL && ptr < end ) - return( end - pat + 1 ); - else - return( 0 ); - - } // fi - - if( *pat == '?' && *target != 0 ) - return( 1 ); - if( *pat == '*' ) - return( 0 ); - if( *target == 0 || *pat == 0 ) - return( 0 ); - if( *target == *pat ) - return( 1 ); - return( 0 ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::OS::FileSystem:: -Glob( const std::string& line, const std::string& pattern ) -{ - const char* target = line.c_str( ); - const char* pat = pattern.c_str( ); - int gobble; - - while( ( gobble = GlobMatch( target, pat ) ) ) - { - target++; - pat += gobble; - - } // elihw - if( *target == 0 && *pat == 0 ) - return( true ); - else if( *pat == '*' ) - { - while( pat[ 1 ] == '*' ) - pat++; - if( pat[ 1 ] == 0 ) - return( true ); - while( *target ) - if( Glob( target++, pat + 1 ) ) - return( 1 ); - - } // fi - return( false ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::OS::FileSystem:: -Read( std::string& buffer, const std::string& fname ) -{ - buffer = ""; - std::ifstream file_stream( fname.c_str( ) ); - if( !file_stream ) - return( false ); - file_stream.seekg( 0, std::ios::end ); - buffer.reserve( ( unsigned int )( file_stream.tellg( ) ) ); - file_stream.seekg( 0, std::ios::beg ); - buffer.assign( - ( std::istreambuf_iterator< char >( file_stream ) ), - std::istreambuf_iterator< char >( ) - ); - file_stream.close( ); - return( true ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::OS::FileSystem:: -Write( const std::string& buffer, const std::string& fname ) -{ - std::ofstream file_stream( fname.c_str( ), std::ofstream::binary ); - if( !file_stream ) - return( false ); - file_stream.write( buffer.c_str( ), buffer.size( ) ); - return( true ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/FileSystem.h b/lib/cpPlugins/OS/FileSystem.h deleted file mode 100644 index 4c59413..0000000 --- a/lib/cpPlugins/OS/FileSystem.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef __cpPlugins__OS__FileSystem__h__ -#define __cpPlugins__OS__FileSystem__h__ - -#include -#include -#include - -namespace cpPlugins -{ - namespace OS - { - /** - */ - class cpPlugins_EXPORT FileSystem - { - public: - typedef FileSystem Self; - - public: - /** - */ - static std::string CanonicalPath( const std::string& path ); - - /** - */ - static std::pair< std::string, std::string > SplitPath( - const std::string& path - ); - - /** - */ - static std::set< std::string > LoadDirContents( - const std::string& path, bool recursive = false, - const std::string& pattern = "" - ); - - /** - */ - static int GlobMatch( const char* target, const char* pattern ); - - /** - */ - static bool Glob( const std::string& line, const std::string& pattern ); - - /** - */ - static bool Read( std::string& buffer, const std::string& fname ); - - /** - */ - static bool Write( const std::string& buffer, const std::string& fname ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__OS__FileSystem__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/String.cxx b/lib/cpPlugins/OS/String.cxx deleted file mode 100644 index 0bb9b59..0000000 --- a/lib/cpPlugins/OS/String.cxx +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -#ifdef cpPlugins_OS_Windows -# define cpPlugins_STRTOK( A, B, N ) strtok_s( A, B, N ) -#else // cpPlugins_OS_Windows -# define cpPlugins_STRTOK( A, B, N ) std::strtok( A, B ) -#endif // cpPlugins_OS_Windows - -// ------------------------------------------------------------------------- -std::vector< std::string > cpPlugins::OS::String:: -Tokenize( const std::string& str, const std::string& delims ) -{ - std::vector< std::string > tokens; - if( str.size( ) > 0 ) - { - auto ssize = str.size( ); - char* buffer = new char[ ssize + 1 ]; - for( unsigned long i = 0; i < ssize; ++i ) - buffer[ i ] = str[ i ]; - buffer[ ssize ] = '\0'; - char* next; - char* it = cpPlugins_STRTOK( buffer, delims.c_str( ), &next ); - while( it != NULL ) - { - tokens.push_back( std::string( it ) ); - it = cpPlugins_STRTOK( NULL, delims.c_str( ), &next ); - - } // elihw - delete [] buffer; - - } // fi - return( tokens ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/String.h b/lib/cpPlugins/OS/String.h deleted file mode 100644 index d87db17..0000000 --- a/lib/cpPlugins/OS/String.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef __cpPlugins__OS__String__h__ -#define __cpPlugins__OS__String__h__ - -#include -#include -#include - -namespace cpPlugins -{ - namespace OS - { - /** - */ - class cpPlugins_EXPORT String - { - public: - static std::vector< std::string > Tokenize( - const std::string& str, const std::string& delims - ); - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__OS__String__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/tinydir.h b/lib/cpPlugins/OS/tinydir.h deleted file mode 100644 index 432bd95..0000000 --- a/lib/cpPlugins/OS/tinydir.h +++ /dev/null @@ -1,806 +0,0 @@ -/* - Copyright (c) 2013-2016, tinydir authors: - - Cong Xu - - Lautis Sun - - Baudouin Feildel - - Andargor - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef cpPlugins__OS__TINYDIR_H -#define cpPlugins__OS__TINYDIR_H - -#ifdef __cplusplus -extern "C" { -#endif - -#if ((defined _UNICODE) && !(defined UNICODE)) -#define UNICODE -#endif - -#if ((defined UNICODE) && !(defined _UNICODE)) -#define _UNICODE -#endif - -#include -#include -#include -#ifdef _MSC_VER -# define WIN32_LEAN_AND_MEAN -# include -# include -# pragma warning(push) -# pragma warning (disable : 4996) -#else -# include -# include -# include -# include -#endif -#ifdef __MINGW32__ -# include -#endif - - -/* types */ - -/* Windows UNICODE wide character support */ -#if defined _MSC_VER || defined __MINGW32__ -#define _tinydir_char_t TCHAR -#define TINYDIR_STRING(s) _TEXT(s) -#define _tinydir_strlen _tcslen -#define _tinydir_strcpy _tcscpy -#define _tinydir_strcat _tcscat -#define _tinydir_strcmp _tcscmp -#define _tinydir_strrchr _tcsrchr -#define _tinydir_strncmp _tcsncmp -#else -#define _tinydir_char_t char -#define TINYDIR_STRING(s) s -#define _tinydir_strlen strlen -#define _tinydir_strcpy strcpy -#define _tinydir_strcat strcat -#define _tinydir_strcmp strcmp -#define _tinydir_strrchr strrchr -#define _tinydir_strncmp strncmp -#endif - -#if (defined _MSC_VER || defined __MINGW32__) -#include -#define _TINYDIR_PATH_MAX MAX_PATH -#elif defined __linux__ -#include -#define _TINYDIR_PATH_MAX PATH_MAX -#else -#define _TINYDIR_PATH_MAX 4096 -#endif - -#ifdef _MSC_VER -/* extra chars for the "\\*" mask */ -# define _TINYDIR_PATH_EXTRA 2 -#else -# define _TINYDIR_PATH_EXTRA 0 -#endif - -#define _TINYDIR_FILENAME_MAX 256 - -#if (defined _MSC_VER || defined __MINGW32__) -#define _TINYDIR_DRIVE_MAX 3 -#endif - -#ifdef _MSC_VER -# define _TINYDIR_FUNC static __inline -#elif !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L -# define _TINYDIR_FUNC static __inline__ -#else -# define _TINYDIR_FUNC static inline -#endif - -/* readdir_r usage; define TINYDIR_USE_READDIR_R to use it (if supported) */ -#ifdef TINYDIR_USE_READDIR_R - -/* readdir_r is a POSIX-only function, and may not be available under various - * environments/settings, e.g. MinGW. Use readdir fallback */ -#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE || \ - _POSIX_SOURCE -# define _TINYDIR_HAS_READDIR_R -#endif -#if _POSIX_C_SOURCE >= 200112L -# define _TINYDIR_HAS_FPATHCONF -# include -#endif -#if _BSD_SOURCE || _SVID_SOURCE || \ - (_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) -# define _TINYDIR_HAS_DIRFD -# include -#endif -#if defined _TINYDIR_HAS_FPATHCONF && defined _TINYDIR_HAS_DIRFD && \ - defined _PC_NAME_MAX -# define _TINYDIR_USE_FPATHCONF -#endif -#if defined __MINGW32__ || !defined _TINYDIR_HAS_READDIR_R || \ - !(defined _TINYDIR_USE_FPATHCONF || defined NAME_MAX) -# define _TINYDIR_USE_READDIR -#endif - -/* Use readdir by default */ -#else -# define _TINYDIR_USE_READDIR -#endif - -/* MINGW32 has two versions of dirent, ASCII and UNICODE*/ -#ifndef _MSC_VER -#if (defined __MINGW32__) && (defined _UNICODE) -#define _TINYDIR_DIR _WDIR -#define _tinydir_dirent _wdirent -#define _tinydir_opendir _wopendir -#define _tinydir_readdir _wreaddir -#define _tinydir_closedir _wclosedir -#else -#define _TINYDIR_DIR DIR -#define _tinydir_dirent dirent -#define _tinydir_opendir opendir -#define _tinydir_readdir readdir -#define _tinydir_closedir closedir -#endif -#endif - -/* Allow user to use a custom allocator by defining _TINYDIR_MALLOC and _TINYDIR_FREE. */ -#if defined(_TINYDIR_MALLOC) && defined(_TINYDIR_FREE) -#elif !defined(_TINYDIR_MALLOC) && !defined(_TINYDIR_FREE) -#else -#error "Either define both alloc and free or none of them!" -#endif - -#if !defined(_TINYDIR_MALLOC) -#define _TINYDIR_MALLOC(_size) malloc(_size) -#define _TINYDIR_FREE(_ptr) free(_ptr) -#endif /* !defined(_TINYDIR_MALLOC) */ - - typedef struct tinydir_file - { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - _tinydir_char_t name[_TINYDIR_FILENAME_MAX]; - _tinydir_char_t *extension; - int is_dir; - int is_reg; - -#ifndef _MSC_VER -#ifdef __MINGW32__ - struct _stat _s; -#else - struct stat _s; -#endif -#endif - } tinydir_file; - - typedef struct tinydir_dir - { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - int has_next; - size_t n_files; - - tinydir_file *_files; -#ifdef _MSC_VER - HANDLE _h; - WIN32_FIND_DATA _f; -#else - _TINYDIR_DIR *_d; - struct _tinydir_dirent *_e; -#ifndef _TINYDIR_USE_READDIR - struct _tinydir_dirent *_ep; -#endif -#endif - } tinydir_dir; - - -/* declarations */ - - _TINYDIR_FUNC - int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path); - _TINYDIR_FUNC - int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path); - _TINYDIR_FUNC - void tinydir_close(tinydir_dir *dir); - - _TINYDIR_FUNC - int tinydir_next(tinydir_dir *dir); - _TINYDIR_FUNC - int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file); - _TINYDIR_FUNC - int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i); - _TINYDIR_FUNC - int tinydir_open_subdir_n(tinydir_dir *dir, size_t i); - - _TINYDIR_FUNC - int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path); - _TINYDIR_FUNC - void _tinydir_get_ext(tinydir_file *file); - _TINYDIR_FUNC - int _tinydir_file_cmp(const void *a, const void *b); -#ifndef _MSC_VER -#ifndef _TINYDIR_USE_READDIR - _TINYDIR_FUNC - size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp); -#endif -#endif - - -/* definitions*/ - - _TINYDIR_FUNC - int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path) - { -#ifndef _MSC_VER -#ifndef _TINYDIR_USE_READDIR - int error; - int size; /* using int size */ -#endif -#else - _tinydir_char_t path_buf[_TINYDIR_PATH_MAX]; -#endif - _tinydir_char_t *pathp; - - if (dir == NULL || path == NULL || _tinydir_strlen(path) == 0) - { - errno = EINVAL; - return -1; - } - if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) - { - errno = ENAMETOOLONG; - return -1; - } - - /* initialise dir */ - dir->_files = NULL; -#ifdef _MSC_VER - dir->_h = INVALID_HANDLE_VALUE; -#else - dir->_d = NULL; -#ifndef _TINYDIR_USE_READDIR - dir->_ep = NULL; -#endif -#endif - tinydir_close(dir); - - _tinydir_strcpy(dir->path, path); - /* Remove trailing slashes */ - pathp = &dir->path[_tinydir_strlen(dir->path) - 1]; - while (pathp != dir->path && (*pathp == TINYDIR_STRING('\\') || *pathp == TINYDIR_STRING('/'))) - { - *pathp = TINYDIR_STRING('\0'); - pathp++; - } -#ifdef _MSC_VER - _tinydir_strcpy(path_buf, dir->path); - _tinydir_strcat(path_buf, TINYDIR_STRING("\\*")); - dir->_h = FindFirstFile(path_buf, &dir->_f); - if (dir->_h == INVALID_HANDLE_VALUE) - { - errno = ENOENT; -#else - dir->_d = _tinydir_opendir(path); - if (dir->_d == NULL) - { -#endif - goto bail; - } - - /* read first file */ - dir->has_next = 1; -#ifndef _MSC_VER -#ifdef _TINYDIR_USE_READDIR - dir->_e = _tinydir_readdir(dir->_d); -#else - /* allocate dirent buffer for readdir_r */ - size = _tinydir_dirent_buf_size(dir->_d); /* conversion to int */ - if (size == -1) return -1; - dir->_ep = (struct _tinydir_dirent*)_TINYDIR_MALLOC(size); - if (dir->_ep == NULL) return -1; - - error = readdir_r(dir->_d, dir->_ep, &dir->_e); - if (error != 0) return -1; -#endif - if (dir->_e == NULL) - { - dir->has_next = 0; - } -#endif - - return 0; - - bail: - tinydir_close(dir); - return -1; - } - - _TINYDIR_FUNC - int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path) - { - /* Count the number of files first, to pre-allocate the files array */ - size_t n_files = 0; - if (tinydir_open(dir, path) == -1) - { - return -1; - } - while (dir->has_next) - { - n_files++; - if (tinydir_next(dir) == -1) - { - goto bail; - } - } - tinydir_close(dir); - - if (tinydir_open(dir, path) == -1) - { - return -1; - } - - dir->n_files = 0; - dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files); - if (dir->_files == NULL) - { - goto bail; - } - while (dir->has_next) - { - tinydir_file *p_file; - dir->n_files++; - - p_file = &dir->_files[dir->n_files - 1]; - if (tinydir_readfile(dir, p_file) == -1) - { - goto bail; - } - - if (tinydir_next(dir) == -1) - { - goto bail; - } - - /* Just in case the number of files has changed between the first and - second reads, terminate without writing into unallocated memory */ - if (dir->n_files == n_files) - { - break; - } - } - - qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); - - return 0; - - bail: - tinydir_close(dir); - return -1; - } - - _TINYDIR_FUNC - void tinydir_close(tinydir_dir *dir) - { - if (dir == NULL) - { - return; - } - - memset(dir->path, 0, sizeof(dir->path)); - dir->has_next = 0; - dir->n_files = 0; - _TINYDIR_FREE(dir->_files); - dir->_files = NULL; -#ifdef _MSC_VER - if (dir->_h != INVALID_HANDLE_VALUE) - { - FindClose(dir->_h); - } - dir->_h = INVALID_HANDLE_VALUE; -#else - if (dir->_d) - { - _tinydir_closedir(dir->_d); - } - dir->_d = NULL; - dir->_e = NULL; -#ifndef _TINYDIR_USE_READDIR - _TINYDIR_FREE(dir->_ep); - dir->_ep = NULL; -#endif -#endif - } - - _TINYDIR_FUNC - int tinydir_next(tinydir_dir *dir) - { - if (dir == NULL) - { - errno = EINVAL; - return -1; - } - if (!dir->has_next) - { - errno = ENOENT; - return -1; - } - -#ifdef _MSC_VER - if (FindNextFile(dir->_h, &dir->_f) == 0) -#else -#ifdef _TINYDIR_USE_READDIR - dir->_e = _tinydir_readdir(dir->_d); -#else - if (dir->_ep == NULL) - { - return -1; - } - if (readdir_r(dir->_d, dir->_ep, &dir->_e) != 0) - { - return -1; - } -#endif - if (dir->_e == NULL) -#endif - { - dir->has_next = 0; -#ifdef _MSC_VER - if (GetLastError() != ERROR_SUCCESS && - GetLastError() != ERROR_NO_MORE_FILES) - { - tinydir_close(dir); - errno = EIO; - return -1; - } -#endif - } - - return 0; - } - - _TINYDIR_FUNC - int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file) - { - if (dir == NULL || file == NULL) - { - errno = EINVAL; - return -1; - } -#ifdef _MSC_VER - if (dir->_h == INVALID_HANDLE_VALUE) -#else - if (dir->_e == NULL) -#endif - { - errno = ENOENT; - return -1; - } - if (_tinydir_strlen(dir->path) + - _tinydir_strlen( -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ) + 1 + _TINYDIR_PATH_EXTRA >= - _TINYDIR_PATH_MAX) - { - /* the path for the file will be too long */ - errno = ENAMETOOLONG; - return -1; - } - if (_tinydir_strlen( -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ) >= _TINYDIR_FILENAME_MAX) - { - errno = ENAMETOOLONG; - return -1; - } - - _tinydir_strcpy(file->path, dir->path); - _tinydir_strcat(file->path, TINYDIR_STRING("/")); - _tinydir_strcpy(file->name, -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ); - _tinydir_strcat(file->path, file->name); -#ifndef _MSC_VER -#ifdef __MINGW32__ - if (_tstat( -#else - if (stat( -#endif - file->path, &file->_s) == -1) - { - return -1; - } -#endif - _tinydir_get_ext(file); - - file->is_dir = -#ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); -#else - S_ISDIR(file->_s.st_mode); -#endif - file->is_reg = -#ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || - ( - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && -#ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && -#endif -#ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && -#endif - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); -#else - S_ISREG(file->_s.st_mode); -#endif - - return 0; - } - - _TINYDIR_FUNC - int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i) - { - if (dir == NULL || file == NULL) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files) - { - errno = ENOENT; - return -1; - } - - memcpy(file, &dir->_files[i], sizeof(tinydir_file)); - _tinydir_get_ext(file); - - return 0; - } - - _TINYDIR_FUNC - int tinydir_open_subdir_n(tinydir_dir *dir, size_t i) - { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - if (dir == NULL) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files || !dir->_files[i].is_dir) - { - errno = ENOENT; - return -1; - } - - _tinydir_strcpy(path, dir->_files[i].path); - tinydir_close(dir); - if (tinydir_open_sorted(dir, path) == -1) - { - return -1; - } - - return 0; - } - -/* Open a single file given its path */ - _TINYDIR_FUNC - int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path) - { - tinydir_dir dir; - int result = 0; - int found = 0; - _tinydir_char_t dir_name_buf[_TINYDIR_PATH_MAX]; - _tinydir_char_t file_name_buf[_TINYDIR_FILENAME_MAX]; - _tinydir_char_t *dir_name; - _tinydir_char_t *base_name; -#if (defined _MSC_VER || defined __MINGW32__) - _tinydir_char_t drive_buf[_TINYDIR_DRIVE_MAX]; - _tinydir_char_t ext_buf[_TINYDIR_FILENAME_MAX]; -#endif - - if (file == NULL || path == NULL || _tinydir_strlen(path) == 0) - { - errno = EINVAL; - return -1; - } - if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) - { - errno = ENAMETOOLONG; - return -1; - } - - /* Get the parent path */ -#if (defined _MSC_VER || defined __MINGW32__) -#if ((defined _MSC_VER) && (_MSC_VER >= 1400)) - _tsplitpath_s( - path, - drive_buf, _TINYDIR_DRIVE_MAX, - dir_name_buf, _TINYDIR_FILENAME_MAX, - file_name_buf, _TINYDIR_FILENAME_MAX, - ext_buf, _TINYDIR_FILENAME_MAX); -#else - _tsplitpath( - path, - drive_buf, - dir_name_buf, - file_name_buf, - ext_buf); -#endif - -/* _splitpath_s not work fine with only filename and widechar support */ -#ifdef _UNICODE - if (drive_buf[0] == L'\xFEFE') - drive_buf[0] = '\0'; - if (dir_name_buf[0] == L'\xFEFE') - dir_name_buf[0] = '\0'; -#endif - - if (errno) - { - errno = EINVAL; - return -1; - } - /* Emulate the behavior of dirname by returning "." for dir name if it's - empty */ - if (drive_buf[0] == '\0' && dir_name_buf[0] == '\0') - { - _tinydir_strcpy(dir_name_buf, TINYDIR_STRING(".")); - } - /* Concatenate the drive letter and dir name to form full dir name */ - _tinydir_strcat(drive_buf, dir_name_buf); - dir_name = drive_buf; - /* Concatenate the file name and extension to form base name */ - _tinydir_strcat(file_name_buf, ext_buf); - base_name = file_name_buf; -#else - _tinydir_strcpy(dir_name_buf, path); - dir_name = dirname(dir_name_buf); - _tinydir_strcpy(file_name_buf, path); - base_name =basename(file_name_buf); -#endif - - /* Open the parent directory */ - if (tinydir_open(&dir, dir_name) == -1) - { - return -1; - } - - /* Read through the parent directory and look for the file */ - while (dir.has_next) - { - if (tinydir_readfile(&dir, file) == -1) - { - result = -1; - goto bail; - } - if (_tinydir_strcmp(file->name, base_name) == 0) - { - /* File found */ - found = 1; - break; - } - tinydir_next(&dir); - } - if (!found) - { - result = -1; - errno = ENOENT; - } - - bail: - tinydir_close(&dir); - return result; - } - - _TINYDIR_FUNC - void _tinydir_get_ext(tinydir_file *file) - { - _tinydir_char_t *period = _tinydir_strrchr(file->name, TINYDIR_STRING('.')); - if (period == NULL) - { - file->extension = &(file->name[_tinydir_strlen(file->name)]); - } - else - { - file->extension = period + 1; - } - } - - _TINYDIR_FUNC - int _tinydir_file_cmp(const void *a, const void *b) - { - const tinydir_file *fa = (const tinydir_file *)a; - const tinydir_file *fb = (const tinydir_file *)b; - if (fa->is_dir != fb->is_dir) - { - return -(fa->is_dir - fb->is_dir); - } - return _tinydir_strncmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); - } - -#ifndef _MSC_VER -#ifndef _TINYDIR_USE_READDIR -/* - The following authored by Ben Hutchings - from https://womble.decadent.org.uk/readdir_r-advisory.html -*/ -/* Calculate the required buffer size (in bytes) for directory * - * entries read from the given directory handle. Return -1 if this * - * this cannot be done. * - * * - * This code does not trust values of NAME_MAX that are less than * - * 255, since some systems (including at least HP-UX) incorrectly * - * define it to be a smaller value. */ - _TINYDIR_FUNC - size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp) - { - long name_max; - size_t name_end; - /* parameter may be unused */ - (void)dirp; - -#if defined _TINYDIR_USE_FPATHCONF - name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX); - if (name_max == -1) -#if defined(NAME_MAX) - name_max = (NAME_MAX > 255) ? NAME_MAX : 255; -#else - return (size_t)(-1); -#endif -#elif defined(NAME_MAX) - name_max = (NAME_MAX > 255) ? NAME_MAX : 255; -#else -#error "buffer size for readdir_r cannot be determined" -#endif - name_end = (size_t)offsetof(struct _tinydir_dirent, d_name) + name_max + 1; - return (name_end > sizeof(struct _tinydir_dirent) ? - name_end : sizeof(struct _tinydir_dirent)); - } -#endif -#endif - -#ifdef __cplusplus - } -#endif - -# if defined (_MSC_VER) -# pragma warning(pop) -# endif - -#endif // cpPlugins__OS__TINYDIR_H - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/OS/tinydir_COPYING.txt b/lib/cpPlugins/OS/tinydir_COPYING.txt deleted file mode 100644 index 0d31329..0000000 --- a/lib/cpPlugins/OS/tinydir_COPYING.txt +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2013-2016, tinydir authors: -- Cong Xu -- Lautis Sun -- Baudouin Feildel -- Andargor -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/cpPlugins/OS/tinydir_README.md.txt b/lib/cpPlugins/OS/tinydir_README.md.txt deleted file mode 100644 index 3fab002..0000000 --- a/lib/cpPlugins/OS/tinydir_README.md.txt +++ /dev/null @@ -1,78 +0,0 @@ -TinyDir -======= -[![Build Status](https://travis-ci.org/cxong/tinydir.svg?branch=master)](https://travis-ci.org/cxong/tinydir)[![Project Stats](https://www.openhub.net/p/tinydir/widgets/project_thin_badge.gif)](https://www.openhub.net/p/tinydir) - -Lightweight, portable and easy to integrate C directory and file reader. TinyDir wraps dirent for POSIX and FindFirstFile for Windows. - -Windows unicode is supported by defining `UNICODE` and `_UNICODE` before including `tinydir.h`. - -Example -======= - -There are two methods. Error checking omitted: - -```C -tinydir_dir dir; -tinydir_open(&dir, "/path/to/dir"); - -while (dir.has_next) -{ - tinydir_file file; - tinydir_readfile(&dir, &file); - - printf("%s", file.name); - if (file.is_dir) - { - printf("/"); - } - printf("\n"); - - tinydir_next(&dir); -} - -tinydir_close(&dir); -``` - -```C -tinydir_dir dir; -int i; -tinydir_open_sorted(&dir, "/path/to/dir"); - -for (i = 0; i < dir.n_files; i++) -{ - tinydir_file file; - tinydir_readfile_n(&dir, &file, i); - - printf("%s", file.name); - if (file.is_dir) - { - printf("/"); - } - printf("\n"); -} - -tinydir_close(&dir); -``` - -See the `/samples` folder for more examples, including an interactive command-line directory navigator. - -Language -======== - -ANSI C, or C90. - -Platforms -========= - -POSIX and Windows supported. Open to the possibility of supporting other platforms. - -License -======= - -Simplified BSD; if you use tinydir you can comply by including `tinydir.h` or `COPYING` somewhere in your package. - -Known Limitations -================= - -- Limited path and filename sizes -- [Possible race condition bug if folder being read has changing content](https://github.com/cxong/tinydir/issues/13) diff --git a/lib/cpPlugins/Pipeline/DataObject.cxx b/lib/cpPlugins/Pipeline/DataObject.cxx deleted file mode 100644 index 7afa1c7..0000000 --- a/lib/cpPlugins/Pipeline/DataObject.cxx +++ /dev/null @@ -1,92 +0,0 @@ -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::DataObject:: -IsCompatible( const Self* other ) const -{ - return( true ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject* -cpPlugins::Pipeline::DataObject:: -GetSource( ) -{ - return( this->m_Source ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::ProcessObject* -cpPlugins::Pipeline::DataObject:: -GetSource( ) const -{ - return( this->m_Source ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::DataObject:: -SetSource( cpPlugins::Pipeline::ProcessObject* src ) -{ - if( this->m_Source != src ) - { - this->m_Source = src; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::DataObject:: -DisconnectFromPipeline( ) -{ - // Disconnect input pipelines (ITK) - itk::DataObject::Pointer itk_obj = this->GetITK< itk::DataObject >( ); - if( itk_obj.IsNotNull( ) ) - itk_obj->DisconnectPipeline( ); - - // Disconnect input pipelines (VTK) - bool ok = this->_DisconnectVTK< vtkImageData >( ); - if( !ok ) ok = this->_DisconnectVTK< vtkPolyData >( ); - - // Unbind source - this->m_Source = NULL; - this->Modified( ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::DataObject:: -DataObject( ) - : Superclass( ), - m_Source( NULL ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::DataObject:: -~DataObject( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TType > -bool cpPlugins::Pipeline::DataObject:: -_DisconnectVTK( ) -{ - _TType* v = dynamic_cast< _TType* >( this->m_VTK.GetPointer( ) ); - if( v != NULL ) - { - vtkSmartPointer< _TType > d = vtkSmartPointer< _TType >::New( ); - d->ShallowCopy( v ); - this->m_VTK = d; - return( true ); - } - else - return( false ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/DataObject.h b/lib/cpPlugins/Pipeline/DataObject.h deleted file mode 100644 index 04623cf..0000000 --- a/lib/cpPlugins/Pipeline/DataObject.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef __cpPlugins__Pipeline__DataObject__h__ -#define __cpPlugins__Pipeline__DataObject__h__ - -#include - -namespace cpPlugins -{ - namespace Pipeline - { - // Some forward declarations - class ProcessObject; - - /** - */ - class cpPlugins_EXPORT DataObject - : public Object - { - friend class ProcessObject; - - public: - typedef DataObject Self; - typedef Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkNewMacro( Self ); - itkTypeMacro( DataObject, Object ); - cpPlugins_Id_Macro( DataObject, Object ); - - public: - virtual bool IsCompatible( const Self* other ) const; - - ProcessObject* GetSource( ); - const ProcessObject* GetSource( ) const; - void SetSource( ProcessObject* src ); - - void DisconnectFromPipeline( ); - - protected: - DataObject( ); - virtual ~DataObject( ); - - template< class _TType > - inline bool _DisconnectVTK( ); - - private: - // Purposely not implemented - DataObject( const Self& ); - Self& operator=( const Self& ); - - protected: - ProcessObject* m_Source; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__DataObject__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Events.h b/lib/cpPlugins/Pipeline/Events.h deleted file mode 100644 index a675d93..0000000 --- a/lib/cpPlugins/Pipeline/Events.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Events__h__ -#define __cpPlugins__Pipeline__Events__h__ - -#include -#include - -// ------------------------------------------------------------------------- -#define cpPluginsEventsOpenMacro( name ) \ - class name \ - : public itk::AnyEvent \ - { \ - public: \ - typedef name Self; \ - typedef itk::AnyEvent Superclass; \ - public: \ - name( ) : Superclass( ) { } \ - virtual ~name( ) { } \ - const char* GetEventName( ) const \ - { return( "cpPlugins::Pipeline::Events::#name" ); } \ - bool CheckEvent( const itk::EventObject* e ) const \ - { return( dynamic_cast< const Self* >( e ) != NULL ); } \ - itk::EventObject* MakeObject( ) const \ - { return( new Self( ) ); } - -// ------------------------------------------------------------------------- -#define cpPluginsEventsCloseMacro( name ) \ - } - -namespace cpPlugins -{ - namespace Pipeline - { - namespace Events - { - /** - */ - cpPluginsEventsOpenMacro( Modified ) - public: - itk::ModifiedTimeType Time; - long Span; - cpPluginsEventsCloseMacro( Modified ); - - } // ecapseman - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Events__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Functor.cxx b/lib/cpPlugins/Pipeline/Functor.cxx deleted file mode 100644 index 2d7a883..0000000 --- a/lib/cpPlugins/Pipeline/Functor.cxx +++ /dev/null @@ -1,16 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Functor:: -Functor( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Functor:: -~Functor( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Functor.h b/lib/cpPlugins/Pipeline/Functor.h deleted file mode 100644 index 96255b7..0000000 --- a/lib/cpPlugins/Pipeline/Functor.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Functor__h__ -#define __cpPlugins__Pipeline__Functor__h__ - -#include - -// ------------------------------------------------------------------------- -namespace cpPlugins -{ - namespace Pipeline - { - /** - */ - class cpPlugins_EXPORT Functor - : public ProcessObject - { - public: - typedef Functor Self; - typedef ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkTypeMacro( Functor, ProcessObject ); - cpPlugins_Id_Macro( Functor, Object ); - - public: - virtual void Instantiate( itk::LightObject* filter ) = 0; - - template< class _TFunctor > - _TFunctor* GetFunctor( ) - { - return( - dynamic_cast< _TFunctor* >( this->m_Functor.GetPointer( ) ) - ); - } - - template< class _TFunctor > - const _TFunctor* GetFunctor( ) const - { - return( - dynamic_cast< const _TFunctor* >( this->m_Functor.GetPointer( ) ) - ); - } - - protected: - Functor( ); - virtual ~Functor( ); - - private: - // Purposely not implemented - Functor( const Self& ); - Self& operator=( const Self& ); - - protected: - itk::LightObject::Pointer m_Functor; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Functor__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Object.cxx b/lib/cpPlugins/Pipeline/Object.cxx deleted file mode 100644 index abcac9c..0000000 --- a/lib/cpPlugins/Pipeline/Object.cxx +++ /dev/null @@ -1,98 +0,0 @@ -#include - -#include -#include - -// ------------------------------------------------------------------------- -const float& cpPlugins::Pipeline::Object:: -GetViewX( ) const -{ - return( this->m_ViewX ); -} - -// ------------------------------------------------------------------------- -const float& cpPlugins::Pipeline::Object:: -GetViewY( ) const -{ - return( this->m_ViewY ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -SetViewCoords( float x, float y ) -{ - this->m_ViewX = x; - this->m_ViewY = y; - // WARNING: do not call "this->Modified( )" -> It could lead to - // re-execution of all pipeline -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -Modified( ) const -{ - const itk::Object* i = - dynamic_cast< const itk::Object* >( this->m_ITK.GetPointer( ) ); - vtkObject* v = dynamic_cast< vtkObject* >( this->m_VTK.GetPointer( ) ); - if( i != NULL ) i->Modified( ); - if( v != NULL ) v->Modified( ); - this->Superclass::Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -SetITK( itk::LightObject* o ) -{ - if( this->m_ITK.GetPointer( ) != o ) - { - this->m_ITK = o; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -SetVTK( vtkObjectBase* o ) -{ - if( this->m_VTK.GetPointer( ) != o ) - { - this->m_VTK = o; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Object:: -Object( ) - : m_ITK( NULL ), - m_VTK( NULL ), - m_ViewX( float( 0 ) ), - m_ViewY( float( 0 ) ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Object:: -~Object( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -_UpdateITK( ) const -{ - // WARNING: do nothing since this is supposed to be defined by DataObjects - // with ITK-VTK conversion strategies. -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Object:: -_UpdateVTK( ) const -{ - // WARNING: do nothing since this is supposed to be defined by DataObjects - // with ITK-VTK conversion strategies. -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Object.h b/lib/cpPlugins/Pipeline/Object.h deleted file mode 100644 index 4f2b2bd..0000000 --- a/lib/cpPlugins/Pipeline/Object.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Object__h__ -#define __cpPlugins__Pipeline__Object__h__ - -#include - -#include -#include -#include -#include -#include - -namespace cpPlugins -{ - namespace Pipeline - { - /** - */ - class cpPlugins_EXPORT Object - : public itk::Object - { - public: - typedef Object Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkTypeMacro( Object, itk::Object ); - - public: - virtual const char* GetClassName( ) const = 0; - virtual const char* GetClassCategory( ) const = 0; - - const float& GetViewX( ) const; - const float& GetViewY( ) const; - void SetViewCoords( float x, float y ); - - virtual void Modified( ) const override; - - virtual void SetITK( itk::LightObject* o ); - virtual void SetVTK( vtkObjectBase* o ); - - template< class _TType = itk::LightObject > - inline _TType* GetITK( ) - { - if( this->m_ITK.GetPointer( ) == NULL ) - this->_UpdateITK( ); - return( dynamic_cast< _TType* >( this->m_ITK.GetPointer( ) ) ); - } - - template< class _TType = itk::LightObject > - inline const _TType* GetITK( ) const - { - if( this->m_ITK.GetPointer( ) == NULL ) - this->_UpdateITK( ); - return( - dynamic_cast< const _TType* >( this->m_ITK.GetPointer( ) ) - ); - } - - template< class _TType = vtkObjectBase > - inline _TType* GetVTK( ) - { - if( this->m_VTK.GetPointer( ) == NULL ) - this->_UpdateVTK( ); - return( dynamic_cast< _TType* >( this->m_VTK.GetPointer( ) ) ); - } - - template< class _TType = vtkObjectBase > - inline const _TType* GetVTK( ) const - { - if( this->m_VTK.GetPointer( ) == NULL ) - this->_UpdateVTK( ); - return( - dynamic_cast< const _TType* >( this->m_VTK.GetPointer( ) ) - ); - } - - protected: - Object( ); - virtual ~Object( ); - - virtual void _UpdateITK( ) const; - virtual void _UpdateVTK( ) const; - - private: - // Purposely not implemented - Object( const Self& ); - Self& operator=( const Self& ); - - protected: - itk::LightObject::Pointer m_ITK; - vtkSmartPointer< vtkObjectBase > m_VTK; - - float m_ViewX; - float m_ViewY; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Object__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Parameters.cxx b/lib/cpPlugins/Pipeline/Parameters.cxx deleted file mode 100644 index ada5e9c..0000000 --- a/lib/cpPlugins/Pipeline/Parameters.cxx +++ /dev/null @@ -1,742 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Parameters:: -Parameters( ) - : m_ProcessObject( NULL ) -{ - this->Clear( ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Parameters:: -~Parameters( ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject* cpPlugins::Pipeline::Parameters:: -GetProcessObject( ) -{ - return( this->m_ProcessObject ); -} - -// ------------------------------------------------------------------------- -const -cpPlugins::Pipeline::ProcessObject* cpPlugins::Pipeline::Parameters:: -GetProcessObject( ) const -{ - return( this->m_ProcessObject ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -SetProcessObject( cpPlugins::Pipeline::ProcessObject* po ) -{ - this->m_ProcessObject = po; -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -Modified( ) const -{ - if( this->m_ProcessObject != NULL ) - this->m_ProcessObject->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -Clear( ) -{ - this->m_Parameters.clear( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -GetNames( std::vector< std::string >& container ) const -{ - container.clear( ); - TParameters::const_iterator i = this->m_Parameters.begin( ); - for( ; i != this->m_Parameters.end( ); ++i ) - container.push_back( i->first ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Parameters:: -Type cpPlugins::Pipeline::Parameters:: -GetType( const std::string& name ) const -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - return( i->second.first ); - else - return( Self::NoType ); -} - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_TypeAsString( Y ) \ - if( i->second.first == Self::Y ) \ - return( #Y ) - -std::string cpPlugins::Pipeline::Parameters:: -GetTypeAsString( const std::string& name ) const -{ - auto i = this->m_Parameters.find( name ); - cpPlugins_Pipeline_Parameters_TypeAsString( String ); - else cpPlugins_Pipeline_Parameters_TypeAsString( Bool ); - else cpPlugins_Pipeline_Parameters_TypeAsString( Int ); - else cpPlugins_Pipeline_Parameters_TypeAsString( Uint ); - else cpPlugins_Pipeline_Parameters_TypeAsString( Real ); - else cpPlugins_Pipeline_Parameters_TypeAsString( OpenFileName ); - else cpPlugins_Pipeline_Parameters_TypeAsString( SaveFileName ); - else cpPlugins_Pipeline_Parameters_TypeAsString( PathName ); - else cpPlugins_Pipeline_Parameters_TypeAsString( StringList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( BoolList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( IntList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( UintList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( RealList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( OpenFileNameList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( SaveFileNameList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( PathNameList ); - else cpPlugins_Pipeline_Parameters_TypeAsString( Choices ); - else return( "NoType" ); -} - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_TypeFromString( Y, str ) \ - if( str == std::string( #Y ) ) \ - return( Self::Y ) - -cpPlugins::Pipeline::Parameters:: -Type cpPlugins::Pipeline::Parameters:: -GetTypeFromString( const std::string& t ) -{ - cpPlugins_Pipeline_Parameters_TypeFromString( String, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( Bool, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( Int, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( Uint, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( Real, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( OpenFileName, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( SaveFileName, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( PathName, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( StringList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( BoolList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( IntList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( UintList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( RealList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( OpenFileNameList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( SaveFileNameList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( PathNameList, t ); - else cpPlugins_Pipeline_Parameters_TypeFromString( Choices, t ); - else return( Self::NoType ); -} - -// ------------------------------------------------------------------------- -std::string cpPlugins::Pipeline::Parameters:: -GetString( const std::string& name, bool force ) const -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == Self::String || force ) - return( i->second.second ); - else - return( "" ); - } - else - return( "" ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -SetString( const std::string& name, const std::string& v, bool force ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == Self::String || force ) - { - if( i->second.second != v ) - { - i->second.second = v; - this->Modified( ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ConfigureAsChoices( - const std::string& name, const std::vector< std::string >& choices - ) -{ - // It is invalid not to give choices when configuring - if( choices.size( ) == 0 ) - return; - - std::stringstream str_choices; - str_choices << choices[ 0 ]; - for( unsigned int i = 1; i < choices.size( ); ++i ) - str_choices << "#" << choices[ i ]; - str_choices << "@"; - this->m_Parameters[ name ] = - TParameter( Self::Choices, str_choices.str( ) ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ConfigureAsRealTypesChoices( const std::string& name ) -{ - std::vector< std::string > choices; - choices.push_back( "float" ); - choices.push_back( "double" ); - this->ConfigureAsChoices( name, choices ); - this->SetSelectedChoice( name, "float" ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ConfigureAsIntTypesChoices( const std::string& name ) -{ - std::vector< std::string > choices; - choices.push_back( "char" ); - choices.push_back( "uchar" ); - choices.push_back( "short" ); - choices.push_back( "ushort" ); - choices.push_back( "int" ); - choices.push_back( "uint" ); - choices.push_back( "long" ); - choices.push_back( "ulong" ); - this->ConfigureAsChoices( name, choices ); - this->SetSelectedChoice( name, "char" ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ConfigureAsScalarTypesChoices( const std::string& name ) -{ - std::vector< std::string > choices; - choices.push_back( "char" ); - choices.push_back( "uchar" ); - choices.push_back( "short" ); - choices.push_back( "ushort" ); - choices.push_back( "int" ); - choices.push_back( "uint" ); - choices.push_back( "long" ); - choices.push_back( "ulong" ); - choices.push_back( "float" ); - choices.push_back( "double" ); - this->ConfigureAsChoices( name, choices ); - this->SetSelectedChoice( name, "char" ); -} - -// ------------------------------------------------------------------------- -std::vector< std::string > cpPlugins::Pipeline::Parameters:: -GetChoices( const std::string& name ) const -{ - std::vector< std::string > choices; - - TParameters::const_iterator i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == Self::Choices ) - { - std::istringstream str_choices( i->second.second ); - std::string real_choices; - std::getline( str_choices, real_choices, '@' ); - std::istringstream str( real_choices ); - std::string token; - while( std::getline( str, token, '#' ) ) - choices.push_back( token ); - - } // fi - - } // fi - return( choices ); -} - -// ------------------------------------------------------------------------- -std::string cpPlugins::Pipeline::Parameters:: -GetSelectedChoice( const std::string& name ) const -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == Self::Choices ) - { - std::istringstream str_choices( i->second.second ); - std::string real_choice; - std::getline( str_choices, real_choice, '@' ); - std::getline( str_choices, real_choice, '@' ); - return( real_choice ); - } - else - return( "" ); - } - else - return( "" ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::Parameters:: -SetSelectedChoice( const std::string& name, const std::string& choice ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == Self::Choices ) - { - std::istringstream str_choices( i->second.second ); - std::string choices; - std::getline( str_choices, choices, '@' ); - if( choices.find( choice ) != std::string::npos ) - { - std::stringstream new_choices; - new_choices << choices << "@" << choice; - i->second.second = new_choices.str( ); - this->Modified( ); - return( true ); - } - else - return( false ); - } - else - return( false ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -std::string cpPlugins::Pipeline::Parameters:: -GetAcceptedFileExtensions( const std::string& name ) const -{ - auto i = this->m_AcceptedFileExtensions.find( name ); - if( i != this->m_AcceptedFileExtensions.end( ) ) - return( i->second ); - else - return( "" ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -SetAcceptedFileExtensions( - const std::string& name, const std::string& extensions - ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - bool is_valid = ( i->second.first == Self::OpenFileName ); - is_valid |= ( i->second.first == Self::SaveFileName ); - is_valid |= ( i->second.first == Self::OpenFileNameList ); - is_valid |= ( i->second.first == Self::SaveFileNameList ); - if( is_valid ) - this->m_AcceptedFileExtensions[ name ] = extensions; - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::Parameters:: -ToXML( - tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* parent_elem - ) const -{ - if( parent_elem == NULL ) - return( false ); - - auto pIt = this->m_Parameters.begin( ); - for( ; pIt != this->m_Parameters.end( ); ++pIt ) - { - tinyxml2::XMLElement* p = doc->NewElement( "Parameter" ); - p->SetAttribute( "Name", pIt->first.c_str( ) ); - p->SetAttribute( "Value", pIt->second.second.c_str( ) ); - p->SetAttribute( "Type", this->GetTypeAsString( pIt->first ).c_str( ) ); - parent_elem->InsertEndChild( p ); - - } // rof - return( true ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::Parameters:: -FromXML( const tinyxml2::XMLElement* filter_elem ) -{ - const tinyxml2::XMLElement* param = - filter_elem->FirstChildElement( "Parameter" ); - bool ret = false; - while( param != NULL ) - { - const char* param_name = param->Attribute( "Name" ); - const char* param_type = param->Attribute( "Type" ); - if( param_name != NULL && param_type != NULL ) - { - TParameter value; - value.second = param->Attribute( "Value" ); - value.first = Self::GetTypeFromString( param_type ); - this->m_Parameters[ param_name ] = value; - - } // fi - param = param->NextSiblingElement( "Parameter" ); - ret = true; - - } // elihw - this->Modified( ); - return( ret ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Parameters:: -TParameters& cpPlugins::Pipeline::Parameters:: -GetRawParameters( ) -{ - return( this->m_Parameters ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::Parameters:: -TParameters& cpPlugins::Pipeline::Parameters:: -GetRawParameters( ) const -{ - return( this->m_Parameters ); -} - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_Configure_Code( Y ) \ - void cpPlugins::Pipeline::Parameters:: \ - ConfigureAs##Y( const std::string& name, const T##Y& init ) \ - { \ - this->_Configure< Y >( name ); \ - this->Set##Y( name, init ); \ - } \ - bool cpPlugins::Pipeline::Parameters:: \ - Has##Y( const std::string& name ) const \ - { return( this->_Has< Y >( name ) ); } - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_ConfigureList_Code( Y ) \ - void cpPlugins::Pipeline::Parameters:: \ - ConfigureAs##Y##List( const std::string& name ) \ - { this->_Configure< Y##List >( name ); } \ - bool cpPlugins::Pipeline::Parameters:: \ - Has##Y##List( const std::string& name ) const \ - { return( this->_Has< Y##List >( name ) ); } - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_GetSet_Code( Y ) \ - cpPlugins::Pipeline::Parameters::T##Y \ - cpPlugins::Pipeline::Parameters:: \ - Get##Y( const std::string& name ) const \ - { return( this->_Get< T##Y, Y >( name ) ); } \ - void cpPlugins::Pipeline::Parameters::Set##Y( \ - const std::string& name, const T##Y& v \ - ) \ - { this->_Set< T##Y, Y >( name, v ); } - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_GetSetList_Code( Y ) \ - std::vector< cpPlugins::Pipeline::Parameters::T##Y > \ - cpPlugins::Pipeline::Parameters:: \ - Get##Y##List( const std::string& name ) const \ - { return( this->_GetList< T##Y, Y##List >( name ) ); } \ - void cpPlugins::Pipeline::Parameters::AddTo##Y##List( \ - const std::string& name, \ - const cpPlugins::Pipeline::Parameters::T##Y& v \ - ) \ - { this->_AddToList< T##Y, Y##List >( name, v ); } \ - void cpPlugins::Pipeline::Parameters:: \ - Clear##Y##List( const std::string& name ) \ - { this->_ClearList< Y##List >( name ); } - -// ------------------------------------------------------------------------- -cpPlugins_Pipeline_Parameters_Configure_Code( String ); -cpPlugins_Pipeline_Parameters_Configure_Code( Bool ); -cpPlugins_Pipeline_Parameters_Configure_Code( Int ); -cpPlugins_Pipeline_Parameters_Configure_Code( Uint ); -cpPlugins_Pipeline_Parameters_Configure_Code( Real ); -cpPlugins_Pipeline_Parameters_Configure_Code( OpenFileName ); -cpPlugins_Pipeline_Parameters_Configure_Code( SaveFileName ); -cpPlugins_Pipeline_Parameters_Configure_Code( PathName ); - -cpPlugins_Pipeline_Parameters_ConfigureList_Code( String ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( Bool ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( Int ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( Uint ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( Real ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( OpenFileName ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( SaveFileName ); -cpPlugins_Pipeline_Parameters_ConfigureList_Code( PathName ); - -cpPlugins_Pipeline_Parameters_GetSet_Code( Bool ); -cpPlugins_Pipeline_Parameters_GetSet_Code( Int ); -cpPlugins_Pipeline_Parameters_GetSet_Code( Uint ); -cpPlugins_Pipeline_Parameters_GetSet_Code( Real ); -cpPlugins_Pipeline_Parameters_GetSet_Code( OpenFileName ); -cpPlugins_Pipeline_Parameters_GetSet_Code( SaveFileName ); -cpPlugins_Pipeline_Parameters_GetSet_Code( PathName ); - -cpPlugins_Pipeline_Parameters_GetSetList_Code( String ); -cpPlugins_Pipeline_Parameters_GetSetList_Code( Bool ); -cpPlugins_Pipeline_Parameters_GetSetList_Code( Int ); -cpPlugins_Pipeline_Parameters_GetSetList_Code( Uint ); -cpPlugins_Pipeline_Parameters_GetSetList_Code( Real ); -cpPlugins_Pipeline_Parameters_GetSetList_Code( PathName ); - -// ------------------------------------------------------------------------- -std::vector< cpPlugins::Pipeline::Parameters::TOpenFileName > -cpPlugins::Pipeline::Parameters:: -GetOpenFileNameList( const std::string& name ) const -{ - return( this->_GetList< TOpenFileName, OpenFileNameList >( name ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -AddToOpenFileNameList( - const std::string& name, - const cpPlugins::Pipeline::Parameters::TOpenFileName& v - ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == OpenFileNameList ) - { - auto pos = v.find_last_of( "/\\" ); - if( i->second.second == "" ) - i->second.second = v.substr( 0, pos ); - i->second.second += std::string( "#" ); - i->second.second += v.substr( pos + 1 ); - this->Modified( ); - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ClearOpenFileNameList( const std::string& name ) -{ - this->_ClearList< OpenFileNameList >( name ); -} - -// ------------------------------------------------------------------------- -std::vector< cpPlugins::Pipeline::Parameters::TSaveFileName > -cpPlugins::Pipeline::Parameters:: -GetSaveFileNameList( const std::string& name ) const -{ - return( this->_GetList< TSaveFileName, SaveFileNameList >( name ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -AddToSaveFileNameList( - const std::string& name, - const cpPlugins::Pipeline::Parameters::TSaveFileName& v - ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == SaveFileNameList ) - { - auto pos = v.find_last_of( "/\\" ); - if( i->second.second == "" ) - i->second.second = v.substr( 0, pos ); - i->second.second += std::string( "#" ); - i->second.second += v.substr( pos + 1 ); - this->Modified( ); - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Parameters:: -ClearSaveFileNameList( const std::string& name ) -{ - this->_ClearList< SaveFileNameList >( name ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _Enum > -void cpPlugins::Pipeline::Parameters:: -_Configure( const std::string& name ) -{ - this->m_Parameters[ name ] = TParameter( ( Self::Type )( _Enum ), "" ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _Enum > -bool cpPlugins::Pipeline::Parameters:: -_Has( const std::string& name ) const -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - return( i->second.first == ( Self::Type )( _Enum ) ); - else - return( false ); -} - -// ------------------------------------------------------------------------- -template< class _Type, unsigned int _Enum > -_Type cpPlugins::Pipeline::Parameters:: -_Get( const std::string& name ) const -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == ( Self::Type )( _Enum ) ) - { - if( typeid( _Type ) != typeid( std::string ) ) - { - std::istringstream tok_str( i->second.second ); - _Type v; - tok_str >> v; - return( v ); - } - else - { - const _Type* ptr = - reinterpret_cast< const _Type* >( &( i->second.second ) ); - return( *ptr ); - - } // fi - - } // fi - - } // fi - return( _Type( 0 ) ); -} - -// ------------------------------------------------------------------------- -template< class _Type, unsigned int _Enum > -void cpPlugins::Pipeline::Parameters:: -_Set( const std::string& name, const _Type& v ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == ( Self::Type )( _Enum ) ) - { - if( typeid( _Type ) != typeid( std::string ) ) - { - std::stringstream str; - str << v; - if( i->second.second != str.str( ) ) - { - i->second.second = str.str( ); - this->Modified( ); - - } // fi - } - else - { - const std::string* str = reinterpret_cast< const std::string* >( &v ); - if( i->second.second != *str ) - { - i->second.second = *str; - this->Modified( ); - - } // fi - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _Type, unsigned int _Enum > -std::vector< _Type > cpPlugins::Pipeline::Parameters:: -_GetList( const std::string& name ) const -{ - std::vector< _Type > lst; - std::vector< std::string >* slst = - reinterpret_cast< std::vector< std::string >* >( &lst ); - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == ( Self::Type )( _Enum ) ) - { - std::vector< std::string > tokens = - cpPlugins::OS::String::Tokenize( i->second.second, "#" ); - for( auto t = tokens.begin( ); t != tokens.end( ); ++t ) - { - if( typeid( _Type ) != typeid( std::string ) ) - { - std::istringstream tok_str( *t ); - _Type v; - tok_str >> v; - lst.push_back( v ); - } - else - slst->push_back( *t ); - - } // rof - - } // fi - - } // fi - return( lst ); -} - -// ------------------------------------------------------------------------- -template< class _Type, unsigned int _Enum > -void cpPlugins::Pipeline::Parameters:: -_AddToList( const std::string& name, const _Type& v ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == ( Self::Type )( _Enum ) ) - { - std::stringstream str; - if( i->second.second != "" ) - str << i->second.second << "#"; - str << v; - i->second.second = str.str( ); - this->Modified( ); - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -template< unsigned int _Enum > -void cpPlugins::Pipeline::Parameters:: -_ClearList( const std::string& name ) -{ - auto i = this->m_Parameters.find( name ); - if( i != this->m_Parameters.end( ) ) - { - if( i->second.first == ( Self::Type )( _Enum ) ) - { - if( i->second.second != "" ) - { - i->second.second = ""; - this->Modified( ); - - } // fi - - } // fi - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Parameters.h b/lib/cpPlugins/Pipeline/Parameters.h deleted file mode 100644 index 4dbd871..0000000 --- a/lib/cpPlugins/Pipeline/Parameters.h +++ /dev/null @@ -1,223 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Parameters__h__ -#define __cpPlugins__Pipeline__Parameters__h__ - -#include - -#include -#include -#include -#include -#include -#include - -// Some forward declarations -namespace tinyxml2 -{ - class XMLElement; - class XMLDocument; -} - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_Configure( Y ) \ - void ConfigureAs##Y( const std::string& name, const T##Y& init ); \ - bool Has##Y( const std::string& name ) const - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_ConfigureList( Y ) \ - void ConfigureAs##Y##List( const std::string& name ); \ - bool Has##Y##List( const std::string& name ) const - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_GetSet( Y ) \ - T##Y Get##Y( const std::string& name ) const; \ - void Set##Y( const std::string& name, const T##Y& v ) - -// ------------------------------------------------------------------------- -#define cpPlugins_Pipeline_Parameters_GetSetList( Y ) \ - std::vector< T##Y > Get##Y##List( const std::string& name ) const; \ - void AddTo##Y##List( const std::string& name, const T##Y& v ); \ - void Clear##Y##List( const std::string& name ) - -// ------------------------------------------------------------------------- -namespace cpPlugins -{ - namespace QT { class ParametersDialog; } - - namespace Pipeline - { - class ProcessObject; - - /** - */ - class cpPlugins_EXPORT Parameters - { - // Frienship with forward declaration to improve Qt dialog execution - friend class cpPlugins::QT::ParametersDialog; - friend std::ostream& operator<<( std::ostream& o, const Parameters& p ) - { - for( - auto i = p.m_Parameters.begin( ); - i != p.m_Parameters.end( ); - ++i - ) - o << i->first << ": (" - << i->second.first << " | " - << i->second.second << ")" - << std::endl; - return( o ); - } - - public: - typedef Parameters Self; - - enum Type - { - String , Bool , Int , - Uint , Real , OpenFileName , - SaveFileName , PathName , StringList , - BoolList , IntList , UintList , - RealList , OpenFileNameList , SaveFileNameList , - PathNameList , Choices , NoType - }; - - typedef bool TBool; - typedef long TInt; - typedef unsigned long TUint; - typedef double TReal; - typedef std::string TString; - typedef std::string TOpenFileName; - typedef std::string TSaveFileName; - typedef std::string TPathName; - - typedef std::pair< Self::Type, std::string > TParameter; - typedef std::map< std::string, TParameter > TParameters; - - public: - cpPlugins_Pipeline_Parameters_Configure( String ); - cpPlugins_Pipeline_Parameters_Configure( Bool ); - cpPlugins_Pipeline_Parameters_Configure( Int ); - cpPlugins_Pipeline_Parameters_Configure( Uint ); - cpPlugins_Pipeline_Parameters_Configure( Real ); - cpPlugins_Pipeline_Parameters_Configure( OpenFileName ); - cpPlugins_Pipeline_Parameters_Configure( SaveFileName ); - cpPlugins_Pipeline_Parameters_Configure( PathName ); - - cpPlugins_Pipeline_Parameters_ConfigureList( String ); - cpPlugins_Pipeline_Parameters_ConfigureList( Bool ); - cpPlugins_Pipeline_Parameters_ConfigureList( Int ); - cpPlugins_Pipeline_Parameters_ConfigureList( Uint ); - cpPlugins_Pipeline_Parameters_ConfigureList( Real ); - cpPlugins_Pipeline_Parameters_ConfigureList( OpenFileName ); - cpPlugins_Pipeline_Parameters_ConfigureList( SaveFileName ); - cpPlugins_Pipeline_Parameters_ConfigureList( PathName ); - - cpPlugins_Pipeline_Parameters_GetSet( Bool ); - cpPlugins_Pipeline_Parameters_GetSet( Int ); - cpPlugins_Pipeline_Parameters_GetSet( Uint ); - cpPlugins_Pipeline_Parameters_GetSet( Real ); - cpPlugins_Pipeline_Parameters_GetSet( OpenFileName ); - cpPlugins_Pipeline_Parameters_GetSet( SaveFileName ); - cpPlugins_Pipeline_Parameters_GetSet( PathName ); - - cpPlugins_Pipeline_Parameters_GetSetList( String ); - cpPlugins_Pipeline_Parameters_GetSetList( Bool ); - cpPlugins_Pipeline_Parameters_GetSetList( Int ); - cpPlugins_Pipeline_Parameters_GetSetList( Uint ); - cpPlugins_Pipeline_Parameters_GetSetList( Real ); - cpPlugins_Pipeline_Parameters_GetSetList( OpenFileName ); - cpPlugins_Pipeline_Parameters_GetSetList( SaveFileName ); - cpPlugins_Pipeline_Parameters_GetSetList( PathName ); - - public: - Parameters( ); - virtual ~Parameters( ); - - ProcessObject* GetProcessObject( ); - const ProcessObject* GetProcessObject( ) const; - void SetProcessObject( ProcessObject* po ); - virtual void Modified( ) const; - - // Parameters container configuration - void Clear( ); - - // Get methods - void GetNames( std::vector< std::string >& container ) const; - Type GetType( const std::string& name ) const; - std::string GetTypeAsString( const std::string& name ) const; - static Type GetTypeFromString( const std::string& t ); - - // Base string methods - std::string GetString( - const std::string& name, bool force = true - ) const; - void SetString( - const std::string& name, const std::string& v, bool force = true - ); - - void ConfigureAsChoices( - const std::string& name, const std::vector< std::string >& choices - ); - void ConfigureAsRealTypesChoices( const std::string& name ); - void ConfigureAsIntTypesChoices( const std::string& name ); - void ConfigureAsScalarTypesChoices( const std::string& name ); - std::vector< std::string > GetChoices( const std::string& name ) const; - std::string GetSelectedChoice( const std::string& name ) const; - bool SetSelectedChoice( - const std::string& name, const std::string& choice - ); - - std::string GetAcceptedFileExtensions( const std::string& name ) const; - void SetAcceptedFileExtensions( - const std::string& name, const std::string& extensions - ); - - // XML "streaming" - bool ToXML( - tinyxml2::XMLDocument* doc, - tinyxml2::XMLElement* parent_elem - ) const; - bool FromXML( const tinyxml2::XMLElement* filter_elem ); - - protected: - TParameters& GetRawParameters( ); - const TParameters& GetRawParameters( ) const; - - template< unsigned int _Enum > - inline void _Configure( const std::string& name ); - - template< unsigned int _Enum > - inline bool _Has( const std::string& name ) const; - - template< class _Type, unsigned int _Enum > - inline _Type _Get( const std::string& name ) const; - - template< class _Type, unsigned int _Enum > - inline void _Set( const std::string& name, const _Type& v ); - - template< class _Type, unsigned int _Enum > - inline std::vector< _Type > _GetList( const std::string& name ) const; - - template< class _Type, unsigned int _Enum > - inline void _AddToList( const std::string& name, const _Type& v ); - - template< unsigned int _Enum > - inline void _ClearList( const std::string& name ); - - private: - // Purposely not implemented - Parameters( const Self& other ); - Self& operator=( const Self& other ); - - protected: - ProcessObject* m_ProcessObject; - TParameters m_Parameters; - std::map< std::string, std::string > m_AcceptedFileExtensions; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Parameters__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Port.cxx b/lib/cpPlugins/Pipeline/Port.cxx deleted file mode 100644 index 4c980c0..0000000 --- a/lib/cpPlugins/Pipeline/Port.cxx +++ /dev/null @@ -1,231 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Port:: -Port( bool required ) - : m_Required( required ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Port:: -~Port( ) -{ -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::Port:: -IsRequired( ) const -{ - return( this->m_Required ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Port:: -Clear( ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::SingleDataPort:: -SingleDataPort( bool required ) - : Superclass( required ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::SingleDataPort:: -~SingleDataPort( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::SingleDataPort:: -Add( cpPlugins::Pipeline::DataObject* o ) -{ - if( this->m_Sample.IsNull( ) ) - throw std::logic_error( - "cpPlugins::SingleDataPort: Port not yet configured" - ); - if( o != NULL ) - { - if( this->m_Sample->IsCompatible( o ) ) - this->m_Data = o; - else - throw std::logic_error( - "cpPlugins::SingleDataPort: incompatible types \"" + - std::string( typeid( *o ).name( ) ) + std::string( "\" and \"" ) + - std::string( typeid( *( this->m_Sample.GetPointer( ) ) ).name( ) ) + - std::string( "\"" ) - ); - } - else - this->m_Data = NULL; -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::DataObject* cpPlugins::Pipeline::SingleDataPort:: -Get( unsigned int i ) -{ - return( this->m_Data.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::DataObject* cpPlugins::Pipeline::SingleDataPort:: -Get( unsigned int i ) const -{ - return( this->m_Data.GetPointer( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpPlugins::Pipeline::SingleDataPort:: -Size( ) const -{ - return( 1 ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::SingleDataPort:: -IsValid( ) const -{ - return( this->m_Data.IsNotNull( ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::SingleDataPort:: -Clear( ) -{ - this->m_Data = NULL; -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::OutputPort:: -OutputPort( bool required ) - : Superclass( required ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::OutputPort:: -~OutputPort( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::OutputPort:: -Set( DataObject* o ) -{ - this->m_Sample = o; - this->m_Data = o; -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::InputPort:: -InputPort( bool required ) - : Superclass( required ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::InputPort:: -~InputPort( ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::MultipleInputsPort:: -MultipleInputsPort( bool required ) - : Superclass( required ) -{ -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::MultipleInputsPort:: -~MultipleInputsPort( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::MultipleInputsPort:: -Add( cpPlugins::Pipeline::DataObject* o ) -{ - if( this->m_Sample.IsNull( ) ) - throw std::logic_error( - "cpPlugins::SingleDataPort: Port not yet configured" - ); - if( o != NULL ) - { - if( this->m_Sample->IsCompatible( o ) ) - { - this->m_Data.push_back( o ); - } - else - throw std::logic_error( - "cpPlugins::SingleDataPort: incompatible types \"" + - std::string( typeid( *o ).name( ) ) + std::string( "\" and \"" ) + - std::string( typeid( *( this->m_Sample.GetPointer( ) ) ).name( ) ) + - std::string( "\"" ) - ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::DataObject* -cpPlugins::Pipeline::MultipleInputsPort:: -Get( unsigned int i ) -{ - if( i < this->m_Data.size( ) ) - return( this->m_Data[ i ].GetPointer( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::DataObject* -cpPlugins::Pipeline::MultipleInputsPort:: -Get( unsigned int i ) const -{ - if( i < this->m_Data.size( ) ) - return( this->m_Data[ i ].GetPointer( ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -unsigned int cpPlugins::Pipeline::MultipleInputsPort:: -Size( ) const -{ - return( this->m_Data.size( ) ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::MultipleInputsPort:: -IsValid( ) const -{ - if( this->m_Data.size( ) > 0 ) - return( this->m_Data[ 0 ].IsNotNull( ) ); - else - return( false ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::MultipleInputsPort:: -Clear( ) -{ - this->m_Data.clear( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::MultipleInputsPort:: -Delete( unsigned int id ) -{ - if( id < this->m_Data.size( ) ) - { - this->m_Data[ id ] = NULL; - this->m_Data.erase( this->m_Data.begin( ) + id ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Port.h b/lib/cpPlugins/Pipeline/Port.h deleted file mode 100644 index 98d81e7..0000000 --- a/lib/cpPlugins/Pipeline/Port.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Port__h__ -#define __cpPlugins__Pipeline__Port__h__ - -#include -#include - -namespace cpPlugins -{ - namespace Pipeline - { - /** - */ - class cpPlugins_EXPORT Port - { - public: - typedef Port Self; - - public: - Port( bool required = true ); - virtual ~Port( ); - - virtual void Add( DataObject* o ) = 0; - virtual DataObject* Get( unsigned int i = 0 ) = 0; - virtual const DataObject* Get( unsigned int i = 0 ) const = 0; - virtual unsigned int Size( ) const = 0; - virtual bool IsValid( ) const = 0; - - virtual bool IsRequired( ) const; - virtual void Clear( ); - - template< class _TType > - inline void Configure( ) { this->m_Sample = _TType::New( ); } - - protected: - bool m_Required; - DataObject::Pointer m_Sample; - }; - - /** - */ - class cpPlugins_EXPORT SingleDataPort - : public Port - { - public: - typedef SingleDataPort Self; - typedef Port Superclass; - - public: - SingleDataPort( bool required = true ); - virtual ~SingleDataPort( ); - - virtual void Add( DataObject* o ) override; - virtual DataObject* Get( unsigned int i = 0 ) override; - virtual const DataObject* Get( unsigned int i = 0 ) const override; - virtual unsigned int Size( ) const override; - virtual bool IsValid( ) const override; - virtual void Clear( ) override; - - protected: - DataObject::Pointer m_Data; - }; - - /** - */ - class cpPlugins_EXPORT OutputPort - : public SingleDataPort - { - public: - typedef OutputPort Self; - typedef SingleDataPort Superclass; - typedef Port BaseClass; - - public: - OutputPort( bool required = true ); - virtual ~OutputPort( ); - - void Set( DataObject* o ); - }; - - /** - */ - class cpPlugins_EXPORT InputPort - : public SingleDataPort - { - public: - typedef InputPort Self; - typedef SingleDataPort Superclass; - typedef Port BaseClass; - - public: - InputPort( bool required = true ); - virtual ~InputPort( ); - }; - - /** - */ - class cpPlugins_EXPORT MultipleInputsPort - : public Port - { - public: - typedef MultipleInputsPort Self; - typedef Port Superclass; - - public: - MultipleInputsPort( bool required = true ); - virtual ~MultipleInputsPort( ); - - virtual void Add( DataObject* o ) override; - virtual DataObject* Get( unsigned int i = 0 ) override; - virtual const DataObject* Get( unsigned int i = 0 ) const override; - virtual unsigned int Size( ) const override; - virtual bool IsValid( ) const override; - virtual void Clear( ) override; - - void Delete( unsigned int id ); - - protected: - std::vector< DataObject::Pointer > m_Data; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Port__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/ProcessObject.cxx b/lib/cpPlugins/Pipeline/ProcessObject.cxx deleted file mode 100644 index bb0bbed..0000000 --- a/lib/cpPlugins/Pipeline/ProcessObject.cxx +++ /dev/null @@ -1,377 +0,0 @@ -#include -#include -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -PrintExecutionOn( ) -{ - this->SetPrintExecution( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -PrintExecutionOff( ) -{ - this->SetPrintExecution( false ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::ProcessObject:: -GetPrintExecution( ) const -{ - return( this->m_PrintExecution ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -SetPrintExecution( bool v ) -{ - this->m_PrintExecution = v; -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -SetPrintExecutionStream( std::ofstream* s ) -{ - this->m_PrintExecutionStream = s; -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Parameters* -cpPlugins::Pipeline::ProcessObject:: -GetParameters( ) -{ - return( &( this->m_Parameters ) ); -} - -// ------------------------------------------------------------------------- -const cpPlugins::Pipeline::Parameters* -cpPlugins::Pipeline::ProcessObject:: -GetParameters( ) const -{ - return( &( this->m_Parameters ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -SetITK( itk::LightObject* o ) -{ - // Polymorphism: do nothing -> this is a filter!!! -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -SetVTK( vtkObjectBase* o ) -{ - // Polymorphism: do nothing -> this is a filter!!! -} - -// ------------------------------------------------------------------------- -std::set< std::string > cpPlugins::Pipeline::ProcessObject:: -GetInputsNames( ) const -{ - std::set< std::string > names; - for( auto i = this->m_Inputs.begin( ); i != this->m_Inputs.end( ); ++i ) - names.insert( i->first ); - return( names ); -} - -// ------------------------------------------------------------------------- -std::set< std::string > cpPlugins::Pipeline::ProcessObject:: -GetOutputsNames( ) const -{ - std::set< std::string > names; - for( auto i = this->m_Outputs.begin( ); i != this->m_Outputs.end( ); ++i ) - names.insert( i->first ); - return( names ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::ProcessObject:: -HasInput( const std::string& n ) const -{ - auto i = this->m_Inputs.find( n ); - return( i != this->m_Inputs.end( ) ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::ProcessObject:: -HasOutput( const std::string& n ) const -{ - auto i = this->m_Outputs.find( n ); - return( i != this->m_Outputs.end( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpPlugins::Pipeline::ProcessObject:: -GetNumberOfInputs( ) const -{ - return( this->m_Inputs.size( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpPlugins::Pipeline::ProcessObject:: -GetNumberOfOutputs( ) const -{ - return( this->m_Outputs.size( ) ); -} - -// ------------------------------------------------------------------------- -unsigned int cpPlugins::Pipeline::ProcessObject:: -GetInputSize( const std::string& n ) const -{ - auto it = this->m_Inputs.find( n ); - if( it != this->m_Inputs.end( ) ) - return( it->second->Size( ) ); - else - return( 0 ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::ProcessObject:: -IsInputMultiple( const std::string& n ) const -{ - auto i = this->m_Inputs.find( n ); - if( i != this->m_Inputs.end( ) ) - return( dynamic_cast< MultipleInputsPort* >( i->second ) != NULL ); - else - return( false ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -AddInput( const std::string& n, cpPlugins::Pipeline::DataObject* o ) -{ - auto it = this->m_Inputs.find( n ); - if( it != this->m_Inputs.end( ) ) - it->second->Add( o ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -SetInput( const std::string& n, cpPlugins::Pipeline::DataObject* o ) -{ - this->AddInput( n, o ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -DisconnectInput( const std::string& n, unsigned int id ) -{ - auto inIt = this->m_Inputs.find( n ); - if( inIt != this->m_Inputs.end( ) ) - { - auto multi = dynamic_cast< MultipleInputsPort* >( inIt->second ); - auto single = dynamic_cast< InputPort* >( inIt->second ); - if( multi != NULL ) - multi->Delete( id ); - else if( single != NULL ) - single->Add( NULL ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -DisconnectInputs( ) -{ - for( auto i = this->m_Inputs.begin( ); i != this->m_Inputs.end( ); ++i ) - i->second->Clear( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -DisconnectOutputs( ) -{ - for( auto i = this->m_Outputs.begin( ); i != this->m_Outputs.end( ); ++i ) - if( i->second->IsValid( ) ) - i->second->Get( )->DisconnectFromPipeline( ); - this->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -Disconnect( ) -{ - this->DisconnectInputs( ); - this->DisconnectOutputs( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -Modified( ) const -{ - this->Superclass::Modified( ); - - cpPlugins::Pipeline::Events::Modified evt; - evt.Time = this->m_LastExecutionTime; - evt.Span = this->m_LastExecutionSpan; - this->InvokeEvent( evt ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -Update( ) -{ - // Force upstream updates - bool update = ( this->m_LastExecutionTime < this->GetMTime( ) ); - try - { - for( auto input : this->m_Inputs ) - { - for( unsigned int i = 0; i < input.second->Size( ); ++i ) - { - auto obj = input.second->Get( i ); - if( obj != NULL ) - { - auto src = obj->GetSource( ); - if( src != NULL ) - { - src->Update( ); - update |= ( this->m_LastExecutionTime < src->GetMTime( ) ); - - } // fi - } - else - { - if( input.second->IsRequired( ) ) - this->_Error( - std::string( "Required input \"" ) + input.first + - std::string( "\" in filter \"" ) + - this->m_Name + - std::string( "\" is not valid." ) - ); - - } // fi - - } // rof - - } // rof - } - catch( std::exception& err ) - { - this->_Error( err.what( ) ); - - } // yrt - - if( update || this->m_ExplicitExecution ) - { - // Show a message, if needed... - if( this->m_PrintExecution && this->m_PrintExecutionStream != NULL ) - { - *( this->m_PrintExecutionStream ) - << "cpPlugins: Updating \"" - << this->GetName( ) << " (" - << this->GetClassCategory( ) << ":" << this->GetClassName( ) - << ")\"... "; - this->m_PrintExecutionStream->flush( ); - - } // fi - - // Execute filter's algorithm and keep information about time - try - { - auto t_start = cpPlugins_CHRONO; - this->_GenerateData( ); - auto t_end = cpPlugins_CHRONO; - this->Modified( ); - this->m_LastExecutionSpan = long( t_end - t_start ); - this->m_LastExecutionTime = this->GetMTime( ); - - // End the message, if needed... - if( this->m_PrintExecution && this->m_PrintExecutionStream != NULL ) - { - *( this->m_PrintExecutionStream ) - << "done in " - << double( this->m_LastExecutionSpan ) / double( 1000 ) - << " s." << std::endl; - - } // fi - } - catch( std::exception& err ) - { - this->_Error( err.what( ) ); - - } // yrt - - } // fi -} - -// ------------------------------------------------------------------------- -QDialog* cpPlugins::Pipeline::ProcessObject:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::ParametersDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::ParametersDialog( ); - dlg->setProcessObject( this ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -AddInteractor( vtkRenderWindowInteractor* i ) -{ -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::ProcessObject:: -IsInteractive( ) -{ - return( false ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject:: -ProcessObject( ) - : Superclass( ), - m_Name( "" ), - m_PluginName( "" ), - m_ExplicitExecution( false ), - m_LastExecutionTime( 0 ), - m_LastExecutionSpan( -1 ), - m_PrintExecution( false ), - m_PrintExecutionStream( &( std::cout ) ) -{ - this->m_Parameters.SetProcessObject( this ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject:: -~ProcessObject( ) -{ - for( auto i = this->m_Inputs.begin( ); i != this->m_Inputs.end( ); ++i ) - delete i->second; - for( auto o = this->m_Outputs.begin( ); o != this->m_Outputs.end( ); ++o ) - delete o->second; - - this->m_Inputs.clear( ); - this->m_Outputs.clear( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::ProcessObject:: -_Error( const std::string& error ) -{ - if( error != "" ) - itkExceptionMacro( - "Error: \"" << this->m_Name << "\": " << error - ); -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/ProcessObject.h b/lib/cpPlugins/Pipeline/ProcessObject.h deleted file mode 100644 index c2ce34c..0000000 --- a/lib/cpPlugins/Pipeline/ProcessObject.h +++ /dev/null @@ -1,168 +0,0 @@ -#ifndef __cpPlugins__Pipeline__ProcessObject__h__ -#define __cpPlugins__Pipeline__ProcessObject__h__ - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -class QDialog; -class vtkRenderWindowInteractor; - -// ------------------------------------------------------------------------- -namespace cpPlugins -{ - namespace Pipeline - { - /** - */ - class cpPlugins_EXPORT ProcessObject - : public Object - { - public: - typedef ProcessObject Self; - typedef Object Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkTypeMacro( ProcessObject, Object ); - cpPlugins_Id_Macro( ProcessObject, Object ); - - itkBooleanMacro( ExplicitExecution ); - - itkGetStringMacro( Name ); - itkGetStringMacro( PluginName ); - itkGetConstMacro( ExplicitExecution, bool ); - itkGetConstMacro( LastExecutionSpan, long ); - - itkSetStringMacro( Name ); - itkSetStringMacro( PluginName ); - itkSetMacro( ExplicitExecution, bool ); - - public: - void PrintExecutionOn( ); - void PrintExecutionOff( ); - bool GetPrintExecution( ) const; - void SetPrintExecution( bool v ); - void SetPrintExecutionStream( std::ofstream* s ); - - Parameters* GetParameters( ); - const Parameters* GetParameters( ) const; - - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - // "Getters" - std::set< std::string > GetInputsNames( ) const; - std::set< std::string > GetOutputsNames( ) const; - bool HasInput( const std::string& n ) const; - bool HasOutput( const std::string& n ) const; - - unsigned int GetNumberOfInputs( ) const; - unsigned int GetNumberOfOutputs( ) const; - unsigned int GetInputSize( const std::string& n ) const; - bool IsInputMultiple( const std::string& n ) const; - - template< class _TType = DataObject > - inline _TType* GetInput( const std::string& n, unsigned int i = 0 ); - - template< class _TType = DataObject > - inline const _TType* GetInput( - const std::string& n, unsigned int i = 0 - ) const; - - template< class _TType = itk::LightObject > - inline _TType* GetInputData( const std::string& n, unsigned int i = 0 ); - - template< class _TType = itk::LightObject > - inline const _TType* GetInputData( - const std::string& n, unsigned int i = 0 - ) const; - - template< class _TType = DataObject > - inline _TType* GetOutput( const std::string& n ); - - template< class _TType = DataObject > - inline const _TType* GetOutput( const std::string& n ) const; - - template< class _TType = itk::LightObject > - inline _TType* GetOutputData( const std::string& n ); - - template< class _TType = itk::LightObject > - inline const _TType* GetOutputData( const std::string& n ) const; - - // "Setters" - virtual void AddInput( const std::string& n, DataObject* o ); - virtual void SetInput( const std::string& n, DataObject* o ); - - // Other interesting methods - void DisconnectInput( const std::string& n, unsigned int id ); - void DisconnectInputs( ); - void DisconnectOutputs( ); - void Disconnect( ); - - // Pipeline execution - virtual void Modified( ) const override; - virtual void Update( ); - - // Qt dialog creation - virtual QDialog* CreateQDialog( ); - virtual void AddInteractor( vtkRenderWindowInteractor* i ); - virtual bool IsInteractive( ); - - protected: - ProcessObject( ); - virtual ~ProcessObject( ); - - // Error handling method - void _Error( const std::string& error ); - - // For configuration purposes - template< class _TType = DataObject > - inline void _ConfigureInput( - const std::string& name, bool required, bool multiple - ); - - template< class _TType = DataObject > - inline void _ConfigureOutput( const std::string& name ); - - template< class _TFilter > - inline _TFilter* _CreateITK( ); - - template< class _TFilter > - inline _TFilter* _CreateVTK( ); - - virtual void _GenerateData( ) = 0; - - private: - // Purposely not implemented - ProcessObject( const Self& ); - Self& operator=( const Self& ); - - protected: - Parameters m_Parameters; - std::string m_Name; - std::string m_PluginName; - bool m_ExplicitExecution; - - std::map< std::string, Port* > m_Inputs; - std::map< std::string, Port* > m_Outputs; - - itk::ModifiedTimeType m_LastExecutionTime; - mutable long m_LastExecutionSpan; - - bool m_PrintExecution; - std::ostream* m_PrintExecutionStream; - }; - - } // ecapseman - -} // ecapseman - -#include - -#endif // __cpPlugins__Pipeline__ProcessObject__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/ProcessObject.hxx b/lib/cpPlugins/Pipeline/ProcessObject.hxx deleted file mode 100644 index 47cd480..0000000 --- a/lib/cpPlugins/Pipeline/ProcessObject.hxx +++ /dev/null @@ -1,293 +0,0 @@ -#ifndef __cpPlugins__Pipeline__ProcessObject__hxx__ -#define __cpPlugins__Pipeline__ProcessObject__hxx__ - -// ------------------------------------------------------------------------- -template< class _TType > -_TType* cpPlugins::Pipeline::ProcessObject:: -GetInput( const std::string& n, unsigned int i ) -{ - auto it = this->m_Inputs.find( n ); - if( it != this->m_Inputs.end( ) ) - return( dynamic_cast< _TType* >( it->second->Get( i ) ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -const _TType* cpPlugins::Pipeline::ProcessObject:: -GetInput( const std::string& n, unsigned int i ) const -{ - auto it = this->m_Inputs.find( n ); - if( it != this->m_Inputs.end( ) ) - return( dynamic_cast< const _TType* >( it->second->Get( i ) ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -_TType* cpPlugins::Pipeline::ProcessObject:: -GetInputData( const std::string& n, unsigned int i ) -{ - auto d = this->GetInput( n, i ); - if( d != NULL ) - { - auto oi = d->m_ITK.GetPointer( ); - auto ov = d->m_VTK.GetPointer( ); - if( oi != NULL && ov != NULL ) - { - auto di = dynamic_cast< _TType* >( oi ); - auto dv = dynamic_cast< _TType* >( ov ); - if ( di != NULL ) return( di ); - else if( dv != NULL ) return( dv ); - else return( NULL ); - } - else if( oi != NULL && ov == NULL ) - { - auto di = dynamic_cast< _TType* >( oi ); - if( di == NULL ) - return( d->GetVTK< _TType >( ) ); - else - return( di ); - } - else if( oi == NULL && ov != NULL ) - { - auto dv = dynamic_cast< _TType* >( ov ); - if( dv == NULL ) - return( d->GetITK< _TType >( ) ); - else - return( dv ); - } - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -const _TType* cpPlugins::Pipeline::ProcessObject:: -GetInputData( const std::string& n, unsigned int i ) const -{ - auto d = this->GetInput( n, i ); - if( d != NULL ) - { - auto oi = d->m_ITK.GetPointer( ); - auto ov = d->m_VTK.GetPointer( ); - if( oi != NULL && ov != NULL ) - { - auto di = dynamic_cast< const _TType* >( oi ); - auto dv = dynamic_cast< const _TType* >( ov ); - if ( di != NULL ) return( di ); - else if( dv != NULL ) return( dv ); - else return( NULL ); - } - else if( oi != NULL && ov == NULL ) - { - auto di = dynamic_cast< const _TType* >( oi ); - if( di == NULL ) - return( d->GetVTK< _TType >( ) ); - else - return( di ); - } - else if( oi == NULL && ov != NULL ) - { - auto dv = dynamic_cast< const _TType* >( ov ); - if( dv == NULL ) - return( d->GetITK< _TType >( ) ); - else - return( dv ); - } - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -_TType* cpPlugins::Pipeline::ProcessObject:: -GetOutput( const std::string& n ) -{ - auto it = this->m_Outputs.find( n ); - if( it != this->m_Outputs.end( ) ) - return( dynamic_cast< _TType* >( it->second->Get( ) ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -const _TType* cpPlugins::Pipeline::ProcessObject:: -GetOutput( const std::string& n ) const -{ - auto it = this->m_Outputs.find( n ); - if( it != this->m_Outputs.end( ) ) - return( dynamic_cast< const _TType* >( it->second->Get( ) ) ); - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -_TType* cpPlugins::Pipeline::ProcessObject:: -GetOutputData( const std::string& n ) -{ - auto d = this->GetOutput( n ); - if( d != NULL ) - { - auto oi = d->m_ITK.GetPointer( ); - auto ov = d->m_VTK.GetPointer( ); - if( oi != NULL && ov != NULL ) - { - auto di = dynamic_cast< _TType* >( oi ); - auto dv = dynamic_cast< _TType* >( ov ); - if ( di != NULL ) return( di ); - else if( dv != NULL ) return( dv ); - else return( NULL ); - } - else if( oi != NULL && ov == NULL ) - { - auto di = dynamic_cast< _TType* >( oi ); - if( di == NULL ) - return( d->GetVTK< _TType >( ) ); - else - return( di ); - } - else if( oi == NULL && ov != NULL ) - { - auto dv = dynamic_cast< _TType* >( ov ); - if( dv == NULL ) - return( d->GetITK< _TType >( ) ); - else - return( dv ); - } - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -const _TType* cpPlugins::Pipeline::ProcessObject:: -GetOutputData( const std::string& n ) const -{ - auto d = this->GetOutput( n ); - if( d != NULL ) - { - auto oi = d->m_ITK.GetPointer( ); - auto ov = d->m_VTK.GetPointer( ); - if( oi != NULL && ov != NULL ) - { - auto di = dynamic_cast< const _TType* >( oi ); - auto dv = dynamic_cast< const _TType* >( ov ); - if ( di != NULL ) return( di ); - else if( dv != NULL ) return( dv ); - else return( NULL ); - } - else if( oi != NULL && ov == NULL ) - { - auto di = dynamic_cast< const _TType* >( oi ); - if( di == NULL ) - return( d->GetVTK< _TType >( ) ); - else - return( di ); - } - else if( oi == NULL && ov != NULL ) - { - auto dv = dynamic_cast< const _TType* >( ov ); - if( dv == NULL ) - return( d->GetITK< _TType >( ) ); - else - return( dv ); - } - else - return( NULL ); - } - else - return( NULL ); -} - -// ------------------------------------------------------------------------- -template< class _TType > -void cpPlugins::Pipeline::ProcessObject:: -_ConfigureInput( const std::string& name, bool required, bool multiple ) -{ - auto it = this->m_Inputs.find( name ); - if( it == this->m_Inputs.end( ) ) - { - Port* port; - if( multiple ) port = new MultipleInputsPort( required ); - else port = new InputPort( required ); - port->Configure< _TType >( ); - this->m_Inputs[ name ] = port; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TType > -void cpPlugins::Pipeline::ProcessObject:: -_ConfigureOutput( const std::string& name ) -{ - auto it = this->m_Outputs.find( name ); - if( it == this->m_Outputs.end( ) ) - { - Port* port = new OutputPort( true ); - port->Configure< _TType >( ); - port->Add( _TType::New( ) ); - port->Get( )->SetSource( this ); - this->m_Outputs[ name ] = port; - this->Modified( ); - - } // fi -} - -// ------------------------------------------------------------------------- -template< class _TFilter > -_TFilter* cpPlugins::Pipeline::ProcessObject:: -_CreateITK( ) -{ - // TODO: why this lead to synch issues??? - _TFilter* filter = this->GetITK< _TFilter >( ); - if( filter == NULL ) - { - typename _TFilter::Pointer filter_ptr = _TFilter::New( ); - this->m_ITK = filter_ptr; - this->m_VTK = NULL; - filter = filter_ptr.GetPointer( ); - this->Modified( ); - - } // fi - return( filter ); -} - -// ------------------------------------------------------------------------- -template< class _TFilter > -_TFilter* cpPlugins::Pipeline::ProcessObject:: -_CreateVTK( ) -{ - // TODO: why this lead to synch issues??? - _TFilter* filter = this->GetVTK< _TFilter >( ); - if( filter == NULL ) - { - vtkSmartPointer< _TFilter > filter_ptr = - vtkSmartPointer< _TFilter >::New( ); - this->m_ITK = NULL; - this->m_VTK = filter_ptr; - filter = filter_ptr.GetPointer( ); - this->Modified( ); - - } // fi - return( filter ); -} - -#endif // __cpPlugins__Pipeline__ProcessObject__hxx__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Widget.cxx b/lib/cpPlugins/Pipeline/Widget.cxx deleted file mode 100644 index 482bed9..0000000 --- a/lib/cpPlugins/Pipeline/Widget.cxx +++ /dev/null @@ -1,46 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Widget:: -AddInteractor( vtkRenderWindowInteractor* i ) -{ - if( this->m_Interactors.insert( i ).second ) - this->Modified( ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::Pipeline::Widget:: -IsInteractive( ) -{ - return( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Widget:: -EnabledOn( ) -{ - this->SetEnabled( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::Pipeline::Widget:: -EnabledOff( ) -{ - this->SetEnabled( false ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Widget:: -Widget( ) - : Superclass( ) -{ - this->m_Parameters.ConfigureAsString( "Text", "" ); -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::Widget:: -~Widget( ) -{ -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/Pipeline/Widget.h b/lib/cpPlugins/Pipeline/Widget.h deleted file mode 100644 index 5d35594..0000000 --- a/lib/cpPlugins/Pipeline/Widget.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef __cpPlugins__Pipeline__Widget__h__ -#define __cpPlugins__Pipeline__Widget__h__ - -#include -#include - -// ------------------------------------------------------------------------- -namespace cpPlugins -{ - namespace Pipeline - { - /** - */ - class cpPlugins_EXPORT Widget - : public ProcessObject - { - public: - typedef Widget Self; - typedef ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkTypeMacro( Widget, ProcessObject ); - cpPlugins_Id_Macro( Widget, Object ); - - public: - virtual void AddInteractor( vtkRenderWindowInteractor* i ) override; - virtual bool IsInteractive( ) override; - - virtual void EnabledOn( ); - virtual void EnabledOff( ); - virtual void Clear( ) = 0; - virtual void SetEnabled( bool v ) = 0; - virtual bool GetEnabled( ) const = 0; - - protected: - Widget( ); - virtual ~Widget( ); - - private: - // Purposely not implemented - Widget( const Self& ); - Self& operator=( const Self& ); - - protected: - typedef vtkSmartPointer< vtkRenderWindowInteractor > _TInteractor; - struct _TInteractorCmp - { - bool operator()( - const _TInteractor& a, const _TInteractor& b - ) const - { return( a.GetPointer( ) < b.GetPointer( ) ); } - }; - std::set< _TInteractor, _TInteractorCmp > m_Interactors; - - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__Pipeline__Widget__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/OpenFileDialog.cxx b/lib/cpPlugins/QT/OpenFileDialog.cxx deleted file mode 100644 index 784d111..0000000 --- a/lib/cpPlugins/QT/OpenFileDialog.cxx +++ /dev/null @@ -1,107 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -cpPlugins::QT::OpenFileDialog:: -OpenFileDialog( QWidget* parent ) - : QFileDialog( parent ), - m_Parameters( NULL ), - m_Name( "" ) -{ - this->connect( - this, SIGNAL( accepted( ) ), this, SLOT( _dlg_Accepted( ) ) - ); - this->setWindowTitle( "Open an(some) file(s)" ); -} - -// ------------------------------------------------------------------------- -cpPlugins::QT::OpenFileDialog:: -~OpenFileDialog( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::OpenFileDialog:: -SetParameters( - cpPlugins::Pipeline::Parameters* params, const std::string& name - ) -{ - if( params == NULL ) - { - this->m_Parameters = NULL; - this->m_Name = ""; - return; - - } // fi - auto param_type = params->GetType( name ); - if( - param_type != cpPlugins::Pipeline::Parameters::OpenFileName && - param_type != cpPlugins::Pipeline::Parameters::OpenFileNameList - ) - { - this->m_Parameters = NULL; - this->m_Name = ""; - return; - - } // fi - this->m_Parameters = params; - this->m_Name = name; - - QStringList filters; - auto extensions = this->m_Parameters->GetAcceptedFileExtensions( name ); - if( extensions != "" ) - filters << extensions.c_str( ); - filters << "Any file (*)"; - if( param_type == cpPlugins::Pipeline::Parameters::OpenFileName ) - this->setFileMode( QFileDialog::ExistingFile ); - else - this->setFileMode( QFileDialog::ExistingFiles ); - this->setNameFilters( filters ); - this->setAcceptMode( QFileDialog::AcceptOpen ); - if( param_type == cpPlugins::Pipeline::Parameters::OpenFileName ) - { - auto file = this->m_Parameters->GetOpenFileName( this->m_Name ); - if( file == "" ) - file = "."; - QFileInfo info( file.c_str( ) ); - this->setDirectory( info.canonicalPath( ) ); - } - else - { - auto files = this->m_Parameters->GetOpenFileNameList( this->m_Name ); - if( files.size( ) > 0 ) - { - QFileInfo info( files[ 0 ].c_str( ) ); - this->setDirectory( info.canonicalPath( ) ); - } - else - this->setDirectory( "." ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::OpenFileDialog:: -_dlg_Accepted( ) -{ - if( this->m_Parameters != NULL ) - { - auto files = this->selectedFiles( ); - auto param_type = this->m_Parameters->GetType( this->m_Name ); - if( param_type == cpPlugins::Pipeline::Parameters::OpenFileNameList ) - { - this->m_Parameters->ClearOpenFileNameList( this->m_Name ); - for( auto fIt = files.begin( ); fIt != files.end( ); ++fIt ) - this->m_Parameters->AddToOpenFileNameList( - this->m_Name, fIt->toStdString( ) - ); - } - else - this->m_Parameters->SetOpenFileName( - this->m_Name, files[ 0 ].toStdString( ) - ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/OpenFileDialog.h b/lib/cpPlugins/QT/OpenFileDialog.h deleted file mode 100644 index 2a69404..0000000 --- a/lib/cpPlugins/QT/OpenFileDialog.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef __cpPlugins__QT__OpenFileDialog__h__ -#define __cpPlugins__QT__OpenFileDialog__h__ - -#include -#include - -namespace cpPlugins{ namespace Pipeline { class Parameters; } } - -namespace cpPlugins -{ - namespace QT - { - /** - */ - class OpenFileDialog - : public QFileDialog - { - Q_OBJECT; - public: - OpenFileDialog( QWidget* parent = 0 ); - virtual ~OpenFileDialog( ); - - void SetParameters( - cpPlugins::Pipeline::Parameters* params, const std::string& name - ); - - protected slots: - void _dlg_Accepted( ); - - protected: - cpPlugins::Pipeline::Parameters* m_Parameters; - std::string m_Name; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__QT__OpenFileDialog__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/ParametersDialog.cxx b/lib/cpPlugins/QT/ParametersDialog.cxx deleted file mode 100644 index 39f1276..0000000 --- a/lib/cpPlugins/QT/ParametersDialog.cxx +++ /dev/null @@ -1,888 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPlugins::QT::ParametersDialog:: -ParametersDialog( QWidget* parent, Qt::WindowFlags f, bool manual ) - : QDialog( parent, f ), - m_ProcessObject( NULL ), - m_WidgetsUpdated( false ), - m_Manual( manual ) -{ - if( !this->m_Manual ) - { - this->m_Title = new QLabel( this ); - this->m_Title->setText( "Parameters dialog title" ); - this->m_MainLayout = new QGridLayout( this ); - this->m_ToolsLayout = new QVBoxLayout( ); - this->m_ToolsLayout->addWidget( this->m_Title ); - this->m_MainLayout->addLayout( this->m_ToolsLayout, 0, 0, 1, 1 ); - - } // fi - this->connect( - this, SIGNAL( accepted( ) ), this, SLOT( _dlg_Accepted( ) ) - ); -} - -// ------------------------------------------------------------------------- -cpPlugins::QT::ParametersDialog:: -~ParametersDialog( ) -{ - if( !this->m_Manual ) - { - delete this->m_Title; - delete this->m_ToolsLayout; - delete this->m_MainLayout; - - } // fi -} - -// ------------------------------------------------------------------------- -cpPlugins::Pipeline::ProcessObject* -cpPlugins::QT::ParametersDialog:: -getProcessObject( ) const -{ - return( this->m_ProcessObject ); -} - -// ------------------------------------------------------------------------- -bool cpPlugins::QT::ParametersDialog:: -setProcessObject( cpPlugins::Pipeline::ProcessObject* obj ) -{ - if( this->m_ProcessObject != NULL || obj == NULL ) - return( false ); - this->m_ProcessObject = obj; - this->m_WidgetsUpdated = false; - this->_updateWidgets( ); - this->updateView( ); - return( true ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -updateParameters( ) -{ - if( this->m_ProcessObject == NULL ) - return; - if( this->m_Manual ) - return; - - // Check if an explicit re-execution button is needed - QCheckBox* v_bool = - this->findChild< QCheckBox* >( "___ExplicitExecution___" ); - if( v_bool != NULL ) - this->m_ProcessObject->SetExplicitExecution( v_bool->isChecked( ) ); - - // Put values - auto parameters = this->m_ProcessObject->GetParameters( ); - auto& raw_params = parameters->GetRawParameters( ); - for( auto pIt = raw_params.begin( ); pIt != raw_params.end( ); ++pIt ) - { - QString pName = pIt->first.c_str( ); - switch( pIt->second.first ) - { - case cpPlugins::Pipeline::Parameters::String: - case cpPlugins::Pipeline::Parameters::OpenFileName: - case cpPlugins::Pipeline::Parameters::SaveFileName: - case cpPlugins::Pipeline::Parameters::PathName: - case cpPlugins::Pipeline::Parameters::IntList: - case cpPlugins::Pipeline::Parameters::UintList: - case cpPlugins::Pipeline::Parameters::RealList: - case cpPlugins::Pipeline::Parameters::OpenFileNameList: - { - QLineEdit* v_string = this->findChild< QLineEdit* >( pName ); - if( v_string != NULL ) - pIt->second.second = v_string->text( ).toStdString( ); - } - break; - case cpPlugins::Pipeline::Parameters::Bool: - { - QCheckBox* v_bool = this->findChild< QCheckBox* >( pName ); - if( v_bool != NULL ) - pIt->second.second = ( v_bool->isChecked( ) )? "1": "0"; - } - break; - case cpPlugins::Pipeline::Parameters::Int: - case cpPlugins::Pipeline::Parameters::Uint: - { - QSpinBox* v_uint = this->findChild< QSpinBox* >( pName ); - if( v_uint ) - { - std::stringstream str; - str << v_uint->value( ); - pIt->second.second = str.str( ); - - } // fi - } - break; - case cpPlugins::Pipeline::Parameters::Real: - { - QDoubleSpinBox* v_double = this->findChild< QDoubleSpinBox* >( pName ); - if( v_double ) - { - std::stringstream str; - str << v_double->value( ); - pIt->second.second = str.str( ); - - } // fi - } - break; - case cpPlugins::Pipeline::Parameters::StringList: - break; - case cpPlugins::Pipeline::Parameters::BoolList: - break; - case cpPlugins::Pipeline::Parameters::SaveFileNameList: - break; - case cpPlugins::Pipeline::Parameters::PathNameList: - break; - case cpPlugins::Pipeline::Parameters::Choices: - { - QComboBox* v_choices = this->findChild< QComboBox* >( pName ); - if( v_choices != NULL ) - { - std::istringstream str_choices( pIt->second.second ); - std::string real_choices; - std::getline( str_choices, real_choices, '@' ); - pIt->second.second = - real_choices + "@" + - v_choices->currentText( ).toStdString( ); - - } // fi - } - break; - default: - break; - } // hctiws - - } // rof - this->m_ProcessObject->Modified( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -updateView( ) -{ - if( this->m_ProcessObject == NULL ) - return; - if( this->m_Manual ) - return; - - // Check if an explicit re-execution button is needed - QCheckBox* v_bool = - this->findChild< QCheckBox* >( "___ExplicitExecution___" ); - if( v_bool != NULL ) - v_bool->setChecked( this->m_ProcessObject->GetExplicitExecution( ) ); - - // Put values - auto parameters = this->m_ProcessObject->GetParameters( ); - auto& raw_params = parameters->GetRawParameters( ); - for( auto pIt = raw_params.begin( ); pIt != raw_params.end( ); ++pIt ) - { - QString pName = pIt->first.c_str( ); - switch( pIt->second.first ) - { - case cpPlugins::Pipeline::Parameters::String: - case cpPlugins::Pipeline::Parameters::OpenFileName: - case cpPlugins::Pipeline::Parameters::SaveFileName: - case cpPlugins::Pipeline::Parameters::PathName: - case cpPlugins::Pipeline::Parameters::IntList: - case cpPlugins::Pipeline::Parameters::UintList: - case cpPlugins::Pipeline::Parameters::RealList: - case cpPlugins::Pipeline::Parameters::OpenFileNameList: - { - QLineEdit* v_string = this->findChild< QLineEdit* >( pName ); - if( v_string != NULL ) - v_string->setText( pIt->second.second.c_str( ) ); - } - break; - case cpPlugins::Pipeline::Parameters::Bool: - { - QCheckBox* v_bool = this->findChild< QCheckBox* >( pName ); - if( v_bool != NULL ) - v_bool->setChecked( pIt->second.second == "1" ); - } - break; - case cpPlugins::Pipeline::Parameters::Int: - case cpPlugins::Pipeline::Parameters::Uint: - { - QSpinBox* v_uint = this->findChild< QSpinBox* >( pName ); - if( v_uint ) - { - std::istringstream tok_str( pIt->second.second ); - int v; - tok_str >> v; - v_uint->setValue( v ); - - } // fi - } - break; - case cpPlugins::Pipeline::Parameters::Real: - { - QDoubleSpinBox* v_double = this->findChild< QDoubleSpinBox* >( pName ); - if( v_double ) - { - std::istringstream tok_str( pIt->second.second ); - double v; - tok_str >> v; - v_double->setValue( v ); - - } // fi - } - break; - case cpPlugins::Pipeline::Parameters::StringList: - break; - case cpPlugins::Pipeline::Parameters::BoolList: - break; - case cpPlugins::Pipeline::Parameters::SaveFileNameList: - break; - case cpPlugins::Pipeline::Parameters::PathNameList: - break; - case cpPlugins::Pipeline::Parameters::Choices: - { - QComboBox* v_choices = this->findChild< QComboBox* >( pName ); - if( v_choices != NULL ) - { - std::istringstream str_choices( pIt->second.second ); - std::string choices, real_choice; - std::getline( str_choices, choices, '@' ); - std::getline( str_choices, real_choice, '@' ); - std::istringstream str( choices ); - std::string token; - int id = -1, cont = 0; - while( std::getline( str, token, '#' ) ) - { - if( token == real_choice ) - id = cont; - cont++; - - } // elihw - - if( id > -1 ) - v_choices->setCurrentIndex( id ); - - } // fi - } - break; - default: - break; - } // hctiws - - } // rof -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_addButtons( ) -{ - if( this->m_Manual ) - return; - - // Add buttons - this->m_Buttons = new QDialogButtonBox( - QDialogButtonBox::Ok | QDialogButtonBox::Cancel - ); - this->connect( - this->m_Buttons, SIGNAL( accepted( ) ), this, SLOT( accept( ) ) - ); - this->connect( - this->m_Buttons, SIGNAL( rejected( ) ), this, SLOT( reject( ) ) - ); - this->m_ToolsLayout->addWidget( this->m_Buttons ); - - this->updateView( ); - this->m_WidgetsUpdated = true; -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_updateWidgets( ) -{ - if( this->m_WidgetsUpdated || this->m_ProcessObject == NULL ) - return; - if( this->m_Manual ) - return; - - // Set dialog title - std::stringstream title; - title - << "Parameters for an object of class \"" - << this->m_ProcessObject->GetClassName( ) - << "\""; - this->m_Title->setText( title.str( ).c_str( ) ); - - // Check if an explicit re-execution button is needed - QCheckBox* v_bool = new QCheckBox( this ); - v_bool->setObjectName( "___ExplicitExecution___" ); - v_bool->setText( "Explicit re-execution" ); - v_bool->setChecked( this->m_ProcessObject->GetExplicitExecution( ) ); - - QHBoxLayout* new_layout = new QHBoxLayout( ); - new_layout->addWidget( v_bool ); - this->m_ToolsLayout->addLayout( new_layout ); - - // Put values - auto parameters = this->m_ProcessObject->GetParameters( ); - auto& raw_params = parameters->GetRawParameters( ); - for( auto pIt = raw_params.begin( ); pIt != raw_params.end( ); ++pIt ) - { - QWidget* w_input = NULL; - switch( pIt->second.first ) - { - case cpPlugins::Pipeline::Parameters::String: - { - QLineEdit* v_string = new QLineEdit( this ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - w_input = v_string; - } - break; - case cpPlugins::Pipeline::Parameters::Bool: - { - QCheckBox* v_bool = new QCheckBox( this ); - v_bool->setObjectName( pIt->first.c_str( ) ); - v_bool->setText( "[ON/OFF]" ); - v_bool->setChecked( pIt->second.second == "1" ); - w_input = v_bool; - } - break; - case cpPlugins::Pipeline::Parameters::Int: - case cpPlugins::Pipeline::Parameters::Uint: - { - std::istringstream tok_str( pIt->second.second ); - int v; - tok_str >> v; - QSpinBox* v_uint = new QSpinBox( this ); - v_uint->setObjectName( pIt->first.c_str( ) ); - if( pIt->second.first == cpPlugins::Pipeline::Parameters::Uint ) - v_uint->setMinimum( 0 ); - else - v_uint->setMinimum( -std::numeric_limits< int >::max( ) ); - v_uint->setMaximum( std::numeric_limits< int >::max( ) ); - v_uint->setValue( v ); - w_input = v_uint; - } - break; - case cpPlugins::Pipeline::Parameters::Real: - { - std::istringstream tok_str( pIt->second.second ); - double v; - tok_str >> v; - QDoubleSpinBox* v_double = new QDoubleSpinBox( this ); - v_double->setObjectName( pIt->first.c_str( ) ); - v_double->setDecimals( 3 ); - v_double->setMinimum( -std::numeric_limits< double >::max( ) ); - v_double->setMaximum( std::numeric_limits< double >::max( ) ); - v_double->setValue( v ); - w_input = v_double; - } - break; - case cpPlugins::Pipeline::Parameters::OpenFileName: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "..." ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_OpenSingleFile( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - case cpPlugins::Pipeline::Parameters::SaveFileName: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "..." ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_SaveSingleFile( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::PathName: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "..." ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_OpenSinglePath( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::StringList: - break; - case cpPlugins::Pipeline::Parameters::BoolList: - break; - case cpPlugins::Pipeline::Parameters::IntList: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "+" ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_AddInt( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::UintList: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "+" ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_AddUint( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::RealList: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "+" ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_AddReal( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::OpenFileNameList: - { - QFrame* frame = new QFrame( this ); - QHBoxLayout* layout = new QHBoxLayout( frame ); - QLineEdit* v_string = new QLineEdit( frame ); - v_string->setObjectName( pIt->first.c_str( ) ); - v_string->setMaxLength( std::numeric_limits< int >::max( ) ); - v_string->setText( pIt->second.second.c_str( ) ); - QPushButton* v_button = new QPushButton( frame ); - v_button->setObjectName( ( pIt->first + "_=?btn" ).c_str( ) ); - v_button->setText( "..." ); - v_button->connect( - v_button, SIGNAL( clicked( ) ), - this, SLOT( _dlg_OpenMultipleFiles( ) ) - ); - layout->addWidget( v_string ); - layout->addWidget( v_button ); - w_input = frame; - } - break; - case cpPlugins::Pipeline::Parameters::SaveFileNameList: - break; - case cpPlugins::Pipeline::Parameters::PathNameList: - break; - case cpPlugins::Pipeline::Parameters::Choices: - { - QComboBox* v_choices = new QComboBox( this ); - v_choices->setObjectName( pIt->first.c_str( ) ); - - std::istringstream str0( pIt->second.second ); - std::string choices; - std::getline( str0, choices, '@' ); - std::istringstream str1( choices ); - std::string token; - int id = 0; - while( std::getline( str1, token, '#' ) ) - v_choices->insertItem( id++, token.c_str( ) ); - w_input = v_choices; - } - break; - default: - w_input = NULL; - break; - } // hctiws - - // Ok, a representation was created - if( w_input != NULL ) - { - QHBoxLayout* new_layout = new QHBoxLayout( ); - QLabel* label = new QLabel( this ); - label->setText( QString( pIt->first.c_str( ) ) ); - new_layout->addWidget( label ); - new_layout->addWidget( w_input ); - this->m_ToolsLayout->addLayout( new_layout ); - - } // fi - - } // rof - - // Update values - this->_addButtons( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_Accepted( ) -{ - this->updateParameters( ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_OpenSingleFile( ) -{ - auto parameters = this->m_ProcessObject->GetParameters( ); - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - std::string param_value = parameters->GetOpenFileName( param_name ); - if( param_value == "" ) - param_value = "."; - QStringList dialog_filters; - std::string extensions = parameters->GetAcceptedFileExtensions( param_name ); - if( extensions != "" ) - dialog_filters << extensions.c_str( ); - dialog_filters << "Any file (*)"; - - // Show dialog and check if it was accepted - QFileDialog dialog( this ); - dialog.setFileMode( QFileDialog::ExistingFile ); - dialog.setDirectory( QFileDialog::tr( param_value.c_str( ) ) ); - dialog.setNameFilters( dialog_filters ); - dialog.setAcceptMode( QFileDialog::AcceptOpen ); - if( dialog.exec( ) ) - line->setText( *( dialog.selectedFiles( ).begin( ) ) ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_SaveSingleFile( ) -{ - auto parameters = this->m_ProcessObject->GetParameters( ); - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - std::string param_value = parameters->GetSaveFileName( param_name ); - if( param_value == "" ) - param_value = "."; - QStringList dialog_filters; - std::string extensions = parameters->GetAcceptedFileExtensions( param_name ); - if( extensions != "" ) - dialog_filters << extensions.c_str( ); - dialog_filters << "Any file (*)"; - - // Show dialog and check if it was accepted - QFileDialog dialog( this ); - dialog.setFileMode( QFileDialog::AnyFile ); - dialog.setDirectory( QFileDialog::tr( param_value.c_str( ) ) ); - dialog.setNameFilters( dialog_filters ); - dialog.setAcceptMode( QFileDialog::AcceptSave ); - if( dialog.exec( ) ) - line->setText( *( dialog.selectedFiles( ).begin( ) ) ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_OpenSinglePath( ) -{ - auto parameters = this->m_ProcessObject->GetParameters( ); - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - std::string param_value = parameters->GetPathName( param_name ); - if( param_value == "" ) - param_value = "."; - - // Show dialog and check if it was accepted - QFileDialog dialog( this ); - dialog.setFileMode( QFileDialog::Directory ); - dialog.setDirectory( QFileDialog::tr( param_value.c_str( ) ) ); - dialog.setAcceptMode( QFileDialog::AcceptOpen ); - if( dialog.exec( ) ) - line->setText( *( dialog.selectedFiles( ).begin( ) ) ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_OpenMultipleFiles( ) -{ - auto parameters = this->m_ProcessObject->GetParameters( ); - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - QStringList dialog_filters; - std::string extensions = parameters->GetAcceptedFileExtensions( param_name ); - if( extensions != "" ) - dialog_filters << extensions.c_str( ); - dialog_filters << "Any file (*)"; - - // Show dialog and check if it was accepted - QFileDialog dialog( this ); - dialog.setFileMode( QFileDialog::ExistingFiles ); - dialog.setNameFilters( dialog_filters ); - dialog.setAcceptMode( QFileDialog::AcceptOpen ); - if( dialog.exec( ) ) - { - if( dialog.selectedFiles( ).size( ) > 0 ) - { - std::stringstream str; - auto files = dialog.selectedFiles( ); - auto fIt = files.begin( ); - str << fIt->toStdString( ); - ++fIt; - for( ; fIt != files.end( ); ++fIt ) - str << "#" << fIt->toStdString( ); - line->setText( str.str( ).c_str( ) ); - - } // fi - - } // fi - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_AddInt( ) -{ - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - bool ok; - int value = - QInputDialog::getInt( - this, - ( - std::string( "Add new value to \"" ) + - param_name + - std::string( "\"" ) - ).c_str( ), - "Value:", - 0, - -std::numeric_limits< int >::max( ), - std::numeric_limits< int >::max( ), - 1, &ok - ); - if( ok ) - { - std::string values = line->text( ).toStdString( ); - if( values != "" ) - values += "#"; - std::stringstream str; - str << values << value; - line->setText( str.str( ).c_str( ) ); - - } // fi - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_AddUint( ) -{ - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - bool ok; - int value = - QInputDialog::getInt( - this, - ( - std::string( "Add new value to \"" ) + - param_name + - std::string( "\"" ) - ).c_str( ), - "Value:", - 0, 0, std::numeric_limits< int >::max( ), 1, - &ok - ); - if( ok ) - { - std::string values = line->text( ).toStdString( ); - if( values != "" ) - values += "#"; - std::stringstream str; - str << values << value; - line->setText( str.str( ).c_str( ) ); - - } // fi - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::ParametersDialog:: -_dlg_AddReal( ) -{ - QPushButton* btn = dynamic_cast< QPushButton* >( this->sender( ) ); - if( btn != NULL ) - { - std::string bName = btn->objectName( ).toStdString( ); - std::string line_name = bName.substr( 0, bName.find( "_=?btn" ) ); - QLineEdit* line = this->findChild< QLineEdit* >( line_name.c_str( ) ); - if( line != NULL ) - { - std::string param_name = line->objectName( ).toStdString( ); - if( param_name != "" ) - { - bool ok; - double value = - QInputDialog::getDouble( - this, - ( - std::string( "Add new value to \"" ) + - param_name + - std::string( "\"" ) - ).c_str( ), - "Value:", - 0, - -std::numeric_limits< double >::max( ), - std::numeric_limits< double >::max( ), - 1, &ok - ); - if( ok ) - { - std::string values = line->text( ).toStdString( ); - if( values != "" ) - values += "#"; - std::stringstream str; - str << values << value; - line->setText( str.str( ).c_str( ) ); - - } // fi - - } // fi - - } // fi - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/ParametersDialog.h b/lib/cpPlugins/QT/ParametersDialog.h deleted file mode 100644 index 37a6863..0000000 --- a/lib/cpPlugins/QT/ParametersDialog.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef __cpPlugins__QT__ParametersDialog__h__ -#define __cpPlugins__QT__ParametersDialog__h__ - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace cpPlugins -{ - namespace QT - { - /** - */ - class cpPlugins_EXPORT ParametersDialog - : public QDialog - { - Q_OBJECT; - - public: - ParametersDialog( - QWidget* parent = 0, Qt::WindowFlags f = 0, bool manual = false - ); - virtual ~ParametersDialog( ); - - cpPlugins::Pipeline::ProcessObject* getProcessObject( ) const; - virtual bool setProcessObject( - cpPlugins::Pipeline::ProcessObject* obj - ); - - virtual void updateParameters( ); - virtual void updateView( ); - - protected: - virtual void _addButtons( ); - virtual void _updateWidgets( ); - - protected slots: - virtual void _dlg_Accepted( ); - virtual void _dlg_OpenSingleFile( ); - virtual void _dlg_SaveSingleFile( ); - virtual void _dlg_OpenSinglePath( ); - virtual void _dlg_OpenMultipleFiles( ); - virtual void _dlg_AddInt( ); - virtual void _dlg_AddUint( ); - virtual void _dlg_AddReal( ); - - protected: - cpPlugins::Pipeline::ProcessObject* m_ProcessObject; - bool m_WidgetsUpdated; - bool m_Manual; - QLabel* m_Title; - QGridLayout* m_MainLayout; - QVBoxLayout* m_ToolsLayout; - QDialogButtonBox* m_Buttons; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__QT__ParametersDialog__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/SaveFileDialog.cxx b/lib/cpPlugins/QT/SaveFileDialog.cxx deleted file mode 100644 index d42af95..0000000 --- a/lib/cpPlugins/QT/SaveFileDialog.cxx +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include - -// ------------------------------------------------------------------------- -cpPlugins::QT::SaveFileDialog:: -SaveFileDialog( QWidget* parent ) - : QFileDialog( parent ), - m_Parameters( NULL ), - m_Name( "" ) -{ - this->connect( - this, SIGNAL( accepted( ) ), this, SLOT( _dlg_Accepted( ) ) - ); - this->setWindowTitle( "Save a file" ); -} - -// ------------------------------------------------------------------------- -cpPlugins::QT::SaveFileDialog:: -~SaveFileDialog( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::SaveFileDialog:: -SetParameters( - cpPlugins::Pipeline::Parameters* params, const std::string& name - ) -{ - if( params == NULL ) - { - this->m_Parameters = NULL; - this->m_Name = ""; - return; - - } // fi - auto param_type = params->GetType( name ); - if( param_type != cpPlugins::Pipeline::Parameters::SaveFileName ) - { - this->m_Parameters = NULL; - this->m_Name = ""; - return; - - } // fi - this->m_Parameters = params; - this->m_Name = name; - - QStringList filters; - auto extensions = this->m_Parameters->GetAcceptedFileExtensions( name ); - if( extensions != "" ) - filters << extensions.c_str( ); - filters << "Any file (*)"; - this->setFileMode( QFileDialog::AnyFile ); - this->setNameFilters( filters ); - this->setAcceptMode( QFileDialog::AcceptOpen ); - auto file = this->m_Parameters->GetSaveFileName( this->m_Name ); - if( file == "" ) - file = "."; - QFileInfo info( file.c_str( ) ); - this->setDirectory( info.canonicalPath( ) ); -} - -// ------------------------------------------------------------------------- -void cpPlugins::QT::SaveFileDialog:: -_dlg_Accepted( ) -{ - if( this->m_Parameters != NULL ) - { - auto files = this->selectedFiles( ); - this->m_Parameters->SetSaveFileName( - this->m_Name, files[ 0 ].toStdString( ) - ); - - } // fi -} - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/QT/SaveFileDialog.h b/lib/cpPlugins/QT/SaveFileDialog.h deleted file mode 100644 index f290ead..0000000 --- a/lib/cpPlugins/QT/SaveFileDialog.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef __cpPlugins__QT__SaveFileDialog__h__ -#define __cpPlugins__QT__SaveFileDialog__h__ - -#include -#include - -namespace cpPlugins{ namespace Pipeline { class Parameters; } } - -namespace cpPlugins -{ - namespace QT - { - /** - */ - class SaveFileDialog - : public QFileDialog - { - Q_OBJECT; - public: - SaveFileDialog( QWidget* parent = 0 ); - virtual ~SaveFileDialog( ); - - void SetParameters( - cpPlugins::Pipeline::Parameters* params, const std::string& name - ); - - protected slots: - void _dlg_Accepted( ); - - protected: - cpPlugins::Pipeline::Parameters* m_Parameters; - std::string m_Name; - }; - - } // ecapseman - -} // ecapseman - -#endif // __cpPlugins__QT__SaveFileDialog__h__ - -// eof - $RCSfile$ diff --git a/lib/cpPlugins/tinyxml2/OLD_CMakeLists.txt.old b/lib/cpPlugins/tinyxml2/OLD_CMakeLists.txt.old deleted file mode 100644 index 6579b71..0000000 --- a/lib/cpPlugins/tinyxml2/OLD_CMakeLists.txt.old +++ /dev/null @@ -1,32 +0,0 @@ -SET(lib_NAME cpPlugins_tinyxml2) -SET(lib_DIR third_party/tinyxml) - -IF(MSVC) - ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS) -ENDIF(MSVC) - -ADD_LIBRARY(${lib_NAME} SHARED tinyxml2.cpp tinyxml2.h) -SET_TARGET_PROPERTIES( - ${lib_NAME} PROPERTIES - VERSION "${prj_VER}" - SOVERSION "${prj_sVER}" - ) -GENERATE_EXPORT_HEADER( - ${lib_NAME} - BASE_NAME ${lib_NAME} - EXPORT_MACRO_NAME ${lib_NAME}_EXPORT - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/lib/${lib_DIR}/${lib_NAME}_Export.h - STATIC_DEFINE ${lib_NAME}_BUILT_AS_STATIC - ) -INSTALL( - TARGETS ${lib_NAME} - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib/static - ) -INSTALL( - FILES tinyxml2.h - DESTINATION include - ) - -## eof - $RCSfile$ diff --git a/lib/cpPlugins/tinyxml2/readme.md b/lib/cpPlugins/tinyxml2/readme.md deleted file mode 100644 index 30424c3..0000000 --- a/lib/cpPlugins/tinyxml2/readme.md +++ /dev/null @@ -1,324 +0,0 @@ -TinyXML-2 [![TravisCI Status](https://travis-ci.org/leethomason/tinyxml2.svg?branch=master)](https://travis-ci.org/leethomason/tinyxml2) [![AppVeyor Status](https://ci.appveyor.com/api/projects/status/github/leethomason/tinyxml2?branch=master&svg=true)](https://ci.appveyor.com/project/leethomason/tinyxml2) -========= -![TinyXML-2 Logo](http://www.grinninglizard.com/tinyxml2/TinyXML2_small.png) - -TinyXML-2 is a simple, small, efficient, C++ XML parser that can be -easily integrated into other programs. - -The master is hosted on github: -https://github.com/leethomason/tinyxml2 - -The online HTML version of these docs: -http://grinninglizard.com/tinyxml2docs/index.html - -Examples are in the "related pages" tab of the HTML docs. - -What it does. -------------- - -In brief, TinyXML-2 parses an XML document, and builds from that a -Document Object Model (DOM) that can be read, modified, and saved. - -XML stands for "eXtensible Markup Language." It is a general purpose -human and machine readable markup language to describe arbitrary data. -All those random file formats created to store application data can -all be replaced with XML. One parser for everything. - -http://en.wikipedia.org/wiki/XML - -There are different ways to access and interact with XML data. -TinyXML-2 uses a Document Object Model (DOM), meaning the XML data is parsed -into a C++ objects that can be browsed and manipulated, and then -written to disk or another output stream. You can also construct an XML document -from scratch with C++ objects and write this to disk or another output -stream. You can even use TinyXML-2 to stream XML programmatically from -code without creating a document first. - -TinyXML-2 is designed to be easy and fast to learn. It is one header and -one cpp file. Simply add these to your project and off you go. -There is an example file - xmltest.cpp - to get you started. - -TinyXML-2 is released under the ZLib license, -so you can use it in open source or commercial code. The details -of the license are at the top of every source file. - -TinyXML-2 attempts to be a flexible parser, but with truly correct and -compliant XML output. TinyXML-2 should compile on any reasonably C++ -compliant system. It does not rely on exceptions, RTTI, or the STL. - -What it doesn't do. -------------------- - -TinyXML-2 doesn't parse or use DTDs (Document Type Definitions) or XSLs -(eXtensible Stylesheet Language.) There are other parsers out there -that are much more fully featured. But they are also much bigger, -take longer to set up in your project, have a higher learning curve, -and often have a more restrictive license. If you are working with -browsers or have more complete XML needs, TinyXML-2 is not the parser for you. - -TinyXML-1 vs. TinyXML-2 ------------------------ - -TinyXML-2 is now the focus of all development, well tested, and your -best choice unless you have a requirement to maintain TinyXML-1 code. - -TinyXML-2 uses a similar API to TinyXML-1 and the same -rich test cases. But the implementation of the parser is completely re-written -to make it more appropriate for use in a game. It uses less memory, is faster, -and uses far fewer memory allocations. - -TinyXML-2 has no requirement for STL, but has also dropped all STL support. All -strings are query and set as 'const char*'. This allows the use of internal -allocators, and keeps the code much simpler. - -Both parsers: - -1. Simple to use with similar APIs. -2. DOM based parser. -3. UTF-8 Unicode support. http://en.wikipedia.org/wiki/UTF-8 - -Advantages of TinyXML-2 - -1. The focus of all future dev. -2. Many fewer memory allocation (1/10th to 1/100th), uses less memory - (about 40% of TinyXML-1), and faster. -3. No STL requirement. -4. More modern C++, including a proper namespace. -5. Proper and useful handling of whitespace - -Advantages of TinyXML-1 - -1. Can report the location of parsing errors. -2. Support for some C++ STL conventions: streams and strings -3. Very mature and well debugged code base. - -Features --------- - -### Memory Model - -An XMLDocument is a C++ object like any other, that can be on the stack, or -new'd and deleted on the heap. - -However, any sub-node of the Document, XMLElement, XMLText, etc, can only -be created by calling the appropriate XMLDocument::NewElement, NewText, etc. -method. Although you have pointers to these objects, they are still owned -by the Document. When the Document is deleted, so are all the nodes it contains. - -### White Space - -#### Whitespace Preservation (default) - -Microsoft has an excellent article on white space: http://msdn.microsoft.com/en-us/library/ms256097.aspx - -By default, TinyXML-2 preserves white space in a (hopefully) sane way that is almost complient with the -spec. (TinyXML-1 used a completely different model, much more similar to 'collapse', below.) - -As a first step, all newlines / carriage-returns / line-feeds are normalized to a -line-feed character, as required by the XML spec. - -White space in text is preserved. For example: - - Hello, World - -The leading space before the "Hello" and the double space after the comma are -preserved. Line-feeds are preserved, as in this example: - - Hello again, - World - -However, white space between elements is **not** preserved. Although not strictly -compliant, tracking and reporting inter-element space is awkward, and not normally -valuable. TinyXML-2 sees these as the same XML: - - - 1 - 2 - 3 - - - 123 - -#### Whitespace Collapse - -For some applications, it is preferable to collapse whitespace. Collapsing -whitespace gives you "HTML-like" behavior, which is sometimes more suitable -for hand typed documents. - -TinyXML-2 supports this with the 'whitespace' parameter to the XMLDocument constructor. -(The default is to preserve whitespace, as described above.) - -However, you may also use COLLAPSE_WHITESPACE, which will: - -* Remove leading and trailing whitespace -* Convert newlines and line-feeds into a space character -* Collapse a run of any number of space characters into a single space character - -Note that (currently) there is a performance impact for using COLLAPSE_WHITESPACE. -It essentially causes the XML to be parsed twice. - -### Entities - -TinyXML-2 recognizes the pre-defined "character entities", meaning special -characters. Namely: - - & & - < < - > > - " " - ' ' - -These are recognized when the XML document is read, and translated to their -UTF-8 equivalents. For instance, text with the XML of: - - Far & Away - -will have the Value() of "Far & Away" when queried from the XMLText object, -and will be written back to the XML stream/file as an ampersand. - -Additionally, any character can be specified by its Unicode code point: -The syntax ` ` or ` ` are both to the non-breaking space character. -This is called a 'numeric character reference'. Any numeric character reference -that isn't one of the special entities above, will be read, but written as a -regular code point. The output is correct, but the entity syntax isn't preserved. - -### Printing - -#### Print to file -You can directly use the convenience function: - - XMLDocument doc; - ... - doc.SaveFile( "foo.xml" ); - -Or the XMLPrinter class: - - XMLPrinter printer( fp ); - doc.Print( &printer ); - -#### Print to memory -Printing to memory is supported by the XMLPrinter. - - XMLPrinter printer; - doc.Print( &printer ); - // printer.CStr() has a const char* to the XML - -#### Print without an XMLDocument - -When loading, an XML parser is very useful. However, sometimes -when saving, it just gets in the way. The code is often set up -for streaming, and constructing the DOM is just overhead. - -The Printer supports the streaming case. The following code -prints out a trivially simple XML file without ever creating -an XML document. - - XMLPrinter printer( fp ); - printer.OpenElement( "foo" ); - printer.PushAttribute( "foo", "bar" ); - printer.CloseElement(); - -Examples --------- - -#### Load and parse an XML file. - - /* ------ Example 1: Load and parse an XML file. ---- */ - { - XMLDocument doc; - doc.LoadFile( "dream.xml" ); - } - -#### Lookup information. - - /* ------ Example 2: Lookup information. ---- */ - { - XMLDocument doc; - doc.LoadFile( "dream.xml" ); - - // Structure of the XML file: - // - Element "PLAY" the root Element, which is the - // FirstChildElement of the Document - // - - Element "TITLE" child of the root PLAY Element - // - - - Text child of the TITLE Element - - // Navigate to the title, using the convenience function, - // with a dangerous lack of error checking. - const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText(); - printf( "Name of play (1): %s\n", title ); - - // Text is just another Node to TinyXML-2. The more - // general way to get to the XMLText: - XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText(); - title = textNode->Value(); - printf( "Name of play (2): %s\n", title ); - } - -Using and Installing --------------------- - -There are 2 files in TinyXML-2: -* tinyxml2.cpp -* tinyxml2.h - -And additionally a test file: -* xmltest.cpp - -Simply compile and run. There is a visual studio 2010 project included, a simple Makefile, -an XCode project, a Code::Blocks project, and a cmake CMakeLists.txt included to help you. -The top of tinyxml.h even has a simple g++ command line if you are are *nix and don't want -to use a build system. - -Versioning ----------- - -TinyXML-2 uses semantic versioning. http://semver.org/ Releases are now tagged in github. - -Note that the major version will (probably) change fairly rapidly. API changes are fairly -common. - -Documentation -------------- - -The documentation is build with Doxygen, using the 'dox' -configuration file. - -License -------- - -TinyXML-2 is released under the zlib license: - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source -distribution. - -Contributors ------------- - -Thanks very much to everyone who sends suggestions, bugs, ideas, and -encouragement. It all helps, and makes this project fun. - -The original TinyXML-1 has many contributors, who all deserve thanks -in shaping what is a very successful library. Extra thanks to Yves -Berquin and Andrew Ellerton who were key contributors. - -TinyXML-2 grew from that effort. Lee Thomason is the original author -of TinyXML-2 (and TinyXML-1) but TinyXML-2 has been and is being improved -by many contributors. - -Thanks to John Mackay at http://john.mackay.rosalilastudio.com for the TinyXML-2 logo! - - diff --git a/lib/cpPlugins/tinyxml2/tinyxml2.cpp b/lib/cpPlugins/tinyxml2/tinyxml2.cpp deleted file mode 100644 index df49d0d..0000000 --- a/lib/cpPlugins/tinyxml2/tinyxml2.cpp +++ /dev/null @@ -1,2467 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#include "tinyxml2.h" - -#include // yes, this one new style header, is in the Android SDK. -#if defined(ANDROID_NDK) || defined(__QNXNTO__) -# include -# include -#else -# include -# include -#endif - -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - // Microsoft Visual Studio, version 2005 and higher. Not WinCE. - /*int _snprintf_s( - char *buffer, - size_t sizeOfBuffer, - size_t count, - const char *format [, - argument] ... - );*/ - static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) - { - va_list va; - va_start( va, format ); - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - va_end( va ); - return result; - } - - static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) - { - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - return result; - } - - #define TIXML_VSCPRINTF _vscprintf - #define TIXML_SSCANF sscanf_s -#elif defined _MSC_VER - // Microsoft Visual Studio 2003 and earlier or WinCE - #define TIXML_SNPRINTF _snprintf - #define TIXML_VSNPRINTF _vsnprintf - #define TIXML_SSCANF sscanf - #if (_MSC_VER < 1400 ) && (!defined WINCE) - // Microsoft Visual Studio 2003 and not WinCE. - #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. - #else - // Microsoft Visual Studio 2003 and earlier or WinCE. - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = 512; - for (;;) { - len = len*2; - char* str = new char[len](); - const int required = _vsnprintf(str, len, format, va); - delete[] str; - if ( required != -1 ) { - TIXMLASSERT( required >= 0 ); - len = required; - break; - } - } - TIXMLASSERT( len >= 0 ); - return len; - } - #endif -#else - // GCC version 3 and higher - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_VSNPRINTF vsnprintf - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = vsnprintf( 0, 0, format, va ); - TIXMLASSERT( len >= 0 ); - return len; - } - #define TIXML_SSCANF sscanf -#endif - - -static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF -static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out -static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; - -// Bunch of unicode info at: -// http://www.unicode.org/faq/utf_bom.html -// ef bb bf (Microsoft "lead bytes") - designates UTF-8 - -static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; -static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; -static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - -namespace tinyxml2 -{ - -struct Entity { - const char* pattern; - int length; - char value; -}; - -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = { - { "quot", 4, DOUBLE_QUOTE }, - { "amp", 3, '&' }, - { "apos", 4, SINGLE_QUOTE }, - { "lt", 2, '<' }, - { "gt", 2, '>' } -}; - - -StrPair::~StrPair() -{ - Reset(); -} - - -void StrPair::TransferTo( StrPair* other ) -{ - if ( this == other ) { - return; - } - // This in effect implements the assignment operator by "moving" - // ownership (as in auto_ptr). - - TIXMLASSERT( other->_flags == 0 ); - TIXMLASSERT( other->_start == 0 ); - TIXMLASSERT( other->_end == 0 ); - - other->Reset(); - - other->_flags = _flags; - other->_start = _start; - other->_end = _end; - - _flags = 0; - _start = 0; - _end = 0; -} - -void StrPair::Reset() -{ - if ( _flags & NEEDS_DELETE ) { - delete [] _start; - } - _flags = 0; - _start = 0; - _end = 0; -} - - -void StrPair::SetStr( const char* str, int flags ) -{ - TIXMLASSERT( str ); - Reset(); - size_t len = strlen( str ); - TIXMLASSERT( _start == 0 ); - _start = new char[ len+1 ]; - memcpy( _start, str, len+1 ); - _end = _start + len; - _flags = flags | NEEDS_DELETE; -} - - -char* StrPair::ParseText( char* p, const char* endTag, int strFlags ) -{ - TIXMLASSERT( endTag && *endTag ); - - char* start = p; - char endChar = *endTag; - size_t length = strlen( endTag ); - - // Inner loop of text parsing. - while ( *p ) { - if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { - Set( start, p, strFlags ); - return p + length; - } - ++p; - } - return 0; -} - - -char* StrPair::ParseName( char* p ) -{ - if ( !p || !(*p) ) { - return 0; - } - if ( !XMLUtil::IsNameStartChar( *p ) ) { - return 0; - } - - char* const start = p; - ++p; - while ( *p && XMLUtil::IsNameChar( *p ) ) { - ++p; - } - - Set( start, p, 0 ); - return p; -} - - -void StrPair::CollapseWhitespace() -{ - // Adjusting _start would cause undefined behavior on delete[] - TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace( _start ); - - if ( *_start ) { - char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( *p ) { - if ( XMLUtil::IsWhiteSpace( *p )) { - p = XMLUtil::SkipWhiteSpace( p ); - if ( *p == 0 ) { - break; // don't write to q; this trims the trailing space. - } - *q = ' '; - ++q; - } - *q = *p; - ++q; - ++p; - } - *q = 0; - } -} - - -const char* StrPair::GetStr() -{ - TIXMLASSERT( _start ); - TIXMLASSERT( _end ); - if ( _flags & NEEDS_FLUSH ) { - *_end = 0; - _flags ^= NEEDS_FLUSH; - - if ( _flags ) { - char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( p < _end ) { - if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if ( *(p+1) == LF ) { - p += 2; - } - else { - ++p; - } - *q++ = LF; - } - else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { - if ( *(p+1) == CR ) { - p += 2; - } - else { - ++p; - } - *q++ = LF; - } - else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if ( *(p+1) == '#' ) { - const int buflen = 10; - char buf[buflen] = { 0 }; - int len = 0; - char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); - if ( adjusted == 0 ) { - *q = *p; - ++p; - ++q; - } - else { - TIXMLASSERT( 0 <= len && len <= buflen ); - TIXMLASSERT( q + len <= adjusted ); - p = adjusted; - memcpy( q, buf, len ); - q += len; - } - } - else { - bool entityFound = false; - for( int i = 0; i < NUM_ENTITIES; ++i ) { - const Entity& entity = entities[i]; - if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 - && *( p + entity.length + 1 ) == ';' ) { - // Found an entity - convert. - *q = entity.value; - ++q; - p += entity.length + 2; - entityFound = true; - break; - } - } - if ( !entityFound ) { - // fixme: treat as error? - ++p; - ++q; - } - } - } - else { - *q = *p; - ++p; - ++q; - } - } - *q = 0; - } - // The loop below has plenty going on, and this - // is a less useful mode. Break it out. - if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { - CollapseWhitespace(); - } - _flags = (_flags & NEEDS_DELETE); - } - TIXMLASSERT( _start ); - return _start; -} - - - - -// --------- XMLUtil ----------- // - -const char* XMLUtil::ReadBOM( const char* p, bool* bom ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( bom ); - *bom = false; - const unsigned char* pu = reinterpret_cast(p); - // Check for BOM: - if ( *(pu+0) == TIXML_UTF_LEAD_0 - && *(pu+1) == TIXML_UTF_LEAD_1 - && *(pu+2) == TIXML_UTF_LEAD_2 ) { - *bom = true; - p += 3; - } - TIXMLASSERT( p ); - return p; -} - - -void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) { - *length = 1; - } - else if ( input < 0x800 ) { - *length = 2; - } - else if ( input < 0x10000 ) { - *length = 3; - } - else if ( input < 0x200000 ) { - *length = 4; - } - else { - *length = 0; // This code won't convert this correctly anyway. - return; - } - - output += *length; - - // Scary scary fall throughs. - switch (*length) { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - break; - default: - TIXMLASSERT( false ); - } -} - - -const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) -{ - // Presume an entity, and pull it out. - *length = 0; - - if ( *(p+1) == '#' && *(p+2) ) { - unsigned long ucs = 0; - TIXMLASSERT( sizeof( ucs ) >= 4 ); - ptrdiff_t delta = 0; - unsigned mult = 1; - static const char SEMICOLON = ';'; - - if ( *(p+2) == 'x' ) { - // Hexadecimal. - const char* q = p+3; - if ( !(*q) ) { - return 0; - } - - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != 'x' ) { - unsigned int digit = 0; - - if ( *q >= '0' && *q <= '9' ) { - digit = *q - '0'; - } - else if ( *q >= 'a' && *q <= 'f' ) { - digit = *q - 'a' + 10; - } - else if ( *q >= 'A' && *q <= 'F' ) { - digit = *q - 'A' + 10; - } - else { - return 0; - } - TIXMLASSERT( digit >= 0 && digit < 16); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - TIXMLASSERT( mult <= UINT_MAX / 16 ); - mult *= 16; - --q; - } - } - else { - // Decimal. - const char* q = p+2; - if ( !(*q) ) { - return 0; - } - - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != '#' ) { - if ( *q >= '0' && *q <= '9' ) { - const unsigned int digit = *q - '0'; - TIXMLASSERT( digit >= 0 && digit < 10); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - } - else { - return 0; - } - TIXMLASSERT( mult <= UINT_MAX / 10 ); - mult *= 10; - --q; - } - } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - return p + delta + 1; - } - return p+1; -} - - -void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); -} - - -void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); -} - - -void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 ); -} - -/* - ToStr() of a number is a very tricky topic. - https://github.com/leethomason/tinyxml2/issues/106 -*/ -void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); -} - - -void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); -} - - -bool XMLUtil::ToInt( const char* str, int* value ) -{ - if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) -{ - if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToBool( const char* str, bool* value ) -{ - int ival = 0; - if ( ToInt( str, &ival )) { - *value = (ival==0) ? false : true; - return true; - } - if ( StringEqual( str, "true" ) ) { - *value = true; - return true; - } - else if ( StringEqual( str, "false" ) ) { - *value = false; - return true; - } - return false; -} - - -bool XMLUtil::ToFloat( const char* str, float* value ) -{ - if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToDouble( const char* str, double* value ) -{ - if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { - return true; - } - return false; -} - - -char* XMLDocument::Identify( char* p, XMLNode** node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( p ); - char* const start = p; - p = XMLUtil::SkipWhiteSpace( p ); - if( !*p ) { - *node = 0; - TIXMLASSERT( p ); - return p; - } - - // These strings define the matching patterns: - static const char* xmlHeader = { "_memPool = &_commentPool; - p += xmlHeaderLen; - } - else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { - TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() ); - returnNode = new (_commentPool.Alloc()) XMLComment( this ); - returnNode->_memPool = &_commentPool; - p += commentHeaderLen; - } - else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { - TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); - XMLText* text = new (_textPool.Alloc()) XMLText( this ); - returnNode = text; - returnNode->_memPool = &_textPool; - p += cdataHeaderLen; - text->SetCData( true ); - } - else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { - TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() ); - returnNode = new (_commentPool.Alloc()) XMLUnknown( this ); - returnNode->_memPool = &_commentPool; - p += dtdHeaderLen; - } - else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { - TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() ); - returnNode = new (_elementPool.Alloc()) XMLElement( this ); - returnNode->_memPool = &_elementPool; - p += elementHeaderLen; - } - else { - TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); - returnNode = new (_textPool.Alloc()) XMLText( this ); - returnNode->_memPool = &_textPool; - p = start; // Back it up, all the text counts. - } - - TIXMLASSERT( returnNode ); - TIXMLASSERT( p ); - *node = returnNode; - return p; -} - - -bool XMLDocument::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } - } - return visitor->VisitExit( *this ); -} - - -// --------- XMLNode ----------- // - -XMLNode::XMLNode( XMLDocument* doc ) : - _document( doc ), - _parent( 0 ), - _firstChild( 0 ), _lastChild( 0 ), - _prev( 0 ), _next( 0 ), - _memPool( 0 ) -{ -} - - -XMLNode::~XMLNode() -{ - DeleteChildren(); - if ( _parent ) { - _parent->Unlink( this ); - } -} - -const char* XMLNode::Value() const -{ - // Catch an edge case: XMLDocuments don't have a a Value. Carefully return nullptr. - if ( this->ToDocument() ) - return 0; - return _value.GetStr(); -} - -void XMLNode::SetValue( const char* str, bool staticMem ) -{ - if ( staticMem ) { - _value.SetInternedStr( str ); - } - else { - _value.SetStr( str ); - } -} - - -void XMLNode::DeleteChildren() -{ - while( _firstChild ) { - TIXMLASSERT( _lastChild ); - TIXMLASSERT( _firstChild->_document == _document ); - XMLNode* node = _firstChild; - Unlink( node ); - - DeleteNode( node ); - } - _firstChild = _lastChild = 0; -} - - -void XMLNode::Unlink( XMLNode* child ) -{ - TIXMLASSERT( child ); - TIXMLASSERT( child->_document == _document ); - TIXMLASSERT( child->_parent == this ); - if ( child == _firstChild ) { - _firstChild = _firstChild->_next; - } - if ( child == _lastChild ) { - _lastChild = _lastChild->_prev; - } - - if ( child->_prev ) { - child->_prev->_next = child->_next; - } - if ( child->_next ) { - child->_next->_prev = child->_prev; - } - child->_parent = 0; -} - - -void XMLNode::DeleteChild( XMLNode* node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( node->_document == _document ); - TIXMLASSERT( node->_parent == this ); - Unlink( node ); - DeleteNode( node ); -} - - -XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); - - if ( _lastChild ) { - TIXMLASSERT( _firstChild ); - TIXMLASSERT( _lastChild->_next == 0 ); - _lastChild->_next = addThis; - addThis->_prev = _lastChild; - _lastChild = addThis; - - addThis->_next = 0; - } - else { - TIXMLASSERT( _firstChild == 0 ); - _firstChild = _lastChild = addThis; - - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} - - -XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); - - if ( _firstChild ) { - TIXMLASSERT( _lastChild ); - TIXMLASSERT( _firstChild->_prev == 0 ); - - _firstChild->_prev = addThis; - addThis->_next = _firstChild; - _firstChild = addThis; - - addThis->_prev = 0; - } - else { - TIXMLASSERT( _lastChild == 0 ); - _firstChild = _lastChild = addThis; - - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} - - -XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - - TIXMLASSERT( afterThis ); - - if ( afterThis->_parent != this ) { - TIXMLASSERT( false ); - return 0; - } - - if ( afterThis->_next == 0 ) { - // The last node or the only node. - return InsertEndChild( addThis ); - } - InsertChildPreamble( addThis ); - addThis->_prev = afterThis; - addThis->_next = afterThis->_next; - afterThis->_next->_prev = addThis; - afterThis->_next = addThis; - addThis->_parent = this; - return addThis; -} - - - - -const XMLElement* XMLNode::FirstChildElement( const char* name ) const -{ - for( const XMLNode* node = _firstChild; node; node = node->_next ) { - const XMLElement* element = node->ToElement(); - if ( element ) { - if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) { - return element; - } - } - } - return 0; -} - - -const XMLElement* XMLNode::LastChildElement( const char* name ) const -{ - for( const XMLNode* node = _lastChild; node; node = node->_prev ) { - const XMLElement* element = node->ToElement(); - if ( element ) { - if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) { - return element; - } - } - } - return 0; -} - - -const XMLElement* XMLNode::NextSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _next; node; node = node->_next ) { - const XMLElement* element = node->ToElement(); - if ( element - && (!name || XMLUtil::StringEqual( name, element->Name() ))) { - return element; - } - } - return 0; -} - - -const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _prev; node; node = node->_prev ) { - const XMLElement* element = node->ToElement(); - if ( element - && (!name || XMLUtil::StringEqual( name, element->Name() ))) { - return element; - } - } - return 0; -} - - -char* XMLNode::ParseDeep( char* p, StrPair* parentEnd ) -{ - // This is a recursive method, but thinking about it "at the current level" - // it is a pretty simple flat list: - // - // - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - - while( p && *p ) { - XMLNode* node = 0; - - p = _document->Identify( p, &node ); - if ( node == 0 ) { - break; - } - - StrPair endTag; - p = node->ParseDeep( p, &endTag ); - if ( !p ) { - DeleteNode( node ); - if ( !_document->Error() ) { - _document->SetError( XML_ERROR_PARSING, 0, 0 ); - } - break; - } - - XMLDeclaration* decl = node->ToDeclaration(); - if ( decl ) { - // A declaration can only be the first child of a document. - // Set error, if document already has children. - if ( !_document->NoChildren() ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, decl->Value(), 0); - DeleteNode( decl ); - break; - } - } - - XMLElement* ele = node->ToElement(); - if ( ele ) { - // We read the end tag. Return it to the parent. - if ( ele->ClosingType() == XMLElement::CLOSING ) { - if ( parentEnd ) { - ele->_value.TransferTo( parentEnd ); - } - node->_memPool->SetTracked(); // created and then immediately deleted. - DeleteNode( node ); - return p; - } - - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - bool mismatch = false; - if ( endTag.Empty() ) { - if ( ele->ClosingType() == XMLElement::OPEN ) { - mismatch = true; - } - } - else { - if ( ele->ClosingType() != XMLElement::OPEN ) { - mismatch = true; - } - else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { - mismatch = true; - } - } - if ( mismatch ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, ele->Name(), 0 ); - DeleteNode( node ); - break; - } - } - InsertEndChild( node ); - } - return 0; -} - -void XMLNode::DeleteNode( XMLNode* node ) -{ - if ( node == 0 ) { - return; - } - MemPool* pool = node->_memPool; - node->~XMLNode(); - pool->Free( node ); -} - -void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const -{ - TIXMLASSERT( insertThis ); - TIXMLASSERT( insertThis->_document == _document ); - - if ( insertThis->_parent ) - insertThis->_parent->Unlink( insertThis ); - else - insertThis->_memPool->SetTracked(); -} - -// --------- XMLText ---------- // -char* XMLText::ParseDeep( char* p, StrPair* ) -{ - const char* start = p; - if ( this->CData() ) { - p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 ); - } - return p; - } - else { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { - flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; - } - - p = _value.ParseText( p, "<", flags ); - if ( p && *p ) { - return p-1; - } - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 ); - } - } - return 0; -} - - -XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? - text->SetCData( this->CData() ); - return text; -} - - -bool XMLText::ShallowEqual( const XMLNode* compare ) const -{ - const XMLText* text = compare->ToText(); - return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); -} - - -bool XMLText::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - - -// --------- XMLComment ---------- // - -XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLComment::~XMLComment() -{ -} - - -char* XMLComment::ParseDeep( char* p, StrPair* ) -{ - // Comment parses as text. - const char* start = p; - p = _value.ParseText( p, "-->", StrPair::COMMENT ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 ); - } - return p; -} - - -XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? - return comment; -} - - -bool XMLComment::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLComment* comment = compare->ToComment(); - return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); -} - - -bool XMLComment::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - - -// --------- XMLDeclaration ---------- // - -XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLDeclaration::~XMLDeclaration() -{ - //printf( "~XMLDeclaration\n" ); -} - - -char* XMLDeclaration::ParseDeep( char* p, StrPair* ) -{ - // Declaration parses as text. - const char* start = p; - p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 ); - } - return p; -} - - -XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? - return dec; -} - - -bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLDeclaration* declaration = compare->ToDeclaration(); - return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); -} - - - -bool XMLDeclaration::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - -// --------- XMLUnknown ---------- // - -XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLUnknown::~XMLUnknown() -{ -} - - -char* XMLUnknown::ParseDeep( char* p, StrPair* ) -{ - // Unknown parses as text. - const char* start = p; - - p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 ); - } - return p; -} - - -XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? - return text; -} - - -bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLUnknown* unknown = compare->ToUnknown(); - return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); -} - - -bool XMLUnknown::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - -// --------- XMLAttribute ---------- // - -const char* XMLAttribute::Name() const -{ - return _name.GetStr(); -} - -const char* XMLAttribute::Value() const -{ - return _value.GetStr(); -} - -char* XMLAttribute::ParseDeep( char* p, bool processEntities ) -{ - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName( p ); - if ( !p || !*p ) { - return 0; - } - - // Skip white space before = - p = XMLUtil::SkipWhiteSpace( p ); - if ( *p != '=' ) { - return 0; - } - - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace( p ); - if ( *p != '\"' && *p != '\'' ) { - return 0; - } - - char endTag[2] = { *p, 0 }; - ++p; // move past opening quote - - p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES ); - return p; -} - - -void XMLAttribute::SetName( const char* n ) -{ - _name.SetStr( n ); -} - - -XMLError XMLAttribute::QueryIntValue( int* value ) const -{ - if ( XMLUtil::ToInt( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const -{ - if ( XMLUtil::ToUnsigned( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryBoolValue( bool* value ) const -{ - if ( XMLUtil::ToBool( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryFloatValue( float* value ) const -{ - if ( XMLUtil::ToFloat( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryDoubleValue( double* value ) const -{ - if ( XMLUtil::ToDouble( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -void XMLAttribute::SetAttribute( const char* v ) -{ - _value.SetStr( v ); -} - - -void XMLAttribute::SetAttribute( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -// --------- XMLElement ---------- // -XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), - _closingType( 0 ), - _rootAttribute( 0 ) -{ -} - - -XMLElement::~XMLElement() -{ - while( _rootAttribute ) { - XMLAttribute* next = _rootAttribute->_next; - DeleteAttribute( _rootAttribute ); - _rootAttribute = next; - } -} - - -const XMLAttribute* XMLElement::FindAttribute( const char* name ) const -{ - for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; - } - } - return 0; -} - - -const char* XMLElement::Attribute( const char* name, const char* value ) const -{ - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return 0; - } - if ( !value || XMLUtil::StringEqual( a->Value(), value )) { - return a->Value(); - } - return 0; -} - - -const char* XMLElement::GetText() const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - return FirstChild()->Value(); - } - return 0; -} - - -void XMLElement::SetText( const char* inText ) -{ - if ( FirstChild() && FirstChild()->ToText() ) - FirstChild()->SetValue( inText ); - else { - XMLText* theText = GetDocument()->NewText( inText ); - InsertFirstChild( theText ); - } -} - - -void XMLElement::SetText( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -XMLError XMLElement::QueryIntText( int* ival ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToInt( t, ival ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToUnsigned( t, uval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryBoolText( bool* bval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToBool( t, bval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryDoubleText( double* dval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToDouble( t, dval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryFloatText( float* fval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToFloat( t, fval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - - -XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) -{ - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for( attrib = _rootAttribute; - attrib; - last = attrib, attrib = attrib->_next ) { - if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { - break; - } - } - if ( !attrib ) { - TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); - attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - attrib->_memPool = &_document->_attributePool; - if ( last ) { - last->_next = attrib; - } - else { - _rootAttribute = attrib; - } - attrib->SetName( name ); - attrib->_memPool->SetTracked(); // always created and linked. - } - return attrib; -} - - -void XMLElement::DeleteAttribute( const char* name ) -{ - XMLAttribute* prev = 0; - for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { - if ( XMLUtil::StringEqual( name, a->Name() ) ) { - if ( prev ) { - prev->_next = a->_next; - } - else { - _rootAttribute = a->_next; - } - DeleteAttribute( a ); - break; - } - prev = a; - } -} - - -char* XMLElement::ParseAttributes( char* p ) -{ - const char* start = p; - XMLAttribute* prevAttribute = 0; - - // Read the attributes. - while( p ) { - p = XMLUtil::SkipWhiteSpace( p ); - if ( !(*p) ) { - _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() ); - return 0; - } - - // attribute. - if (XMLUtil::IsNameStartChar( *p ) ) { - TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); - XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - - p = attrib->ParseDeep( p, _document->ProcessEntities() ); - if ( !p || Attribute( attrib->Name() ) ) { - DeleteAttribute( attrib ); - _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p ); - return 0; - } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if ( prevAttribute ) { - prevAttribute->_next = attrib; - } - else { - _rootAttribute = attrib; - } - prevAttribute = attrib; - } - // end of the tag - else if ( *p == '>' ) { - ++p; - break; - } - // end of the tag - else if ( *p == '/' && *(p+1) == '>' ) { - _closingType = CLOSED; - return p+2; // done; sealed element. - } - else { - _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p ); - return 0; - } - } - return p; -} - -void XMLElement::DeleteAttribute( XMLAttribute* attribute ) -{ - if ( attribute == 0 ) { - return; - } - MemPool* pool = attribute->_memPool; - attribute->~XMLAttribute(); - pool->Free( attribute ); -} - -// -// -// foobar -// -char* XMLElement::ParseDeep( char* p, StrPair* strPair ) -{ - // Read the element name. - p = XMLUtil::SkipWhiteSpace( p ); - - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if ( *p == '/' ) { - _closingType = CLOSING; - ++p; - } - - p = _value.ParseName( p ); - if ( _value.Empty() ) { - return 0; - } - - p = ParseAttributes( p ); - if ( !p || !*p || _closingType ) { - return p; - } - - p = XMLNode::ParseDeep( p, strPair ); - return p; -} - - - -XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? - for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { - element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? - } - return element; -} - - -bool XMLElement::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLElement* other = compare->ToElement(); - if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { - - const XMLAttribute* a=FirstAttribute(); - const XMLAttribute* b=other->FirstAttribute(); - - while ( a && b ) { - if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { - return false; - } - a = a->Next(); - b = b->Next(); - } - if ( a || b ) { - // different count - return false; - } - return true; - } - return false; -} - - -bool XMLElement::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this, _rootAttribute ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } - } - return visitor->VisitExit( *this ); -} - - -// --------- XMLDocument ----------- // - -// Warning: List must match 'enum XMLError' -const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { - "XML_SUCCESS", - "XML_NO_ATTRIBUTE", - "XML_WRONG_ATTRIBUTE_TYPE", - "XML_ERROR_FILE_NOT_FOUND", - "XML_ERROR_FILE_COULD_NOT_BE_OPENED", - "XML_ERROR_FILE_READ_ERROR", - "XML_ERROR_ELEMENT_MISMATCH", - "XML_ERROR_PARSING_ELEMENT", - "XML_ERROR_PARSING_ATTRIBUTE", - "XML_ERROR_IDENTIFYING_TAG", - "XML_ERROR_PARSING_TEXT", - "XML_ERROR_PARSING_CDATA", - "XML_ERROR_PARSING_COMMENT", - "XML_ERROR_PARSING_DECLARATION", - "XML_ERROR_PARSING_UNKNOWN", - "XML_ERROR_EMPTY_DOCUMENT", - "XML_ERROR_MISMATCHED_ELEMENT", - "XML_ERROR_PARSING", - "XML_CAN_NOT_CONVERT_TEXT", - "XML_NO_TEXT_NODE" -}; - - -XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) : - XMLNode( 0 ), - _writeBOM( false ), - _processEntities( processEntities ), - _errorID( XML_NO_ERROR ), - _whitespace( whitespace ), - _errorStr1( 0 ), - _errorStr2( 0 ), - _charBuffer( 0 ) -{ - // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) - _document = this; -} - - -XMLDocument::~XMLDocument() -{ - Clear(); -} - - -void XMLDocument::Clear() -{ - DeleteChildren(); - -#ifdef DEBUG - const bool hadError = Error(); -#endif - _errorID = XML_NO_ERROR; - _errorStr1 = 0; - _errorStr2 = 0; - - delete [] _charBuffer; - _charBuffer = 0; - -#if 0 - _textPool.Trace( "text" ); - _elementPool.Trace( "element" ); - _commentPool.Trace( "comment" ); - _attributePool.Trace( "attribute" ); -#endif - -#ifdef DEBUG - if ( !hadError ) { - TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); - TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); - TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); - TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); - } -#endif -} - - -XMLElement* XMLDocument::NewElement( const char* name ) -{ - TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() ); - XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this ); - ele->_memPool = &_elementPool; - ele->SetName( name ); - return ele; -} - - -XMLComment* XMLDocument::NewComment( const char* str ) -{ - TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() ); - XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this ); - comment->_memPool = &_commentPool; - comment->SetValue( str ); - return comment; -} - - -XMLText* XMLDocument::NewText( const char* str ) -{ - TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); - XMLText* text = new (_textPool.Alloc()) XMLText( this ); - text->_memPool = &_textPool; - text->SetValue( str ); - return text; -} - - -XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) -{ - TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() ); - XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this ); - dec->_memPool = &_commentPool; - dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); - return dec; -} - - -XMLUnknown* XMLDocument::NewUnknown( const char* str ) -{ - TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() ); - XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this ); - unk->_memPool = &_commentPool; - unk->SetValue( str ); - return unk; -} - -static FILE* callfopen( const char* filepath, const char* mode ) -{ - TIXMLASSERT( filepath ); - TIXMLASSERT( mode ); -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filepath, mode ); - if ( err ) { - return 0; - } -#else - FILE* fp = fopen( filepath, mode ); -#endif - return fp; -} - -void XMLDocument::DeleteNode( XMLNode* node ) { - TIXMLASSERT( node ); - TIXMLASSERT(node->_document == this ); - if (node->_parent) { - node->_parent->DeleteChild( node ); - } - else { - // Isn't in the tree. - // Use the parent delete. - // Also, we need to mark it tracked: we 'know' - // it was never used. - node->_memPool->SetTracked(); - // Call the static XMLNode version: - XMLNode::DeleteNode(node); - } -} - - -XMLError XMLDocument::LoadFile( const char* filename ) -{ - Clear(); - FILE* fp = callfopen( filename, "rb" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 ); - return _errorID; - } - LoadFile( fp ); - fclose( fp ); - return _errorID; -} - -// This is likely overengineered template art to have a check that unsigned long value incremented -// by one still fits into size_t. If size_t type is larger than unsigned long type -// (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit -// -Wtype-limits warning. This piece makes the compiler select code with a check when a check -// is useful and code with no check when a check is redundant depending on how size_t and unsigned long -// types sizes relate to each other. -template -= sizeof(size_t))> -struct LongFitsIntoSizeTMinusOne { - static bool Fits( unsigned long value ) - { - return value < (size_t)-1; - } -}; - -template <> -bool LongFitsIntoSizeTMinusOne::Fits( unsigned long /*value*/ ) -{ - return true; -} - -XMLError XMLDocument::LoadFile( FILE* fp ) -{ - Clear(); - - fseek( fp, 0, SEEK_SET ); - if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - fseek( fp, 0, SEEK_END ); - const long filelength = ftell( fp ); - fseek( fp, 0, SEEK_SET ); - if ( filelength == -1L ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - TIXMLASSERT( filelength >= 0 ); - - if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) { - // Cannot handle files which won't fit in buffer together with null terminator - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - if ( filelength == 0 ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - - const size_t size = filelength; - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[size+1]; - size_t read = fread( _charBuffer, 1, size, fp ); - if ( read != size ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - _charBuffer[size] = 0; - - Parse(); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( const char* filename, bool compact ) -{ - FILE* fp = callfopen( filename, "w" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 ); - return _errorID; - } - SaveFile(fp, compact); - fclose( fp ); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) -{ - // Clear any error from the last save, otherwise it will get reported - // for *this* call. - SetError( XML_NO_ERROR, 0, 0 ); - XMLPrinter stream( fp, compact ); - Print( &stream ); - return _errorID; -} - - -XMLError XMLDocument::Parse( const char* p, size_t len ) -{ - Clear(); - - if ( len == 0 || !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - if ( len == (size_t)(-1) ) { - len = strlen( p ); - } - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[ len+1 ]; - memcpy( _charBuffer, p, len ); - _charBuffer[len] = 0; - - Parse(); - if ( Error() ) { - // clean up now essentially dangling memory. - // and the parse fail can put objects in the - // pools that are dead and inaccessible. - DeleteChildren(); - _elementPool.Clear(); - _attributePool.Clear(); - _textPool.Clear(); - _commentPool.Clear(); - } - return _errorID; -} - - -void XMLDocument::Print( XMLPrinter* streamer ) const -{ - if ( streamer ) { - Accept( streamer ); - } - else { - XMLPrinter stdoutStreamer( stdout ); - Accept( &stdoutStreamer ); - } -} - - -void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 ) -{ - TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); - _errorID = error; - _errorStr1 = str1; - _errorStr2 = str2; -} - -const char* XMLDocument::ErrorName() const -{ - TIXMLASSERT( _errorID >= 0 && _errorID < XML_ERROR_COUNT ); - const char* errorName = _errorNames[_errorID]; - TIXMLASSERT( errorName && errorName[0] ); - return errorName; -} - -void XMLDocument::PrintError() const -{ - if ( Error() ) { - static const int LEN = 20; - char buf1[LEN] = { 0 }; - char buf2[LEN] = { 0 }; - - if ( _errorStr1 ) { - TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 ); - } - if ( _errorStr2 ) { - TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 ); - } - - // Should check INT_MIN <= _errorID && _errorId <= INT_MAX, but that - // causes a clang "always true" -Wtautological-constant-out-of-range-compare warning - TIXMLASSERT( 0 <= _errorID && XML_ERROR_COUNT - 1 <= INT_MAX ); - printf( "XMLDocument error id=%d '%s' str1=%s str2=%s\n", - static_cast( _errorID ), ErrorName(), buf1, buf2 ); - } -} - -void XMLDocument::Parse() -{ - TIXMLASSERT( NoChildren() ); // Clear() must have been called previously - TIXMLASSERT( _charBuffer ); - char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace( p ); - p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); - if ( !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return; - } - ParseDeep(p, 0 ); -} - -XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : - _elementJustOpened( false ), - _firstElement( true ), - _fp( file ), - _depth( depth ), - _textDepth( -1 ), - _processEntities( true ), - _compactMode( compact ) -{ - for( int i=0; i'] = true; // not required, but consistency is nice - _buffer.Push( 0 ); -} - - -void XMLPrinter::Print( const char* format, ... ) -{ - va_list va; - va_start( va, format ); - - if ( _fp ) { - vfprintf( _fp, format, va ); - } - else { - const int len = TIXML_VSCPRINTF( format, va ); - // Close out and re-start the va-args - va_end( va ); - TIXMLASSERT( len >= 0 ); - va_start( va, format ); - TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); - char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. - TIXML_VSNPRINTF( p, len+1, format, va ); - } - va_end( va ); -} - - -void XMLPrinter::PrintSpace( int depth ) -{ - for( int i=0; i 0 && *q < ENTITY_RANGE ) { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if ( flag[(unsigned char)(*q)] ) { - while ( p < q ) { - const size_t delta = q - p; - // %.*s accepts type int as "precision" - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; - Print( "%.*s", toPrint, p ); - p += toPrint; - } - bool entityPatternPrinted = false; - for( int i=0; i" ); - } - else { - if ( _textDepth < 0 && !compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - Print( "", name ); - } - - if ( _textDepth == _depth ) { - _textDepth = -1; - } - if ( _depth == 0 && !compactMode) { - Print( "\n" ); - } - _elementJustOpened = false; -} - - -void XMLPrinter::SealElementIfJustOpened() -{ - if ( !_elementJustOpened ) { - return; - } - _elementJustOpened = false; - Print( ">" ); -} - - -void XMLPrinter::PushText( const char* text, bool cdata ) -{ - _textDepth = _depth-1; - - SealElementIfJustOpened(); - if ( cdata ) { - Print( "", text ); - } - else { - PrintString( text, true ); - } -} - -void XMLPrinter::PushText( int value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( unsigned value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( bool value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( float value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( double value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushComment( const char* comment ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", comment ); -} - - -void XMLPrinter::PushDeclaration( const char* value ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", value ); -} - - -void XMLPrinter::PushUnknown( const char* value ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", value ); -} - - -bool XMLPrinter::VisitEnter( const XMLDocument& doc ) -{ - _processEntities = doc.ProcessEntities(); - if ( doc.HasBOM() ) { - PushHeader( true, false ); - } - return true; -} - - -bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) -{ - const XMLElement* parentElem = 0; - if ( element.Parent() ) { - parentElem = element.Parent()->ToElement(); - } - const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; - OpenElement( element.Name(), compactMode ); - while ( attribute ) { - PushAttribute( attribute->Name(), attribute->Value() ); - attribute = attribute->Next(); - } - return true; -} - - -bool XMLPrinter::VisitExit( const XMLElement& element ) -{ - CloseElement( CompactMode(element) ); - return true; -} - - -bool XMLPrinter::Visit( const XMLText& text ) -{ - PushText( text.Value(), text.CData() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLComment& comment ) -{ - PushComment( comment.Value() ); - return true; -} - -bool XMLPrinter::Visit( const XMLDeclaration& declaration ) -{ - PushDeclaration( declaration.Value() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLUnknown& unknown ) -{ - PushUnknown( unknown.Value() ); - return true; -} - -} // namespace tinyxml2 - diff --git a/lib/cpPlugins/tinyxml2/tinyxml2.h b/lib/cpPlugins/tinyxml2/tinyxml2.h deleted file mode 100644 index 3598786..0000000 --- a/lib/cpPlugins/tinyxml2/tinyxml2.h +++ /dev/null @@ -1,2106 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#ifndef TINYXML2_INCLUDED -#define TINYXML2_INCLUDED - -#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -# include -# include -# include -# include -# include -#else -# include -# include -# include -# include -# include -#endif - -/* - TODO: intern strings instead of allocation. -*/ -/* - gcc: - g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe - - Formatting, Artistic Style: - AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h -*/ - -#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) -# ifndef DEBUG -# define DEBUG -# endif -#endif - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4251) -#endif - -#ifdef _WIN32 -# ifdef TINYXML2_EXPORT -# define TINYXML2_LIB __declspec(dllexport) -# elif defined(TINYXML2_IMPORT) -# define TINYXML2_LIB __declspec(dllimport) -# else -# define TINYXML2_LIB -# endif -#else -# define TINYXML2_LIB -#endif - - -#if defined(DEBUG) -# if defined(_MSC_VER) -# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like -# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } -# elif defined (ANDROID_NDK) -# include -# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } -# else -# include -# define TIXMLASSERT assert -# endif -#else -# define TIXMLASSERT( x ) {} -#endif - - -/* Versioning, past 1.0.14: - http://semver.org/ -*/ -static const int TIXML2_MAJOR_VERSION = 3; -static const int TIXML2_MINOR_VERSION = 0; -static const int TIXML2_PATCH_VERSION = 0; - -#include -#undef TINYXML2_LIB -#define TINYXML2_LIB cpPlugins_EXPORT - -namespace tinyxml2 -{ -class XMLDocument; -class XMLElement; -class XMLAttribute; -class XMLComment; -class XMLText; -class XMLDeclaration; -class XMLUnknown; -class XMLPrinter; - -/* - A class that wraps strings. Normally stores the start and end - pointers into the XML file itself, and will apply normalization - and entity translation if actually read. Can also store (and memory - manage) a traditional char[] -*/ -class StrPair -{ -public: - enum { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - NEEDS_WHITESPACE_COLLAPSING = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; - - StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} - ~StrPair(); - - void Set( char* start, char* end, int flags ) { - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } - - const char* GetStr(); - - bool Empty() const { - return _start == _end; - } - - void SetInternedStr( const char* str ) { - Reset(); - _start = const_cast(str); - } - - void SetStr( const char* str, int flags=0 ); - - char* ParseText( char* in, const char* endTag, int strFlags ); - char* ParseName( char* in ); - - void TransferTo( StrPair* other ); - -private: - void Reset(); - void CollapseWhitespace(); - - enum { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 - }; - - int _flags; - char* _start; - char* _end; - - StrPair( const StrPair& other ); // not supported - void operator=( StrPair& other ); // not supported, use TransferTo() -}; - - -/* - A dynamic array of Plain Old Data. Doesn't support constructors, etc. - Has a small initial memory pool, so that low or no usage will not - cause a call to new/delete -*/ -template -class DynArray -{ -public: - DynArray() { - _mem = _pool; - _allocated = INITIAL_SIZE; - _size = 0; - } - - ~DynArray() { - if ( _mem != _pool ) { - delete [] _mem; - } - } - - void Clear() { - _size = 0; - } - - void Push( T t ) { - TIXMLASSERT( _size < INT_MAX ); - EnsureCapacity( _size+1 ); - _mem[_size++] = t; - } - - T* PushArr( int count ) { - TIXMLASSERT( count >= 0 ); - TIXMLASSERT( _size <= INT_MAX - count ); - EnsureCapacity( _size+count ); - T* ret = &_mem[_size]; - _size += count; - return ret; - } - - T Pop() { - TIXMLASSERT( _size > 0 ); - return _mem[--_size]; - } - - void PopArr( int count ) { - TIXMLASSERT( _size >= count ); - _size -= count; - } - - bool Empty() const { - return _size == 0; - } - - T& operator[](int i) { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& operator[](int i) const { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& PeekTop() const { - TIXMLASSERT( _size > 0 ); - return _mem[ _size - 1]; - } - - int Size() const { - TIXMLASSERT( _size >= 0 ); - return _size; - } - - int Capacity() const { - TIXMLASSERT( _allocated >= INITIAL_SIZE ); - return _allocated; - } - - const T* Mem() const { - TIXMLASSERT( _mem ); - return _mem; - } - - T* Mem() { - TIXMLASSERT( _mem ); - return _mem; - } - -private: - DynArray( const DynArray& ); // not supported - void operator=( const DynArray& ); // not supported - - void EnsureCapacity( int cap ) { - TIXMLASSERT( cap > 0 ); - if ( cap > _allocated ) { - TIXMLASSERT( cap <= INT_MAX / 2 ); - int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs - if ( _mem != _pool ) { - delete [] _mem; - } - _mem = newMem; - _allocated = newAllocated; - } - } - - T* _mem; - T _pool[INITIAL_SIZE]; - int _allocated; // objects allocated - int _size; // number objects in use -}; - - -/* - Parent virtual class of a pool for fast allocation - and deallocation of objects. -*/ -class MemPool -{ -public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free( void* ) = 0; - virtual void SetTracked() = 0; - virtual void Clear() = 0; -}; - - -/* - Template child class to create pools of the correct type. -*/ -template< int SIZE > -class MemPoolT : public MemPool -{ -public: - MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} - ~MemPoolT() { - Clear(); - } - - void Clear() { - // Delete the blocks. - while( !_blockPtrs.Empty()) { - Block* b = _blockPtrs.Pop(); - delete b; - } - _root = 0; - _currentAllocs = 0; - _nAllocs = 0; - _maxAllocs = 0; - _nUntracked = 0; - } - - virtual int ItemSize() const { - return SIZE; - } - int CurrentAllocs() const { - return _currentAllocs; - } - - virtual void* Alloc() { - if ( !_root ) { - // Need a new block. - Block* block = new Block(); - _blockPtrs.Push( block ); - - for( int i=0; ichunk[i].next = &block->chunk[i+1]; - } - block->chunk[COUNT-1].next = 0; - _root = block->chunk; - } - void* result = _root; - _root = _root->next; - - ++_currentAllocs; - if ( _currentAllocs > _maxAllocs ) { - _maxAllocs = _currentAllocs; - } - _nAllocs++; - _nUntracked++; - return result; - } - - virtual void Free( void* mem ) { - if ( !mem ) { - return; - } - --_currentAllocs; - Chunk* chunk = static_cast( mem ); -#ifdef DEBUG - memset( chunk, 0xfe, sizeof(Chunk) ); -#endif - chunk->next = _root; - _root = chunk; - } - void Trace( const char* name ) { - printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, _maxAllocs, _maxAllocs*SIZE/1024, _currentAllocs, SIZE, _nAllocs, _blockPtrs.Size() ); - } - - void SetTracked() { - _nUntracked--; - } - - int Untracked() const { - return _nUntracked; - } - - // This number is perf sensitive. 4k seems like a good tradeoff on my machine. - // The test file is large, 170k. - // Release: VS2010 gcc(no opt) - // 1k: 4000 - // 2k: 4000 - // 4k: 3900 21000 - // 16k: 5200 - // 32k: 4300 - // 64k: 4000 21000 - enum { COUNT = (4*1024)/SIZE }; // Some compilers do not accept to use COUNT in private part if COUNT is private - -private: - MemPoolT( const MemPoolT& ); // not supported - void operator=( const MemPoolT& ); // not supported - - union Chunk { - Chunk* next; - char mem[SIZE]; - }; - struct Block { - Chunk chunk[COUNT]; - }; - DynArray< Block*, 10 > _blockPtrs; - Chunk* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; -}; - - - -/** - Implements the interface to the "Visitor pattern" (see the Accept() method.) - If you call the Accept() method, it requires being passed a XMLVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs - are simply called with Visit(). - - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, no children of this node or its siblings will be visited. - - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. - - Generally Accept() is called on the XMLDocument, although all nodes support visiting. - - You should never change the document from a callback. - - @sa XMLNode::Accept() -*/ -class TINYXML2_LIB XMLVisitor -{ -public: - virtual ~XMLVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { - return true; - } - /// Visit a document. - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - /// Visit an element. - virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { - return true; - } - /// Visit an element. - virtual bool VisitExit( const XMLElement& /*element*/ ) { - return true; - } - - /// Visit a declaration. - virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { - return true; - } - /// Visit a text node. - virtual bool Visit( const XMLText& /*text*/ ) { - return true; - } - /// Visit a comment node. - virtual bool Visit( const XMLComment& /*comment*/ ) { - return true; - } - /// Visit an unknown node. - virtual bool Visit( const XMLUnknown& /*unknown*/ ) { - return true; - } -}; - -// WARNING: must match XMLDocument::_errorNames[] -enum XMLError { - XML_SUCCESS = 0, - XML_NO_ERROR = 0, - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - XML_ERROR_ELEMENT_MISMATCH, - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - XML_ERROR_IDENTIFYING_TAG, - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE, - - XML_ERROR_COUNT -}; - - -/* - Utility functionality. -*/ -class XMLUtil -{ -public: - static const char* SkipWhiteSpace( const char* p ) { - TIXMLASSERT( p ); - while( IsWhiteSpace(*p) ) { - ++p; - } - TIXMLASSERT( p ); - return p; - } - static char* SkipWhiteSpace( char* p ) { - return const_cast( SkipWhiteSpace( const_cast(p) ) ); - } - - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static bool IsWhiteSpace( char p ) { - return !IsUTF8Continuation(p) && isspace( static_cast(p) ); - } - - inline static bool IsNameStartChar( unsigned char ch ) { - if ( ch >= 128 ) { - // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() - return true; - } - if ( isalpha( ch ) ) { - return true; - } - return ch == ':' || ch == '_'; - } - - inline static bool IsNameChar( unsigned char ch ) { - return IsNameStartChar( ch ) - || isdigit( ch ) - || ch == '.' - || ch == '-'; - } - - inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { - if ( p == q ) { - return true; - } - return strncmp( p, q, nChar ) == 0; - } - - inline static bool IsUTF8Continuation( char p ) { - return ( p & 0x80 ) != 0; - } - - static const char* ReadBOM( const char* p, bool* hasBOM ); - // p is the starting location, - // the UTF-8 value of the entity will be placed in value, and length filled in. - static const char* GetCharacterRef( const char* p, char* value, int* length ); - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); - - // converts primitive types to strings - static void ToStr( int v, char* buffer, int bufferSize ); - static void ToStr( unsigned v, char* buffer, int bufferSize ); - static void ToStr( bool v, char* buffer, int bufferSize ); - static void ToStr( float v, char* buffer, int bufferSize ); - static void ToStr( double v, char* buffer, int bufferSize ); - - // converts strings to primitive types - static bool ToInt( const char* str, int* value ); - static bool ToUnsigned( const char* str, unsigned* value ); - static bool ToBool( const char* str, bool* value ); - static bool ToFloat( const char* str, float* value ); - static bool ToDouble( const char* str, double* value ); -}; - - -/** XMLNode is a base class for every object that is in the - XML Document Object Model (DOM), except XMLAttributes. - Nodes have siblings, a parent, and children which can - be navigated. A node is always in a XMLDocument. - The type of a XMLNode can be queried, and it can - be cast to its more defined type. - - A XMLDocument allocates memory for all its Nodes. - When the XMLDocument gets deleted, all its Nodes - will also be deleted. - - @verbatim - A Document can contain: Element (container or leaf) - Comment (leaf) - Unknown (leaf) - Declaration( leaf ) - - An Element can contain: Element (container or leaf) - Text (leaf) - Attributes (not on tree) - Comment (leaf) - Unknown (leaf) - - @endverbatim -*/ -class TINYXML2_LIB XMLNode -{ - friend class XMLDocument; - friend class XMLElement; -public: - - /// Get the XMLDocument that owns this XMLNode. - const XMLDocument* GetDocument() const { - TIXMLASSERT( _document ); - return _document; - } - /// Get the XMLDocument that owns this XMLNode. - XMLDocument* GetDocument() { - TIXMLASSERT( _document ); - return _document; - } - - /// Safely cast to an Element, or null. - virtual XMLElement* ToElement() { - return 0; - } - /// Safely cast to Text, or null. - virtual XMLText* ToText() { - return 0; - } - /// Safely cast to a Comment, or null. - virtual XMLComment* ToComment() { - return 0; - } - /// Safely cast to a Document, or null. - virtual XMLDocument* ToDocument() { - return 0; - } - /// Safely cast to a Declaration, or null. - virtual XMLDeclaration* ToDeclaration() { - return 0; - } - /// Safely cast to an Unknown, or null. - virtual XMLUnknown* ToUnknown() { - return 0; - } - - virtual const XMLElement* ToElement() const { - return 0; - } - virtual const XMLText* ToText() const { - return 0; - } - virtual const XMLComment* ToComment() const { - return 0; - } - virtual const XMLDocument* ToDocument() const { - return 0; - } - virtual const XMLDeclaration* ToDeclaration() const { - return 0; - } - virtual const XMLUnknown* ToUnknown() const { - return 0; - } - - /** The meaning of 'value' changes for the specific type. - @verbatim - Document: empty (NULL is returned, not an empty string) - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - const char* Value() const; - - /** Set the Value of an XML node. - @sa Value() - */ - void SetValue( const char* val, bool staticMem=false ); - - /// Get the parent of this node on the DOM. - const XMLNode* Parent() const { - return _parent; - } - - XMLNode* Parent() { - return _parent; - } - - /// Returns true if this node has no children. - bool NoChildren() const { - return !_firstChild; - } - - /// Get the first child node, or null if none exists. - const XMLNode* FirstChild() const { - return _firstChild; - } - - XMLNode* FirstChild() { - return _firstChild; - } - - /** Get the first child element, or optionally the first child - element with the specified name. - */ - const XMLElement* FirstChildElement( const char* name = 0 ) const; - - XMLElement* FirstChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->FirstChildElement( name )); - } - - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { - return _lastChild; - } - - XMLNode* LastChild() { - return _lastChild; - } - - /** Get the last child element or optionally the last child - element with the specified name. - */ - const XMLElement* LastChildElement( const char* name = 0 ) const; - - XMLElement* LastChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->LastChildElement(name) ); - } - - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { - return _prev; - } - - XMLNode* PreviousSibling() { - return _prev; - } - - /// Get the previous (left) sibling element of this node, with an optionally supplied name. - const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; - - XMLElement* PreviousSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); - } - - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { - return _next; - } - - XMLNode* NextSibling() { - return _next; - } - - /// Get the next (right) sibling element of this node, with an optionally supplied name. - const XMLElement* NextSiblingElement( const char* name = 0 ) const; - - XMLElement* NextSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->NextSiblingElement( name ) ); - } - - /** - Add a child node as the last (right) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertEndChild( XMLNode* addThis ); - - XMLNode* LinkEndChild( XMLNode* addThis ) { - return InsertEndChild( addThis ); - } - /** - Add a child node as the first (left) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertFirstChild( XMLNode* addThis ); - /** - Add a node after the specified child node. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the afterThis node - is not a child of this node, or if the node does not - belong to the same document. - */ - XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); - - /** - Delete all the children of this node. - */ - void DeleteChildren(); - - /** - Delete a child of this node. - */ - void DeleteChild( XMLNode* node ); - - /** - Make a copy of this node, but not its children. - You may pass in a Document pointer that will be - the owner of the new Node. If the 'document' is - null, then the node returned will be allocated - from the current Document. (this->GetDocument()) - - Note: if called on a XMLDocument, this will return null. - */ - virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; - - /** - Test if 2 nodes are the same, but don't test children. - The 2 nodes do not need to be in the same Document. - - Note: if called on a XMLDocument, this will return false. - */ - virtual bool ShallowEqual( const XMLNode* compare ) const = 0; - - /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the XMLVisitor interface. - - This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this - interface versus any other.) - - The interface has been based on ideas from: - - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - - Which are both good references for "visiting". - - An example of using Accept(): - @verbatim - XMLPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( XMLVisitor* visitor ) const = 0; - -protected: - XMLNode( XMLDocument* ); - virtual ~XMLNode(); - - virtual char* ParseDeep( char*, StrPair* ); - - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - - XMLNode* _firstChild; - XMLNode* _lastChild; - - XMLNode* _prev; - XMLNode* _next; - -private: - MemPool* _memPool; - void Unlink( XMLNode* child ); - static void DeleteNode( XMLNode* node ); - void InsertChildPreamble( XMLNode* insertThis ) const; - - XMLNode( const XMLNode& ); // not supported - XMLNode& operator=( const XMLNode& ); // not supported -}; - - -/** XML text. - - Note that a text node can have child element nodes, for example: - @verbatim - This is bold - @endverbatim - - A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCData() and query it with CData(). -*/ -class TINYXML2_LIB XMLText : public XMLNode -{ - friend class XMLBase; - friend class XMLDocument; -public: - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLText* ToText() { - return this; - } - virtual const XMLText* ToText() const { - return this; - } - - /// Declare whether this should be CDATA or standard text. - void SetCData( bool isCData ) { - _isCData = isCData; - } - /// Returns true if this is a CDATA text element. - bool CData() const { - return _isCData; - } - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} - virtual ~XMLText() {} - - char* ParseDeep( char*, StrPair* endTag ); - -private: - bool _isCData; - - XMLText( const XMLText& ); // not supported - XMLText& operator=( const XMLText& ); // not supported -}; - - -/** An XML Comment. */ -class TINYXML2_LIB XMLComment : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLComment* ToComment() { - return this; - } - virtual const XMLComment* ToComment() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLComment( XMLDocument* doc ); - virtual ~XMLComment(); - - char* ParseDeep( char*, StrPair* endTag ); - -private: - XMLComment( const XMLComment& ); // not supported - XMLComment& operator=( const XMLComment& ); // not supported -}; - - -/** In correct XML the declaration is the first entry in the file. - @verbatim - - @endverbatim - - TinyXML-2 will happily read or write files without a declaration, - however. - - The text of the declaration isn't interpreted. It is parsed - and written as a string. -*/ -class TINYXML2_LIB XMLDeclaration : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLDeclaration* ToDeclaration() { - return this; - } - virtual const XMLDeclaration* ToDeclaration() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLDeclaration( XMLDocument* doc ); - virtual ~XMLDeclaration(); - - char* ParseDeep( char*, StrPair* endTag ); - -private: - XMLDeclaration( const XMLDeclaration& ); // not supported - XMLDeclaration& operator=( const XMLDeclaration& ); // not supported -}; - - -/** Any tag that TinyXML-2 doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. - - DTD tags get thrown into XMLUnknowns. -*/ -class TINYXML2_LIB XMLUnknown : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLUnknown* ToUnknown() { - return this; - } - virtual const XMLUnknown* ToUnknown() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLUnknown( XMLDocument* doc ); - virtual ~XMLUnknown(); - - char* ParseDeep( char*, StrPair* endTag ); - -private: - XMLUnknown( const XMLUnknown& ); // not supported - XMLUnknown& operator=( const XMLUnknown& ); // not supported -}; - - - -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. - - @note The attributes are not XMLNodes. You may only query the - Next() attribute in a list. -*/ -class TINYXML2_LIB XMLAttribute -{ - friend class XMLElement; -public: - /// The name of the attribute. - const char* Name() const; - - /// The value of the attribute. - const char* Value() const; - - /// The next attribute in the list. - const XMLAttribute* Next() const { - return _next; - } - - /** IntValue interprets the attribute as an integer, and returns the value. - If the value isn't an integer, 0 will be returned. There is no error checking; - use QueryIntValue() if you need error checking. - */ - int IntValue() const { - int i=0; - QueryIntValue( &i ); - return i; - } - /// Query as an unsigned integer. See IntValue() - unsigned UnsignedValue() const { - unsigned i=0; - QueryUnsignedValue( &i ); - return i; - } - /// Query as a boolean. See IntValue() - bool BoolValue() const { - bool b=false; - QueryBoolValue( &b ); - return b; - } - /// Query as a double. See IntValue() - double DoubleValue() const { - double d=0; - QueryDoubleValue( &d ); - return d; - } - /// Query as a float. See IntValue() - float FloatValue() const { - float f=0; - QueryFloatValue( &f ); - return f; - } - - /** QueryIntValue interprets the attribute as an integer, and returns the value - in the provided parameter. The function will return XML_NO_ERROR on success, - and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. - */ - XMLError QueryIntValue( int* value ) const; - /// See QueryIntValue - XMLError QueryUnsignedValue( unsigned int* value ) const; - /// See QueryIntValue - XMLError QueryBoolValue( bool* value ) const; - /// See QueryIntValue - XMLError QueryDoubleValue( double* value ) const; - /// See QueryIntValue - XMLError QueryFloatValue( float* value ) const; - - /// Set the attribute to a string value. - void SetAttribute( const char* value ); - /// Set the attribute to value. - void SetAttribute( int value ); - /// Set the attribute to value. - void SetAttribute( unsigned value ); - /// Set the attribute to value. - void SetAttribute( bool value ); - /// Set the attribute to value. - void SetAttribute( double value ); - /// Set the attribute to value. - void SetAttribute( float value ); - -private: - enum { BUF_SIZE = 200 }; - - XMLAttribute() : _next( 0 ), _memPool( 0 ) {} - virtual ~XMLAttribute() {} - - XMLAttribute( const XMLAttribute& ); // not supported - void operator=( const XMLAttribute& ); // not supported - void SetName( const char* name ); - - char* ParseDeep( char* p, bool processEntities ); - - mutable StrPair _name; - mutable StrPair _value; - XMLAttribute* _next; - MemPool* _memPool; -}; - - -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class TINYXML2_LIB XMLElement : public XMLNode -{ - friend class XMLBase; - friend class XMLDocument; -public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { - return Value(); - } - /// Set the name of the element. - void SetName( const char* str, bool staticMem=false ) { - SetValue( str, staticMem ); - } - - virtual XMLElement* ToElement() { - return this; - } - virtual const XMLElement* ToElement() const { - return this; - } - virtual bool Accept( XMLVisitor* visitor ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none - exists. For example: - - @verbatim - const char* value = ele->Attribute( "foo" ); - @endverbatim - - The 'value' parameter is normally null. However, if specified, - the attribute will only be returned if the 'name' and 'value' - match. This allow you to write code: - - @verbatim - if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); - @endverbatim - - rather than: - @verbatim - if ( ele->Attribute( "foo" ) ) { - if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); - } - @endverbatim - */ - const char* Attribute( const char* name, const char* value=0 ) const; - - /** Given an attribute name, IntAttribute() returns the value - of the attribute interpreted as an integer. 0 will be - returned if there is an error. For a method with error - checking, see QueryIntAttribute() - */ - int IntAttribute( const char* name ) const { - int i=0; - QueryIntAttribute( name, &i ); - return i; - } - /// See IntAttribute() - unsigned UnsignedAttribute( const char* name ) const { - unsigned i=0; - QueryUnsignedAttribute( name, &i ); - return i; - } - /// See IntAttribute() - bool BoolAttribute( const char* name ) const { - bool b=false; - QueryBoolAttribute( name, &b ); - return b; - } - /// See IntAttribute() - double DoubleAttribute( const char* name ) const { - double d=0; - QueryDoubleAttribute( name, &d ); - return d; - } - /// See IntAttribute() - float FloatAttribute( const char* name ) const { - float f=0; - QueryFloatAttribute( name, &f ); - return f; - } - - /** Given an attribute name, QueryIntAttribute() returns - XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryIntAttribute( const char* name, int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryIntValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryUnsignedValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryBoolAttribute( const char* name, bool* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryBoolValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute( const char* name, double* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryDoubleValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute( const char* name, float* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryFloatValue( value ); - } - - - /** Given an attribute name, QueryAttribute() returns - XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. It is overloaded for the primitive types, - and is a generally more convenient replacement of - QueryIntAttribute() and related functions. - - If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - int QueryAttribute( const char* name, int* value ) const { - return QueryIntAttribute( name, value ); - } - - int QueryAttribute( const char* name, unsigned int* value ) const { - return QueryUnsignedAttribute( name, value ); - } - - int QueryAttribute( const char* name, bool* value ) const { - return QueryBoolAttribute( name, value ); - } - - int QueryAttribute( const char* name, double* value ) const { - return QueryDoubleAttribute( name, value ); - } - - int QueryAttribute( const char* name, float* value ) const { - return QueryFloatAttribute( name, value ); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, const char* value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, int value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, unsigned value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, bool value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, double value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, float value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /** - Delete an attribute. - */ - void DeleteAttribute( const char* name ); - - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { - return _rootAttribute; - } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute( const char* name ) const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the XMLText child - and accessing it directly. - - If the first child of 'this' is a XMLText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". - */ - const char* GetText() const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, SetText() is limited compared to creating an XMLText child - and mutating it directly. - - If the first child of 'this' is a XMLText, SetText() sets its value to - the given string, otherwise it will create a first child that is an XMLText. - - This is a convenient method for setting the text of simple contained text: - @verbatim - This is text - fooElement->SetText( "Hullaballoo!" ); - Hullaballoo! - @endverbatim - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then it will not change "This is text", but rather prefix it with a text element: - @verbatim - Hullaballoo!This is text - @endverbatim - - For this XML: - @verbatim - - @endverbatim - SetText() will generate - @verbatim - Hullaballoo! - @endverbatim - */ - void SetText( const char* inText ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( int value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( unsigned value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( bool value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( double value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( float value ); - - /** - Convenience method to query the value of a child text node. This is probably best - shown by example. Given you have a document is this form: - @verbatim - - 1 - 1.4 - - @endverbatim - - The QueryIntText() and similar functions provide a safe and easier way to get to the - "value" of x and y. - - @verbatim - int x = 0; - float y = 0; // types of x and y are contrived for example - const XMLElement* xElement = pointElement->FirstChildElement( "x" ); - const XMLElement* yElement = pointElement->FirstChildElement( "y" ); - xElement->QueryIntText( &x ); - yElement->QueryFloatText( &y ); - @endverbatim - - @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted - to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. - - */ - XMLError QueryIntText( int* ival ) const; - /// See QueryIntText() - XMLError QueryUnsignedText( unsigned* uval ) const; - /// See QueryIntText() - XMLError QueryBoolText( bool* bval ) const; - /// See QueryIntText() - XMLError QueryDoubleText( double* dval ) const; - /// See QueryIntText() - XMLError QueryFloatText( float* fval ) const; - - // internal: - enum { - OPEN, // - CLOSED, // - CLOSING // - }; - int ClosingType() const { - return _closingType; - } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - char* ParseDeep( char* p, StrPair* endTag ); - -private: - XMLElement( XMLDocument* doc ); - virtual ~XMLElement(); - XMLElement( const XMLElement& ); // not supported - void operator=( const XMLElement& ); // not supported - - XMLAttribute* FindAttribute( const char* name ) { - return const_cast(const_cast(this)->FindAttribute( name )); - } - XMLAttribute* FindOrCreateAttribute( const char* name ); - //void LinkAttribute( XMLAttribute* attrib ); - char* ParseAttributes( char* p ); - static void DeleteAttribute( XMLAttribute* attribute ); - - enum { BUF_SIZE = 200 }; - int _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; -}; - - -enum Whitespace { - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE -}; - - -/** A Document binds together all the functionality. - It can be saved, loaded, and printed to the screen. - All Nodes are connected and allocated to a Document. - If the Document is deleted, all its Nodes are also deleted. -*/ -class TINYXML2_LIB XMLDocument : public XMLNode -{ - friend class XMLElement; -public: - /// constructor - XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() { - TIXMLASSERT( this == _document ); - return this; - } - virtual const XMLDocument* ToDocument() const { - TIXMLASSERT( this == _document ); - return this; - } - - /** - Parse an XML file from a character string. - Returns XML_NO_ERROR (0) on success, or - an errorID. - - You may optionally pass in the 'nBytes', which is - the number of bytes which will be parsed. If not - specified, TinyXML-2 will assume 'xml' points to a - null terminated string. - */ - XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); - - /** - Load an XML file from disk. - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError LoadFile( const char* filename ); - - /** - Load an XML file from disk. You are responsible - for providing and closing the FILE*. - - NOTE: The file should be opened as binary ("rb") - not text in order for TinyXML-2 to correctly - do newline normalization. - - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError LoadFile( FILE* ); - - /** - Save the XML file to disk. - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError SaveFile( const char* filename, bool compact = false ); - - /** - Save the XML file to disk. You are responsible - for providing and closing the FILE*. - - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError SaveFile( FILE* fp, bool compact = false ); - - bool ProcessEntities() const { - return _processEntities; - } - Whitespace WhitespaceMode() const { - return _whitespace; - } - - /** - Returns true if this document has a leading Byte Order Mark of UTF8. - */ - bool HasBOM() const { - return _writeBOM; - } - /** Sets whether to write the BOM when writing the file. - */ - void SetBOM( bool useBOM ) { - _writeBOM = useBOM; - } - - /** Return the root element of DOM. Equivalent to FirstChildElement(). - To get the first node, use FirstChild(). - */ - XMLElement* RootElement() { - return FirstChildElement(); - } - const XMLElement* RootElement() const { - return FirstChildElement(); - } - - /** Print the Document. If the Printer is not provided, it will - print to stdout. If you provide Printer, this can print to a file: - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Or you can use a printer to print to memory: - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - // printer.CStr() has a const char* to the XML - @endverbatim - */ - void Print( XMLPrinter* streamer=0 ) const; - virtual bool Accept( XMLVisitor* visitor ) const; - - /** - Create a new Element associated with - this Document. The memory for the Element - is managed by the Document. - */ - XMLElement* NewElement( const char* name ); - /** - Create a new Comment associated with - this Document. The memory for the Comment - is managed by the Document. - */ - XMLComment* NewComment( const char* comment ); - /** - Create a new Text associated with - this Document. The memory for the Text - is managed by the Document. - */ - XMLText* NewText( const char* text ); - /** - Create a new Declaration associated with - this Document. The memory for the object - is managed by the Document. - - If the 'text' param is null, the standard - declaration is used.: - @verbatim - - @endverbatim - */ - XMLDeclaration* NewDeclaration( const char* text=0 ); - /** - Create a new Unknown associated with - this Document. The memory for the object - is managed by the Document. - */ - XMLUnknown* NewUnknown( const char* text ); - - /** - Delete a node associated with this document. - It will be unlinked from the DOM. - */ - void DeleteNode( XMLNode* node ); - - void SetError( XMLError error, const char* str1, const char* str2 ); - - /// Return true if there was an error parsing the document. - bool Error() const { - return _errorID != XML_NO_ERROR; - } - /// Return the errorID. - XMLError ErrorID() const { - return _errorID; - } - const char* ErrorName() const; - - /// Return a possibly helpful diagnostic location or string. - const char* GetErrorStr1() const { - return _errorStr1; - } - /// Return a possibly helpful secondary diagnostic location or string. - const char* GetErrorStr2() const { - return _errorStr2; - } - /// If there is an error, print it to stdout. - void PrintError() const; - - /// Clear the document, resetting it to the initial state. - void Clear(); - - // internal - char* Identify( char* p, XMLNode** node ); - - virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { - return 0; - } - virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { - return false; - } - -private: - XMLDocument( const XMLDocument& ); // not supported - void operator=( const XMLDocument& ); // not supported - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespace; - const char* _errorStr1; - const char* _errorStr2; - char* _charBuffer; - - MemPoolT< sizeof(XMLElement) > _elementPool; - MemPoolT< sizeof(XMLAttribute) > _attributePool; - MemPoolT< sizeof(XMLText) > _textPool; - MemPoolT< sizeof(XMLComment) > _commentPool; - - static const char* _errorNames[XML_ERROR_COUNT]; - - void Parse(); -}; - - -/** - A XMLHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - - - - - - - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - XMLElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - XMLElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - XMLElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - XMLElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. XMLHandle addresses the verbosity - of such code. A XMLHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - XMLHandle docHandle( &document ); - XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - XMLHandle handleCopy = handle; - @endverbatim - - See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. -*/ -class TINYXML2_LIB XMLHandle -{ -public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - XMLHandle( XMLNode* node ) { - _node = node; - } - /// Create a handle from a node. - XMLHandle( XMLNode& node ) { - _node = &node; - } - /// Copy constructor - XMLHandle( const XMLHandle& ref ) { - _node = ref._node; - } - /// Assignment - XMLHandle& operator=( const XMLHandle& ref ) { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { - return XMLHandle( _node ? _node->FirstChild() : 0 ); - } - /// Get the first child element of this handle. - XMLHandle FirstChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - /// Get the last child of this handle. - XMLHandle LastChild() { - return XMLHandle( _node ? _node->LastChild() : 0 ); - } - /// Get the last child element of this handle. - XMLHandle LastChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { - return XMLHandle( _node ? _node->PreviousSibling() : 0 ); - } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { - return XMLHandle( _node ? _node->NextSibling() : 0 ); - } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { - return _node; - } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { - return ( ( _node == 0 ) ? 0 : _node->ToElement() ); - } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { - return ( ( _node == 0 ) ? 0 : _node->ToText() ); - } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { - return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); - } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { - return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); - } - -private: - XMLNode* _node; -}; - - -/** - A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the - same in all regards, except for the 'const' qualifiers. See XMLHandle for API. -*/ -class TINYXML2_LIB XMLConstHandle -{ -public: - XMLConstHandle( const XMLNode* node ) { - _node = node; - } - XMLConstHandle( const XMLNode& node ) { - _node = &node; - } - XMLConstHandle( const XMLConstHandle& ref ) { - _node = ref._node; - } - - XMLConstHandle& operator=( const XMLConstHandle& ref ) { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const { - return XMLConstHandle( _node ? _node->FirstChild() : 0 ); - } - const XMLConstHandle FirstChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - const XMLConstHandle LastChild() const { - return XMLConstHandle( _node ? _node->LastChild() : 0 ); - } - const XMLConstHandle LastChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - const XMLConstHandle PreviousSibling() const { - return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); - } - const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - const XMLConstHandle NextSibling() const { - return XMLConstHandle( _node ? _node->NextSibling() : 0 ); - } - const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - - const XMLNode* ToNode() const { - return _node; - } - const XMLElement* ToElement() const { - return ( ( _node == 0 ) ? 0 : _node->ToElement() ); - } - const XMLText* ToText() const { - return ( ( _node == 0 ) ? 0 : _node->ToText() ); - } - const XMLUnknown* ToUnknown() const { - return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); - } - const XMLDeclaration* ToDeclaration() const { - return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); - } - -private: - const XMLNode* _node; -}; - - -/** - Printing functionality. The XMLPrinter gives you more - options than the XMLDocument::Print() method. - - It can: - -# Print to memory. - -# Print to a file you provide. - -# Print XML without a XMLDocument. - - Print to Memory - - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - SomeFunction( printer.CStr() ); - @endverbatim - - Print to a File - - You provide the file pointer. - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Print without a XMLDocument - - When loading, an XML parser is very useful. However, sometimes - when saving, it just gets in the way. The code is often set up - for streaming, and constructing the DOM is just overhead. - - The Printer supports the streaming case. The following code - prints out a trivially simple XML file without ever creating - an XML document. - - @verbatim - XMLPrinter printer( fp ); - printer.OpenElement( "foo" ); - printer.PushAttribute( "foo", "bar" ); - printer.CloseElement(); - @endverbatim -*/ -class TINYXML2_LIB XMLPrinter : public XMLVisitor -{ -public: - /** Construct the printer. If the FILE* is specified, - this will print to the FILE. Else it will print - to memory, and the result is available in CStr(). - If 'compact' is set to true, then output is created - with only required whitespace and newlines. - */ - XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); - virtual ~XMLPrinter() {} - - /** If streaming, write the BOM and declaration. */ - void PushHeader( bool writeBOM, bool writeDeclaration ); - /** If streaming, start writing an element. - The element must be closed with CloseElement() - */ - void OpenElement( const char* name, bool compactMode=false ); - /// If streaming, add an attribute to an open element. - void PushAttribute( const char* name, const char* value ); - void PushAttribute( const char* name, int value ); - void PushAttribute( const char* name, unsigned value ); - void PushAttribute( const char* name, bool value ); - void PushAttribute( const char* name, double value ); - /// If streaming, close the Element. - virtual void CloseElement( bool compactMode=false ); - - /// Add a text node. - void PushText( const char* text, bool cdata=false ); - /// Add a text node from an integer. - void PushText( int value ); - /// Add a text node from an unsigned. - void PushText( unsigned value ); - /// Add a text node from a bool. - void PushText( bool value ); - /// Add a text node from a float. - void PushText( float value ); - /// Add a text node from a double. - void PushText( double value ); - - /// Add a comment - void PushComment( const char* comment ); - - void PushDeclaration( const char* value ); - void PushUnknown( const char* value ); - - virtual bool VisitEnter( const XMLDocument& /*doc*/ ); - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); - virtual bool VisitExit( const XMLElement& element ); - - virtual bool Visit( const XMLText& text ); - virtual bool Visit( const XMLComment& comment ); - virtual bool Visit( const XMLDeclaration& declaration ); - virtual bool Visit( const XMLUnknown& unknown ); - - /** - If in print to memory mode, return a pointer to - the XML file in memory. - */ - const char* CStr() const { - return _buffer.Mem(); - } - /** - If in print to memory mode, return the size - of the XML file in memory. (Note the size returned - includes the terminating null.) - */ - int CStrSize() const { - return _buffer.Size(); - } - /** - If in print to memory mode, reset the buffer to the - beginning. - */ - void ClearBuffer() { - _buffer.Clear(); - _buffer.Push(0); - } - -protected: - virtual bool CompactMode( const XMLElement& ) { return _compactMode; } - - /** Prints out the space before an element. You may override to change - the space and tabs used. A PrintSpace() override should call Print(). - */ - virtual void PrintSpace( int depth ); - void Print( const char* format, ... ); - - void SealElementIfJustOpened(); - bool _elementJustOpened; - DynArray< const char*, 10 > _stack; - -private: - void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. - - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum { - ENTITY_RANGE = 64, - BUF_SIZE = 200 - }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray< char, 20 > _buffer; -}; - - -} // tinyxml2 - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // TINYXML2_INCLUDED diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt deleted file mode 100644 index 72feba3..0000000 --- a/plugins/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ - -## ===================== -## == List of plugins == -## ===================== - -SET( - _directories - GenericPlugins - VTKFilters - VTKIO - VTKWidgets - ITKAnisotropicSmoothing - ITKBinaryFunctorFilters - ITKDistanceMapFilters - ITKFiniteDifference - ITKImageGenericFilters_1 - ITKImageInterpolators - ITKIO - ITKLevelSetFilters - ITKMorphology - ITKNeighborhoodOperatorFilters - ITKParaMorphology - ITKSeparableFilters - ITKSliceFilters - ITKUnaryFunctorFilters - ITKRasterFilters - cpExtensions - ) - -## ========================= -## == Compile each plugin == -## ========================= - -INCLUDE_DIRECTORIES( - ${PROJECT_SOURCE_DIR}/lib - ${PROJECT_BINARY_DIR}/lib - ) -FOREACH(_dir ${_directories}) - cpPlugins_BuildPluginsLibrary(cpPlugins_${_dir} ${_dir}) - TARGET_LINK_LIBRARIES(cpPlugins_${_dir} cpPluginsDataObjects) -ENDFOREACH(_dir) - -TARGET_LINK_LIBRARIES(cpPlugins_ITKDistanceMapFilters cpPlugins_ITKUnaryFunctorFilters) -TARGET_LINK_LIBRARIES(cpPlugins_ITKAnisotropicSmoothing cpPlugins_ITKFiniteDifference) -TARGET_LINK_LIBRARIES( - cpPlugins_ITKLevelSetFilters - cpPlugins_ITKAnisotropicSmoothing - cpPlugins_ITKNeighborhoodOperatorFilters - cpPlugins_ITKImageGenericFilters_1 - ) -TARGET_LINK_LIBRARIES(cpPlugins_ITKParaMorphology cpPlugins_ITKUnaryFunctorFilters) -TARGET_LINK_LIBRARIES(cpPlugins_ITKSeparableFilters cpPlugins_ITKImageGenericFilters_1) -TARGET_LINK_LIBRARIES( - cpPlugins_ITKSliceFilters - cpPlugins_ITKImageInterpolators - cpPlugins_ITKImageGenericFilters_1 - ) - -## eof - $RCSfile$ diff --git a/plugins/GenericPlugins/DataReproducer.cxx b/plugins/GenericPlugins/DataReproducer.cxx deleted file mode 100644 index 586e37b..0000000 --- a/plugins/GenericPlugins/DataReproducer.cxx +++ /dev/null @@ -1,49 +0,0 @@ -#include "DataReproducer.h" -#include - -// ------------------------------------------------------------------------- -void cpPlugins_GenericPlugins::DataReproducer:: -AddInput( const std::string& n, cpPlugins::Pipeline::DataObject* o ) -{ - this->Superclass::AddInput( n, o ); - auto out = - dynamic_cast< cpPlugins::Pipeline::OutputPort* >( - this->m_Outputs.find( "Output" )->second - ); - out->Set( o ); -} - -// ------------------------------------------------------------------------- -void cpPlugins_GenericPlugins::DataReproducer:: -SetInput( const std::string& n, cpPlugins::Pipeline::DataObject* o ) -{ - this->Superclass::SetInput( n, o ); - auto out = - dynamic_cast< cpPlugins::Pipeline::OutputPort* >( - this->m_Outputs.find( "Output" )->second - ); - out->Set( o ); -} - -// ------------------------------------------------------------------------- -cpPlugins_GenericPlugins::DataReproducer:: -DataReproducer( ) - : Superclass( ) -{ - this->_ConfigureInput( "Input", true, false ); - this->_ConfigureOutput( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPlugins_GenericPlugins::DataReproducer:: -~DataReproducer( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins_GenericPlugins::DataReproducer:: -_GenerateData( ) -{ -} - -// eof - $RCSfile$ diff --git a/plugins/GenericPlugins/DataReproducer.h b/plugins/GenericPlugins/DataReproducer.h deleted file mode 100644 index e61c453..0000000 --- a/plugins/GenericPlugins/DataReproducer.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __cpPlugins_GenericPlugins__DataReproducer__h__ -#define __cpPlugins_GenericPlugins__DataReproducer__h__ - -#include -#include - -namespace cpPlugins_GenericPlugins -{ - /** - */ - class cpPlugins_GenericPlugins_EXPORT DataReproducer - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - DataReproducer, - cpPlugins::Pipeline::ProcessObject, - GenericPlugins - ); - - public: - virtual void AddInput( - const std::string& n, cpPlugins::Pipeline::DataObject* o - ) override; - virtual void SetInput( - const std::string& n, cpPlugins::Pipeline::DataObject* o - ) override; - }; - -} // ecapseman - -#endif // __cpPlugins_GenericPlugins__DataReproducer__h__ - -// eof - $RCSfile$ diff --git a/plugins/GenericPlugins/JoinBoundingBoxes.cxx b/plugins/GenericPlugins/JoinBoundingBoxes.cxx deleted file mode 100644 index d3bdfb5..0000000 --- a/plugins/GenericPlugins/JoinBoundingBoxes.cxx +++ /dev/null @@ -1,44 +0,0 @@ -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPlugins_GenericPlugins::JoinBoundingBoxes:: -JoinBoundingBoxes( ) - : Superclass( ) -{ - this->_ConfigureInput( "Inputs", true, true ); - this->_ConfigureOutput< cpInstances::DataObjects::BoundingBox >( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPlugins_GenericPlugins::JoinBoundingBoxes:: -~JoinBoundingBoxes( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPlugins_GenericPlugins::JoinBoundingBoxes:: -_GenerateData( ) -{ - typedef cpPlugins::Pipeline::DataObject _TDO; - typedef cpInstances::DataObjects::BoundingBox _TBB; - - auto out = dynamic_cast< _TBB* >( this->GetOutput( "Output" ) ); - unsigned int nInputs = this->GetInputSize( "Inputs" ); - for( unsigned int i = 0; i < nInputs; ++i ) - { - auto in = dynamic_cast< _TDO* >( this->GetInput( "Inputs", i ) ); - if( i > 0 ) - { - _TBB::Pointer bb = _TBB::New( ); - bb->SetDataObject( in ); - out->Blend( bb ); - } - else - out->SetDataObject( in ); - - } // rof -} - -// eof - $RCSfile$ diff --git a/plugins/GenericPlugins/JoinBoundingBoxes.h b/plugins/GenericPlugins/JoinBoundingBoxes.h deleted file mode 100644 index 6751dad..0000000 --- a/plugins/GenericPlugins/JoinBoundingBoxes.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __CPPLUGINSGENERICFILTERS__JOINBOUNDINGBOXES__H__ -#define __CPPLUGINSGENERICFILTERS__JOINBOUNDINGBOXES__H__ - -#include -#include - -namespace cpPlugins_GenericPlugins -{ - /** - */ - class cpPlugins_GenericPlugins_EXPORT JoinBoundingBoxes - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - JoinBoundingBoxes, - cpPlugins::Pipeline::ProcessObject, - GenericPlugins - ); - }; - -} // ecapseman - -#endif // __CPPLUGINSGENERICFILTERS__JOINBOUNDINGBOXES__H__ - -// eof - $RCSfile$ diff --git a/plugins/IO/ImageJSkeletonWriter.cxx b/plugins/IO/ImageJSkeletonWriter.cxx deleted file mode 100644 index 482000f..0000000 --- a/plugins/IO/ImageJSkeletonWriter.cxx +++ /dev/null @@ -1,104 +0,0 @@ -#include -#include - -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsIO::ImageJSkeletonWriter:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::SaveFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::SaveFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsIO::ImageJSkeletonWriter:: -ImageJSkeletonWriter( ) - : Superclass( ) -{ - typedef cpPluginsExtensions::Skeleton _TSkeleton; - this->_ConfigureInput< _TSkeleton >( "Input", true, false ); - - this->m_Parameters.ConfigureAsSaveFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "ImageJ files (*.txt)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginsIO::ImageJSkeletonWriter:: -~ImageJSkeletonWriter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsIO::ImageJSkeletonWriter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Skeleton_All_1( o, _GD0 ) - this->_Error( "Invalid input skeleton type." ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpPluginsIO::ImageJSkeletonWriter:: -_GD0( _TSkeleton* skeleton ) -{ - std::stringstream data; - unsigned long id = 1; - - auto mIt = skeleton->BeginEdgesRows( ); - for( ; mIt != skeleton->EndEdgesRows( ); ++mIt ) - { - auto rIt = mIt->second.begin( ); - for( ; rIt != mIt->second.end( ); ++rIt ) - { - auto eIt = rIt->second.begin( ); - for( ; eIt != rIt->second.end( ); ++eIt ) - { - auto path = *eIt; - auto p0 = path->GetSmoothPoint( 0 ); - auto p1 = path->GetSmoothPoint( 1 ); - double length = p1.EuclideanDistanceTo( p0 ); - data - << id << "\t1\t" << length << "\t" - << p0[ 0 ] << "\t" << p0[ 1 ] << "\t"<< p0[ 2 ] << "\t" - << p1[ 0 ] << "\t" << p1[ 1 ] << "\t"<< p1[ 2 ] << "\t" - << p1.EuclideanDistanceTo( p0 ) << std::endl; - id++; - - } // rof - - } // rof - - } // rof - - if( - !( - cpExtensions::Write( - data.str( ), this->m_Parameters.GetSaveFileName( "FileName" ) - ) - ) - ) - this->_Error( "Could not write on ImageJ file." ); -} - -// eof - $RCSfile$ diff --git a/plugins/IO/ImageJSkeletonWriter.h b/plugins/IO/ImageJSkeletonWriter.h deleted file mode 100644 index 5c72e5d..0000000 --- a/plugins/IO/ImageJSkeletonWriter.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef __cpPluginsIO__ImageJSkeletonWriter__h__ -#define __cpPluginsIO__ImageJSkeletonWriter__h__ - -#include -#include - -namespace cpPluginsIO -{ - /** - */ - class cpPluginsIO_EXPORT ImageJSkeletonWriter - : public cpPlugins::BaseObjects::ProcessObject - { - cpPluginsObject( ImageJSkeletonWriter, cpPlugins::BaseObjects::ProcessObject, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< class _TSkeleton > - inline void _GD0( _TSkeleton* skeleton ); - }; - -} // ecapseman - -#endif // __cpPluginsIO__ImageJSkeletonWriter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.cxx b/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.cxx deleted file mode 100644 index 26b76b0..0000000 --- a/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.cxx +++ /dev/null @@ -1,71 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKAnisotropicSmoothing::CurvatureAnisotropicDiffusionImageFilter:: -CurvatureAnisotropicDiffusionImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - this->m_Parameters.ConfigureAsUint( "NumberOfIterations", 5 ); - this->m_Parameters.ConfigureAsBool( "UseImageSpacing", false ); - this->m_Parameters.ConfigureAsReal( "ConductanceParameter", 3 ); - this->m_Parameters.ConfigureAsReal( "TimeStep", 0.0625 ); - this->m_Parameters.ConfigureAsRealTypesChoices( "OutputResolution" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKAnisotropicSmoothing::CurvatureAnisotropicDiffusionImageFilter:: -~CurvatureAnisotropicDiffusionImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKAnisotropicSmoothing::CurvatureAnisotropicDiffusionImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "No valid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKAnisotropicSmoothing::CurvatureAnisotropicDiffusionImageFilter:: -_GD0( _TImage* image ) -{ - std::string out_res = - this->m_Parameters.GetSelectedChoice( "OutputResolution" ); - if( out_res == "float" ) this->_GD1< _TImage, float >( image ); - if( out_res == "double" ) this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKAnisotropicSmoothing::CurvatureAnisotropicDiffusionImageFilter:: -_GD1( _TImage* image ) -{ - typedef itk::Image< _TScalar, _TImage::ImageDimension > _TOutImage; - typedef - itk::CurvatureAnisotropicDiffusionImageFilter< _TImage, _TOutImage > - _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetNumberOfIterations( this->m_Parameters.GetUint( "NumberOfIterations" ) ); - filter->SetUseImageSpacing( this->m_Parameters.GetBool( "UseImageSpacing" ) ); - filter->SetConductanceParameter( this->m_Parameters.GetReal( "ConductanceParameter" ) ); - filter->SetTimeStep( this->m_Parameters.GetReal( "TimeStep" ) ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.h b/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.h deleted file mode 100644 index dc91e06..0000000 --- a/plugins/ITKAnisotropicSmoothing/CurvatureAnisotropicDiffusionImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKAnisotropicSmoothing__CurvatureAnisotropicDiffusionImageFilter__h__ -#define __cpPluginsITKAnisotropicSmoothing__CurvatureAnisotropicDiffusionImageFilter__h__ - -#include -#include - -namespace cpPluginsITKAnisotropicSmoothing -{ - /** - */ - class cpPlugins_ITKAnisotropicSmoothing_EXPORT CurvatureAnisotropicDiffusionImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - CurvatureAnisotropicDiffusionImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageSmoothing - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKAnisotropicSmoothing__CurvatureAnisotropicDiffusionImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKAnisotropicSmoothing/ITKAnisotropicSmoothing.i b/plugins/ITKAnisotropicSmoothing/ITKAnisotropicSmoothing.i deleted file mode 100644 index d87073b..0000000 --- a/plugins/ITKAnisotropicSmoothing/ITKAnisotropicSmoothing.i +++ /dev/null @@ -1,12 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define functions=ScalarAnisotropicDiffusionFunction;GradientNDAnisotropicDiffusionFunction;CurvatureNDAnisotropicDiffusionFunction -tinclude itk#functions#:h|hxx -instances itk::#functions#< itk::Image< #scalar_types#, #pdims# > > - -define filters=AnisotropicDiffusionImageFilter - -tinclude itk#filters#:h|hxx -instances itk::#filters#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #real_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.cxx b/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.cxx deleted file mode 100644 index b297489..0000000 --- a/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.cxx +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKBinaryFunctorFilters::BinaryArithmeticImageFilter:: -BinaryArithmeticImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input1", true, false ); - this->_ConfigureInput< _TImage >( "Input2", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - std::vector< std::string > choices; - choices.push_back( "Add" ); - choices.push_back( "Subtract" ); - choices.push_back( "Multiply" ); - choices.push_back( "Divide" ); - choices.push_back( "DivideOrZero" ); - choices.push_back( "Pow" ); - this->m_Parameters.ConfigureAsChoices( "Operator", choices ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKBinaryFunctorFilters::BinaryArithmeticImageFilter:: -~BinaryArithmeticImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKBinaryFunctorFilters::BinaryArithmeticImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input1" ); - cpPlugins_Demangle_Image_IntPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKBinaryFunctorFilters::BinaryArithmeticImageFilter:: -_GD0( _TImage* image1 ) -{ - typedef itk::AddImageFilter< _TImage, _TImage > _TAdd; - typedef itk::SubtractImageFilter< _TImage, _TImage > _TSubtract; - typedef itk::MultiplyImageFilter< _TImage, _TImage > _TMultiply; - typedef itk::DivideImageFilter< _TImage, _TImage, _TImage > _TDivide; - typedef itk::DivideOrZeroOutImageFilter< _TImage, _TImage > _TDivideOrZero; - typedef itk::PowImageFilter< _TImage, _TImage > _TPow; - - auto image2 = this->GetInputData< _TImage >( "Input2" ); - if( image2 == NULL ) - this->_Error( "Incompatible second input image." ); - std::string op = this->m_Parameters.GetSelectedChoice( "Operator" ); - if( op == "Add" ) - this->_GD1< _TAdd, _TImage >( image1, image2 ); - else if( op == "Subtract" ) - this->_GD1< _TSubtract, _TImage >( image1, image2 ); - else if( op == "Multiply" ) - this->_GD1< _TMultiply, _TImage >( image1, image2 ); - else if( op == "Divide" ) - this->_GD1< _TDivide, _TImage >( image1, image2 ); - else if( op == "DivideOrZero" ) - this->_GD1< _TDivideOrZero, _TImage >( image1, image2 ); - else if( op == "Pow" ) - this->_GD1< _TPow, _TImage >( image1, image2 ); -} - -// ------------------------------------------------------------------------- -template< class _TFilter, class _TImage > -void cpPluginsITKBinaryFunctorFilters::BinaryArithmeticImageFilter:: -_GD1( _TImage* image1, _TImage* image2 ) -{ - // Configure filter - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput1( image1 ); - filter->SetInput2( image2 ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.h b/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.h deleted file mode 100644 index 0b3b9f6..0000000 --- a/plugins/ITKBinaryFunctorFilters/BinaryArithmeticImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKBinaryFunctorFilters__BinaryArithmeticImageFilter__h__ -#define __cpPluginsITKBinaryFunctorFilters__BinaryArithmeticImageFilter__h__ - -#include -#include - -namespace cpPluginsITKBinaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKBinaryFunctorFilters_EXPORT BinaryArithmeticImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryArithmeticImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageArithmeticFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image1 ); - - template< class _TFilter, class _TImage > - inline void _GD1( _TImage* image1, _TImage* image2 ); - }; - -} // ecapseman - -#endif // __cpPluginsITKBinaryFunctorFilters__BinaryArithmeticImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.cxx b/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.cxx deleted file mode 100644 index 3202b74..0000000 --- a/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.cxx +++ /dev/null @@ -1,74 +0,0 @@ -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKBinaryFunctorFilters::BinaryBooleanImageFilter:: -BinaryBooleanImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input1", true, false ); - this->_ConfigureInput< _TImage >( "Input2", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - std::vector< std::string > choices; - choices.push_back( "And" ); - choices.push_back( "Or" ); - choices.push_back( "Xor" ); - this->m_Parameters.ConfigureAsChoices( "Operator", choices ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKBinaryFunctorFilters::BinaryBooleanImageFilter:: -~BinaryBooleanImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKBinaryFunctorFilters::BinaryBooleanImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input1" ); - cpPlugins_Demangle_Image_IntPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKBinaryFunctorFilters::BinaryBooleanImageFilter:: -_GD0( _TImage* image1 ) -{ - typedef itk::AndImageFilter< _TImage, _TImage > _TAnd; - typedef itk::OrImageFilter< _TImage, _TImage > _TOr; - typedef itk::XorImageFilter< _TImage, _TImage > _TXor; - - auto image2 = this->GetInputData< _TImage >( "Input2" ); - if( image2 == NULL ) - this->_Error( "Incompatible second input image." ); - std::string op = this->m_Parameters.GetSelectedChoice( "Operator" ); - if ( op == "And" ) this->_GD1< _TAnd, _TImage >( image1, image2 ); - else if( op == "Or" ) this->_GD1< _TOr, _TImage >( image1, image2 ); - else if( op == "Xor" ) this->_GD1< _TXor, _TImage >( image1, image2 ); -} - -// ------------------------------------------------------------------------- -template< class _TFilter, class _TImage > -void cpPluginsITKBinaryFunctorFilters::BinaryBooleanImageFilter:: -_GD1( _TImage* image1, _TImage* image2 ) -{ - // Configure filter - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput1( image1 ); - filter->SetInput2( image2 ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.h b/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.h deleted file mode 100644 index 439e178..0000000 --- a/plugins/ITKBinaryFunctorFilters/BinaryBooleanImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKBinaryFunctorFilters__BinaryBooleanImageFilter__h__ -#define __cpPluginsITKBinaryFunctorFilters__BinaryBooleanImageFilter__h__ - -#include -#include - -namespace cpPluginsITKBinaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKBinaryFunctorFilters_EXPORT BinaryBooleanImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryBooleanImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageBooleanFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image1 ); - - template< class _TFilter, class _TImage > - inline void _GD1( _TImage* image1, _TImage* image2 ); - }; - -} // ecapseman - -#endif // __cpPluginsITKBinaryFunctorFilters__BinaryBooleanImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKBinaryFunctorFilters/ITKBinaryFunctorFilters.i b/plugins/ITKBinaryFunctorFilters/ITKBinaryFunctorFilters.i deleted file mode 100644 index d9d98bb..0000000 --- a/plugins/ITKBinaryFunctorFilters/ITKBinaryFunctorFilters.i +++ /dev/null @@ -1,17 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define all_ints=#int_types#;#uint_types# -define a_filters=Add;Subtract;Multiply;Divide;DivideOrZeroOut;Pow -define a_functor=Add2;Sub2;Mult;Div;DivideOrZeroOut;Pow -define b_filters=And;Or;Xor -define b_functor=AND;OR;XOR - -tinclude itkBinaryFunctorImageFilter:h|hxx -cinclude itk#a_filters#ImageFilter.h -cinclude itk#b_filters#ImageFilter.h - -instances itk::BinaryFunctorImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# >, itk::Functor::#a_functor#< #scalar_types#, #scalar_types#, #scalar_types# > > - -instances itk::BinaryFunctorImageFilter< itk::Image< #all_ints#, #pdims# >, itk::Image< #all_ints#, #pdims# >, itk::Image< #all_ints#, #pdims# >, itk::Functor::#b_functor#< #all_ints#, #all_ints#, #all_ints# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.cxx b/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.cxx deleted file mode 100644 index 0cb9711..0000000 --- a/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.cxx +++ /dev/null @@ -1,71 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKDistanceMapFilters::BinaryContourImageFilter:: -BinaryContourImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "BackgroundValue", 0 ); - this->m_Parameters.ConfigureAsReal( "ForegroundValue", 1 ); - this->m_Parameters.ConfigureAsBool( "FullyConnected", false ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKDistanceMapFilters::BinaryContourImageFilter:: -~BinaryContourImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKDistanceMapFilters::BinaryContourImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_VisualDims_1( o, _GD0 ) - this->_Error( "Invalid input image dimension." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKDistanceMapFilters::BinaryContourImageFilter:: -_GD0( _TImage* image ) -{ - cpPlugins_Demangle_Image_ScalarPixels_1( image, _GD1, _TImage::ImageDimension ) - this->_Error( "Invalid input image pixel type." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKDistanceMapFilters::BinaryContourImageFilter:: -_GD1( _TImage* image ) -{ - typedef - itk::BinaryContourImageFilter< _TImage, _TImage > - _TFilter; - - // Get parameters - double b = this->m_Parameters.GetReal( "BackgroundValue" ); - double f = this->m_Parameters.GetReal( "ForegroundValue" ); - double c = this->m_Parameters.GetBool( "FullyConnected" ); - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetBackgroundValue( ( typename _TImage::PixelType )( b ) ); - filter->SetForegroundValue( ( typename _TImage::PixelType )( f ) ); - filter->SetFullyConnected( c ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.h b/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.h deleted file mode 100644 index 8e16c99..0000000 --- a/plugins/ITKDistanceMapFilters/BinaryContourImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKDistanceMapFilters__BinaryContourImageFilter__h__ -#define __cpPluginsITKDistanceMapFilters__BinaryContourImageFilter__h__ - -#include -#include - -namespace cpPluginsITKDistanceMapFilters -{ - /** - */ - class cpPlugins_ITKDistanceMapFilters_EXPORT BinaryContourImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryContourImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageDistanceMaps - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKDistanceMapFilters__BinaryContourImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKDistanceMapFilters/ITKDistanceMapFilters.i b/plugins/ITKDistanceMapFilters/ITKDistanceMapFilters.i deleted file mode 100644 index 6a703ad..0000000 --- a/plugins/ITKDistanceMapFilters/ITKDistanceMapFilters.i +++ /dev/null @@ -1,15 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkImageRegionConstIterator:h|h -tinclude itkImageRegionIterator:h|h -tinclude itkProgressReporter:h|h - -tinclude itkBinaryContourImageFilter:h|hxx -instances itk::BinaryContourImageFilter< itk::Image< #scalar_types#, #vdims# >, itk::Image< #scalar_types#, #vdims# > > - -define filters=SignedMaurerDistanceMapImageFilter -** ;DanielssonDistanceMapImageFilter;SignedDanielssonDistanceMapImageFilter -tinclude itk#filters#:h|hxx -instances itk::#filters#< itk::Image< #scalar_types#, #vdims# >, itk::Image< #real_types#, #vdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.cxx b/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.cxx deleted file mode 100644 index b92b881..0000000 --- a/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.cxx +++ /dev/null @@ -1,82 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKDistanceMapFilters::SignedMaurerDistanceMapImageFilter:: -SignedMaurerDistanceMapImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "BackgroundValue", 0 ); - this->m_Parameters.ConfigureAsBool( "InsideIsPositive", true ); - this->m_Parameters.ConfigureAsBool( "SquaredDistance", false ); - this->m_Parameters.ConfigureAsBool( "UseImageSpacing", true ); - - std::vector< std::string > choices; - choices.push_back( "float" ); - choices.push_back( "double" ); - this->m_Parameters.ConfigureAsChoices( "OutputResolution", choices ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKDistanceMapFilters::SignedMaurerDistanceMapImageFilter:: -~SignedMaurerDistanceMapImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKDistanceMapFilters::SignedMaurerDistanceMapImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_VisualDims_1( o, _GD0 ) - this->_Error( "Invalid input image dimension." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKDistanceMapFilters::SignedMaurerDistanceMapImageFilter:: -_GD0( _TImage* image ) -{ - std::string out_res = - this->m_Parameters.GetSelectedChoice( "OutputResolution" ); - if( out_res == "float" ) this->_GD1< _TImage, float >( image ); - if( out_res == "double" ) this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKDistanceMapFilters::SignedMaurerDistanceMapImageFilter:: -_GD1( _TImage* image ) -{ - typedef itk::Image< _TScalar, _TImage::ImageDimension > _TDMap; - typedef - itk::SignedMaurerDistanceMapImageFilter< _TImage, _TDMap > - _TFilter; - - // Get parameters - double bv = this->m_Parameters.GetReal( "BackgroundValue" ); - bool pi = this->m_Parameters.GetBool( "InsideIsPositive" ); - bool sd = this->m_Parameters.GetBool( "SquaredDistance" ); - bool us = this->m_Parameters.GetBool( "UseImageSpacing" ); - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetBackgroundValue( ( typename _TImage::PixelType )( bv ) ); - filter->SetInsideIsPositive( pi ); - filter->SetSquaredDistance( sd ); - filter->SetUseImageSpacing( us ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.h b/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.h deleted file mode 100644 index 825c09b..0000000 --- a/plugins/ITKDistanceMapFilters/SignedMaurerDistanceMapImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKDistanceMapFilters__SignedMaurerDistanceMapImageFilter__h__ -#define __cpPluginsITKDistanceMapFilters__SignedMaurerDistanceMapImageFilter__h__ - -#include -#include - -namespace cpPluginsITKDistanceMapFilters -{ - /** - */ - class cpPlugins_ITKDistanceMapFilters_EXPORT SignedMaurerDistanceMapImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SignedMaurerDistanceMapImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageDistanceMaps - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKDistanceMapFilters__SignedMaurerDistanceMapImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKFiniteDifference/ITKFiniteDifference.i b/plugins/ITKFiniteDifference/ITKFiniteDifference.i deleted file mode 100644 index 1db9b6a..0000000 --- a/plugins/ITKFiniteDifference/ITKFiniteDifference.i +++ /dev/null @@ -1,15 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define base=FiniteDifferenceImageFilter;DenseFiniteDifferenceImageFilter -define functions=FiniteDifferenceFunction - -define i_reals=#real_types# -define o_reals=#real_types# - -tinclude itk#functions#:h|hxx -tinclude itk#base#:h|hxx - -instances itk::#functions#< itk::Image< #scalar_types#, #pdims# > > -instances itk::#base#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #o_reals#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesReader.cxx b/plugins/ITKIO/DicomSeriesReader.cxx deleted file mode 100644 index 18ec6f0..0000000 --- a/plugins/ITKIO/DicomSeriesReader.cxx +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include - -#ifdef cpPlugins_QT4 - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesReaderQDialog:: -DicomSeriesReaderQDialog( QWidget* parent ) - : QDialog( parent ), - m_UI( new Ui::DicomSeriesReaderQDialog ), - m_ProcessObject( NULL ) -{ - this->m_UI->setupUi( this ); - this->connect( - this, SIGNAL( accepted( ) ), this, SLOT( _dlg_Accepted( ) ) - ); - this->setWindowTitle( "Open DICOM series" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesReaderQDialog:: -~DicomSeriesReaderQDialog( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::DicomSeriesReaderQDialog:: -setProcessObject( cpPlugins::Pipeline::ProcessObject* obj ) -{ - if( obj == NULL ) - return; - this->m_ProcessObject = obj; - auto param = this->m_ProcessObject->GetParameters( ); - auto files = param->GetOpenFileNameList( "FileNames" ); - if( files.size( ) > 0 ) - { - QFileInfo info( files[ 0 ].c_str( ) ); - this->m_UI->Selector->setStartDir( info.canonicalPath( ) ); - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::DicomSeriesReaderQDialog:: -_dlg_Accepted( ) -{ - if( this->m_ProcessObject != NULL ) - { - auto param = this->m_ProcessObject->GetParameters( ); - auto files = this->m_UI->Selector->selectedFilenames( ); - param->ClearOpenFileNameList( "FileNames" ); - for( auto fIt = files->begin( ); fIt != files->end( ); ++fIt ) - param->AddToOpenFileNameList( "FileNames", *fIt ); - - } // fi -} - -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsITKIO::DicomSeriesReader:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - DicomSeriesReaderQDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new DicomSeriesReaderQDialog( ); - dlg->setProcessObject( this ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesReader:: -DicomSeriesReader( ) - : Superclass( ) -{ -} -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesReader:: -~DicomSeriesReader( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::DicomSeriesReader:: -_GenerateData( ) -{ - this->Superclass::_GenerateData( ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesReader.h b/plugins/ITKIO/DicomSeriesReader.h deleted file mode 100644 index b1419d3..0000000 --- a/plugins/ITKIO/DicomSeriesReader.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef __cpPluginsITKIO__DicomSeriesReader__h__ -#define __cpPluginsITKIO__DicomSeriesReader__h__ - -#include - -namespace cpPluginsITKIO -{ - /** - */ - class cpPlugins_ITKIO_EXPORT DicomSeriesReader - : public ImageReader - { - cpPluginsObject( DicomSeriesReader, ImageReader, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - }; - -} // ecapseman - -#endif // __cpPluginsITKIO__DicomSeriesReader__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesReaderQDialog.h b/plugins/ITKIO/DicomSeriesReaderQDialog.h deleted file mode 100644 index 3c17e3a..0000000 --- a/plugins/ITKIO/DicomSeriesReaderQDialog.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef __cpPluginsITKIO__DicomSeriesreaderQDialog__h__ -#define __cpPluginsITKIO__DicomSeriesreaderQDialog__h__ - -#include - -#ifdef cpPlugins_QT4 - -#include -#include - -namespace cpPlugins { namespace Pipeline { class ProcessObject; } } -namespace Ui { class DicomSeriesReaderQDialog; } - -namespace cpPluginsITKIO -{ - /** - */ - class DicomSeriesReaderQDialog - : public QDialog - { - Q_OBJECT; - public: - DicomSeriesReaderQDialog( QWidget* parent = 0 ); - virtual ~DicomSeriesReaderQDialog( ); - void setProcessObject( cpPlugins::Pipeline::ProcessObject* obj ); - - protected slots: - void _dlg_Accepted( ); - - protected: - Ui::DicomSeriesReaderQDialog* m_UI; - cpPlugins::Pipeline::ProcessObject* m_ProcessObject; - }; - -} // ecapseman - -#endif // cpPlugins_QT4 - -#endif // __cpPluginsITKIO__DicomSeriesreaderQDialog__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesReaderQDialog.ui b/plugins/ITKIO/DicomSeriesReaderQDialog.ui deleted file mode 100644 index 0ab2c2e..0000000 --- a/plugins/ITKIO/DicomSeriesReaderQDialog.ui +++ /dev/null @@ -1,81 +0,0 @@ - - - DicomSeriesReaderQDialog - - - - 0 - 0 - 511 - 335 - - - - - 511 - 335 - - - - Dialog - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - cpPluginsITKIO::DicomSeriesSelectorWidget - QWidget -
ITKIO/DicomSeriesSelectorWidget.h
- 1 -
-
- - - - ButtonBox - accepted() - DicomSeriesReaderQDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - ButtonBox - rejected() - DicomSeriesReaderQDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - -
diff --git a/plugins/ITKIO/DicomSeriesSelectorWidget.cxx b/plugins/ITKIO/DicomSeriesSelectorWidget.cxx deleted file mode 100644 index 98954d4..0000000 --- a/plugins/ITKIO/DicomSeriesSelectorWidget.cxx +++ /dev/null @@ -1,182 +0,0 @@ -#include - -#ifdef cpPlugins_QT4 - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesSelectorWidget:: -DicomSeriesSelectorWidget( QWidget* parent ) - : QWidget( parent ), - m_UI( new Ui::DicomSeriesSelectorWidget ) -{ - this->m_UI->setupUi( this ); - this->setStartDir( ".", false ); - this->connect( - this->m_UI->ChooseButton, SIGNAL( clicked( ) ), - this, SLOT( _Choose( ) ) - ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::DicomSeriesSelectorWidget:: -~DicomSeriesSelectorWidget( ) -{ - delete this->m_UI; -} - -// ------------------------------------------------------------------------- -QString cpPluginsITKIO::DicomSeriesSelectorWidget:: -startDir( ) const -{ - return( this->m_UI->Directory->text( ) ); -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::DicomSeriesSelectorWidget:: -setStartDir( const QString& dir, bool build ) -{ - this->m_Series.clear( ); - - this->m_UI->Directory->setText( dir ); - if( !build ) - return; - - // Process subdirs - QApplication::setOverrideCursor( Qt::WaitCursor ); - - this->m_UI->Series->clear( ); - this->m_UI->Series->setColumnCount( 3 ); - QStringList labels; - labels << "Images count" << "Series UID" << "Series path"; - this->m_UI->Series->setHorizontalHeaderLabels( labels ); - - std::string main_dir_name = dir.toStdString( ); - std::queue< std::string > q; - q.push( main_dir_name ); - while( !( q.empty( ) ) ) - { - std::string dir_name = q.front( ); - q.pop( ); - - // Update queue - QDir dir( dir_name.c_str( ) ); - QFileInfoList contents = dir.entryInfoList( ); - QFileInfoList::const_iterator i = contents.begin( ); - std::set< std::string > files; - for( ; i != contents.end( ); ++i ) - { - if( i->isDir( ) ) - { - std::string new_dir_name = i->absoluteFilePath( ).toStdString( ); - if( new_dir_name.size( ) > dir_name.size( ) ) - q.push( new_dir_name ); - } - else - files.insert( i->absoluteFilePath( ).toStdString( ) ); - - } // rof - - if( files.size( ) > 0 ) - { - this->m_GDCMHelper.Clear( ); - this->m_GDCMHelper.SetUseSeriesDetails( true ); - this->m_GDCMHelper.SetLoadMode( 0 ); - this->m_GDCMHelper.AddRestriction( "0008|0021" ); - this->m_GDCMHelper.SetFileNames( files.begin( ), files.end( ) ); - - gdcm::FileList* flist = - this->m_GDCMHelper.GetFirstSingleSerieUIDFileSet( ); - while( flist != NULL ) - { - if( flist->size( ) > 0 ) - { - this->m_GDCMHelper.OrderFileList( flist ); - gdcm::File* file = ( *flist )[ 0 ]; - std::string id = - this->m_GDCMHelper.CreateUniqueSeriesIdentifier( file ).c_str( ); - - gdcm::FileList::iterator it; - for( it = flist->begin( ); it != flist->end( ); ++it ) - if( *it != NULL ) - this->m_Series[ id ].push_back( ( *it )->filename ); - - } // fi - flist = this->m_GDCMHelper.GetNextSingleSerieUIDFileSet( ); - - } // elihw - - } // fi - - } // elihw - - // Show series - for( auto sIt = this->m_Series.begin( ); sIt != this->m_Series.end( ); ++sIt ) - { - if( sIt->second.size( ) > 0 ) - { - QFileInfo fdir( sIt->second[ 0 ].c_str( ) ); - - unsigned long rows = this->m_UI->Series->rowCount( ); - this->m_UI->Series->insertRow( rows ); - std::stringstream str_count; - str_count << sIt->second.size( ); - QTableWidgetItem* count_item = - new QTableWidgetItem( str_count.str( ).c_str( ) ); - QTableWidgetItem* uid_item = - new QTableWidgetItem( sIt->first.c_str( ) ); - QTableWidgetItem* dir_item = - new QTableWidgetItem( fdir.dir( ).canonicalPath( ) ); - count_item->setFlags( count_item->flags( ) & ~Qt::ItemIsEditable ); - uid_item->setFlags( uid_item->flags( ) & ~Qt::ItemIsEditable ); - dir_item->setFlags( dir_item->flags( ) & ~Qt::ItemIsEditable ); - this->m_UI->Series->setItem( rows, 0, count_item ); - this->m_UI->Series->setItem( rows, 1, uid_item ); - this->m_UI->Series->setItem( rows, 2, dir_item ); - - } // fi - - } // rof - - // Restore cursor - QApplication::restoreOverrideCursor( ); -} - -// ------------------------------------------------------------------------- -std::vector< std::string >* cpPluginsITKIO::DicomSeriesSelectorWidget:: -selectedFilenames( ) -{ - auto items = this->m_UI->Series->selectedItems( ); - if( items.size( ) > 0 ) - { - std::string uid = - this->m_UI->Series-> - item( items[ 0 ]->row( ), 1 )->text( ).toStdString( ); - auto sIt = this->m_Series.find( uid ); - if( sIt != this->m_Series.end( ) ) - return( &( sIt->second ) ); - - } // fi - return( NULL ); -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::DicomSeriesSelectorWidget:: -_Choose( ) -{ - QString qdir = - QFileDialog::getExistingDirectory( - this, tr( "Open Directory" ), - this->startDir( ), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks - ); - if( qdir.toStdString( ) != "" ) - this->setStartDir( qdir ); -} - -#endif // cpPlugins_QT4 - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesSelectorWidget.h b/plugins/ITKIO/DicomSeriesSelectorWidget.h deleted file mode 100644 index 3ac2fbb..0000000 --- a/plugins/ITKIO/DicomSeriesSelectorWidget.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef __cpPluginsITKIO__DicomSeriesSelectorWidget__H__ -#define __cpPluginsITKIO__DicomSeriesSelectorWidget__H__ - -#include -#include - -#ifdef cpPlugins_QT4 - -#include -#include - -// ------------------------------------------------------------------------- -namespace Ui -{ - class DicomSeriesSelectorWidget; -} - -// ------------------------------------------------------------------------- -namespace cpPluginsITKIO -{ - /** - */ - class cpPlugins_ITKIO_EXPORT DicomSeriesSelectorWidget - : public QWidget - { - Q_OBJECT; - - public: - typedef DicomSeriesSelectorWidget Self; - - protected: - /** - */ - class _GDCMSerieHelper - : public gdcm::SerieHelper - { - public: - _GDCMSerieHelper( ) - { - } - virtual ~_GDCMSerieHelper( ) - { - } - template< class _TIt > - void SetFileNames( _TIt b, _TIt e ) - { - for( _TIt i = b; i != e; ++i ) - this->AddFileName( *i ); - } - }; - - public: - explicit DicomSeriesSelectorWidget( QWidget* parent = 0 ); - virtual ~DicomSeriesSelectorWidget( ); - - QString startDir( ) const; - void setStartDir( const QString& dir, bool build = true ); - - std::vector< std::string >* selectedFilenames( ); - - protected slots: - void _Choose( ); - - protected: - Ui::DicomSeriesSelectorWidget* m_UI; - _GDCMSerieHelper m_GDCMHelper; - std::map< std::string, std::vector< std::string > > m_Series; - }; - -} // ecapseman - -#endif // cpPlugins_QT4 - -#endif // __cpPluginsITKIO__DicomSeriesSelectorWidget__H__ - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/DicomSeriesSelectorWidget.ui b/plugins/ITKIO/DicomSeriesSelectorWidget.ui deleted file mode 100644 index d3b648f..0000000 --- a/plugins/ITKIO/DicomSeriesSelectorWidget.ui +++ /dev/null @@ -1,89 +0,0 @@ - - - DicomSeriesSelectorWidget - - - - 0 - 0 - 358 - 299 - - - - Form - - - - 1 - - - 1 - - - - - - - - 101 - 14 - - - - - 101 - 14 - - - - DICOM directory: - - - - - - - true - - - true - - - - - - - - 25 - 25 - - - - - 25 - 25 - - - - ... - - - - - - - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - - - - - - \ No newline at end of file diff --git a/plugins/ITKIO/ITKIO.i b/plugins/ITKIO/ITKIO.i deleted file mode 100644 index 372512e..0000000 --- a/plugins/ITKIO/ITKIO.i +++ /dev/null @@ -1,28 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION -header #define ITKIOImageBase_HIDDEN - -define color_pixels=RGBPixel;RGBAPixel -define vector_pixels=CovariantVector;Point;Vector;SymmetricSecondRankTensor -define matrices=Matrix -define pixels=#scalar_types#;itk::#color_pixels#< #scalar_types# >;std::complex< #real_types# > - -cinclude complex -cinclude itkImage.h -cinclude itk#color_pixels#.h -cinclude itkFixedArray.h -cinclude itk#vector_pixels#.h -cinclude itk#matrices#.h -cinclude itkDiffusionTensor3D.h -cinclude itkConvertPixelBuffer.hxx - -define io=ImageFileReader;ImageSeriesReader;ImageFileWriter - -tinclude itk#io#:h|hxx -instances itk::#io#< itk::Image< #pixels#, #pdims# > > -instances itk::#io#< itk::Image< itk::FixedArray< #scalar_types#, #pdims# >, #pdims# > > -instances itk::#io#< itk::Image< itk::#vector_pixels#< #real_types#, #pdims# >, #pdims# > > -instances itk::#io#< itk::Image< itk::#matrices#< #real_types#, #pdims#, #pdims# >, #pdims# > > -instances itk::#io#< itk::Image< itk::Offset< #pdims# >, #pdims# > > -instances itk::#io#< itk::Image< itk::DiffusionTensor3D< #real_types# >, 3 > > - -** eof - $RCSfile$ diff --git a/plugins/ITKIO/ImageReader.cxx b/plugins/ITKIO/ImageReader.cxx deleted file mode 100644 index 90b032f..0000000 --- a/plugins/ITKIO/ImageReader.cxx +++ /dev/null @@ -1,269 +0,0 @@ -#include -#include -#include - -#define ITKIOImageBase_HIDDEN -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsITKIO::ImageReader:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::OpenFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::OpenFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileNames" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::ImageReader:: -ImageReader( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - this->m_Parameters.Clear( ); - this->m_Parameters.ConfigureAsOpenFileNameList( "FileNames" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileNames", - "Image files (*.bmp *.png *.jpg *.jpeg *.dcm *.mhd *.nhdr *.nrrd *.tiff)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::ImageReader:: -~ImageReader( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::ImageReader:: -_GenerateData( ) -{ - // Get filenames - auto fnames = this->m_Parameters.GetOpenFileNameList( "FileNames" ); - std::string fname = ""; - if( fnames.size( ) > 1 ) - { - std::stringstream fname_str; - fname_str << fnames[ 0 ] << cpPlugins_PATH_SEPARATOR << fnames[ 1 ]; - fname = fname_str.str( ); - } - else if( fnames.size( ) == 1 ) - fname = fnames[ 0 ]; - - if( fname != "" ) - { - // Guess image properties - itk::ImageIOBase::Pointer io = - itk::ImageIOFactory::CreateImageIO( - fname.c_str( ), itk::ImageIOFactory::ReadMode - ); - if( io.IsNotNull( ) ) - { - io->SetFileName( fname ); - io->ReadImageInformation( ); - bool success = false; - unsigned int dim = io->GetNumberOfDimensions( ); -#ifdef cpPlugins_PROCESS_DIMS_1 - if( dim == 1 ) success = this->_GD0< 1 >( io ); -#endif // cpPlugins_PROCESS_DIMS_1 -#ifdef cpPlugins_PROCESS_DIMS_2 - if( dim == 2 ) success = this->_GD0< 2 >( io ); -#endif // cpPlugins_PROCESS_DIMS_2 -#ifdef cpPlugins_PROCESS_DIMS_3 - if( dim == 3 ) success = this->_GD0< 3 >( io ); -#endif // cpPlugins_PROCESS_DIMS_3 -#ifdef cpPlugins_PROCESS_DIMS_4 - if( dim == 4 ) success = this->_GD0< 4 >( io ); -#endif // cpPlugins_PROCESS_DIMS_4 - if( !success ) - this->_Error( "Image dimension not supported." ); - } - else - this->_Error( - std::string( "Could not create an ImageIO for \"" ) + - fnames[ 0 ] + - std::string( "\"" ) - ); - } - else - this->_Error( "No image(s) given" ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _Dim > -bool cpPluginsITKIO::ImageReader:: -_GD0( itk::ImageIOBase* io ) -{ - typedef unsigned char uchar; - typedef unsigned short ushort; - typedef unsigned int uint; - typedef unsigned long ulong; - - itk::ImageIOBase::IOComponentType ct = io->GetComponentType( ); - itk::ImageIOBase::IOPixelType pt = io->GetPixelType( ); - - bool success = false; - if( pt == itk::ImageIOBase::SCALAR ) - { - if( ct == itk::ImageIOBase::CHAR ) success = this->_GD1< char, _Dim >( io ); - if( ct == itk::ImageIOBase::UCHAR ) success = this->_GD1< uchar, _Dim >( io ); - if( ct == itk::ImageIOBase::SHORT ) success = this->_GD1< short, _Dim >( io ); - if( ct == itk::ImageIOBase::USHORT ) success = this->_GD1< ushort, _Dim >( io ); - if( ct == itk::ImageIOBase::INT ) success = this->_GD1< int, _Dim >( io ); - if( ct == itk::ImageIOBase::UINT ) success = this->_GD1< uint, _Dim >( io ); - if( ct == itk::ImageIOBase::LONG ) success = this->_GD1< long, _Dim >( io ); - if( ct == itk::ImageIOBase::ULONG ) success = this->_GD1< ulong, _Dim >( io ); - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< float, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< double, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::RGB ) - { - if( ct == itk::ImageIOBase::CHAR ) success = this->_GD1< itk::RGBPixel< char >, _Dim >( io ); - if( ct == itk::ImageIOBase::UCHAR ) success = this->_GD1< itk::RGBPixel< uchar >, _Dim >( io ); - if( ct == itk::ImageIOBase::SHORT ) success = this->_GD1< itk::RGBPixel< short >, _Dim >( io ); - if( ct == itk::ImageIOBase::USHORT ) success = this->_GD1< itk::RGBPixel< ushort >, _Dim >( io ); - if( ct == itk::ImageIOBase::INT ) success = this->_GD1< itk::RGBPixel< int >, _Dim >( io ); - if( ct == itk::ImageIOBase::UINT ) success = this->_GD1< itk::RGBPixel< uint >, _Dim >( io ); - if( ct == itk::ImageIOBase::LONG ) success = this->_GD1< itk::RGBPixel< long >, _Dim >( io ); - if( ct == itk::ImageIOBase::ULONG ) success = this->_GD1< itk::RGBPixel< ulong >, _Dim >( io ); - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::RGBPixel< float >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::RGBPixel< double >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::RGBA ) - { - if( ct == itk::ImageIOBase::CHAR ) success = this->_GD1< itk::RGBAPixel< char >, _Dim >( io ); - if( ct == itk::ImageIOBase::UCHAR ) success = this->_GD1< itk::RGBAPixel< uchar >, _Dim >( io ); - if( ct == itk::ImageIOBase::SHORT ) success = this->_GD1< itk::RGBAPixel< short >, _Dim >( io ); - if( ct == itk::ImageIOBase::USHORT ) success = this->_GD1< itk::RGBAPixel< ushort >, _Dim >( io ); - if( ct == itk::ImageIOBase::INT ) success = this->_GD1< itk::RGBAPixel< int >, _Dim >( io ); - if( ct == itk::ImageIOBase::UINT ) success = this->_GD1< itk::RGBAPixel< uint >, _Dim >( io ); - if( ct == itk::ImageIOBase::LONG ) success = this->_GD1< itk::RGBAPixel< long >, _Dim >( io ); - if( ct == itk::ImageIOBase::ULONG ) success = this->_GD1< itk::RGBAPixel< ulong >, _Dim >( io ); - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::RGBAPixel< float >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::RGBAPixel< double >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::COMPLEX ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< std::complex< float >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< std::complex< double >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::COVARIANTVECTOR ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::CovariantVector< float, _Dim >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::CovariantVector< double, _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::POINT ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::Point< float, _Dim >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::Point< double, _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::VECTOR ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::Vector< float, _Dim >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::Vector< double, _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::SYMMETRICSECONDRANKTENSOR ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::SymmetricSecondRankTensor< float, _Dim >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::SymmetricSecondRankTensor< double, _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::DIFFUSIONTENSOR3D ) - { - if( _Dim == 3 ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::DiffusionTensor3D< float >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::DiffusionTensor3D< double >, _Dim >( io ); - } - else - this->_Error( "DiffusionTensor3D dimension not supported." ); - } - else if( pt == itk::ImageIOBase::MATRIX ) - { - if( ct == itk::ImageIOBase::FLOAT ) success = this->_GD1< itk::Matrix< float, _Dim, _Dim >, _Dim >( io ); - if( ct == itk::ImageIOBase::DOUBLE ) success = this->_GD1< itk::Matrix< double, _Dim, _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::OFFSET ) - { - this->_GD1< itk::Offset< _Dim >, _Dim >( io ); - } - else if( pt == itk::ImageIOBase::FIXEDARRAY ) - { - } // fi - return( success ); -} - -// ------------------------------------------------------------------------- -template< class _TPixel, unsigned int _Dim > -bool cpPluginsITKIO::ImageReader:: -_GD1( itk::ImageIOBase* io ) -{ - typedef itk::Image< _TPixel, _Dim > _TImage; - - // Get filenames - auto fnames = this->m_Parameters.GetOpenFileNameList( "FileNames" ); - if( fnames.size( ) == 1 || fnames.size( ) == 2 ) - { - std::stringstream fname_str; - if( fnames.size( ) == 1 ) - fname_str << fnames[ 0 ]; - else - fname_str << fnames[ 0 ] << cpPlugins_PATH_SEPARATOR << fnames[ 1 ]; - - auto f = this->_CreateITK< itk::ImageFileReader< _TImage > >( ); - f->SetFileName( fname_str.str( ) ); - f->SetImageIO( io ); - try - { - f->Update( ); - this->GetOutput( "Output" )->SetITK( f->GetOutput( ) ); - return( true ); - } - catch( itk::ExceptionObject& err ) - { - this->_Error( err.GetDescription( ) ); - return( false ); - - } // yrt - } - else // if( fnames.size( ) > 1 ) - { - auto f = this->_CreateITK< itk::ImageSeriesReader< _TImage > >( ); - auto i = fnames.begin( ); - std::stringstream dir; - dir << *i << cpPlugins_PATH_SEPARATOR; - i++; - for( ; i != fnames.end( ); ++i ) - f->AddFileName( dir.str( ) + *i ); - f->SetImageIO( io ); - try - { - f->Update( ); - this->GetOutput( "Output" )->SetITK( f->GetOutput( ) ); - return( true ); - } - catch( itk::ExceptionObject& err ) - { - this->_Error( err.GetDescription( ) ); - return( false ); - - } // yrt - - } // fi -} - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/ImageReader.h b/plugins/ITKIO/ImageReader.h deleted file mode 100644 index 80b8a02..0000000 --- a/plugins/ITKIO/ImageReader.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __cpPluginsITKIO__ImageReader__h__ -#define __cpPluginsITKIO__ImageReader__h__ - -#include -#include - -namespace itk { class ImageIOBase; } - -namespace cpPluginsITKIO -{ - /** - */ - class cpPlugins_ITKIO_EXPORT ImageReader - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( ImageReader, cpPlugins::Pipeline::ProcessObject, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< unsigned int _Dim > - inline bool _GD0( itk::ImageIOBase* io ); - - template< class _TPixel, unsigned int _Dim > - inline bool _GD1( itk::ImageIOBase* io ); - }; - -} // ecapseman - -#endif // __cpPluginsITKIO__ImageReader__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/ImageWriter.cxx b/plugins/ITKIO/ImageWriter.cxx deleted file mode 100644 index a40aad6..0000000 --- a/plugins/ITKIO/ImageWriter.cxx +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include - -#define ITKIOImageBase_HIDDEN -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsITKIO::ImageWriter:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::SaveFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::SaveFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::ImageWriter:: -ImageWriter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->m_Parameters.ConfigureAsSaveFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "Image files (*.bmp *.png *.jpg *.jpeg *.dcm *.mhd *.nhdr *.nrrd *.tiff)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKIO::ImageWriter:: -~ImageWriter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKIO::ImageWriter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ProcessDims_1( o, _GD0 ) - cpPlugins_Demangle_Image_DiffTensors3D_1( o, _GD1 ) - this->_Error( "Invalid input image dimension." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKIO::ImageWriter:: -_GD0( _TImage* image ) -{ - cpPlugins_Demangle_Image_ScalarPixels_1( image, _GD1, _TImage::ImageDimension ) - cpPlugins_Demangle_Image_ComplexPixels_1( image, _GD1, _TImage::ImageDimension ) - cpPlugins_Demangle_Image_ColorPixels_1( image, _GD1, _TImage::ImageDimension ) - cpPlugins_Demangle_Image_VectorPixels_1( image, _GD1, _TImage::ImageDimension ) - this->_Error( "Invalid input image pixel type." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKIO::ImageWriter:: -_GD1( _TImage* image ) -{ - typedef itk::ImageFileWriter< _TImage > _TFilter; - - auto f = this->_CreateITK< _TFilter >( ); - f->SetFileName( this->m_Parameters.GetSaveFileName( "FileName" ) ); - f->SetInput( image ); - try - { - f->Update( ); - } - catch( itk::ExceptionObject& err ) - { - this->_Error( err.GetDescription( ) ); - - } // yrt -} - -// eof - $RCSfile$ diff --git a/plugins/ITKIO/ImageWriter.h b/plugins/ITKIO/ImageWriter.h deleted file mode 100644 index 4f63885..0000000 --- a/plugins/ITKIO/ImageWriter.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef __cpPluginsITKIO__ImageWriter__h__ -#define __cpPluginsITKIO__ImageWriter__h__ - -#include -#include - -namespace cpPluginsITKIO -{ - /** - */ - class cpPlugins_ITKIO_EXPORT ImageWriter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( ImageWriter, cpPlugins::Pipeline::ProcessObject, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKIO__ImageWriter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/CastImageFilter.cxx b/plugins/ITKImageGenericFilters_1/CastImageFilter.cxx deleted file mode 100644 index a7cf31b..0000000 --- a/plugins/ITKImageGenericFilters_1/CastImageFilter.cxx +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::CastImageFilter:: -CastImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - this->m_Parameters.ConfigureAsScalarTypesChoices( "OutputPixelType" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::CastImageFilter:: -~CastImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageGenericFilters_1::CastImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TInput > -void cpPluginsITKImageGenericFilters_1::CastImageFilter:: -_GD0( _TInput* input ) -{ - std::string o_type = - this->m_Parameters.GetSelectedChoice( "OutputPixelType" ); - if( o_type == "char" ) this->_GD1< _TInput, char >( input ); - else if( o_type == "short" ) this->_GD1< _TInput, short >( input ); - else if( o_type == "int" ) this->_GD1< _TInput, int >( input ); - else if( o_type == "long" ) this->_GD1< _TInput, long >( input ); - else if( o_type == "uchar" ) this->_GD1< _TInput, unsigned char >( input ); - else if( o_type == "ushort" ) this->_GD1< _TInput, unsigned short >( input ); - else if( o_type == "uint" ) this->_GD1< _TInput, unsigned int >( input ); - else if( o_type == "ulong" ) this->_GD1< _TInput, unsigned long >( input ); - else if( o_type == "float" ) this->_GD1< _TInput, float >( input ); - else if( o_type == "double" ) this->_GD1< _TInput, double >( input ); -} - -// ------------------------------------------------------------------------- -template< class _TInput, class _TOutputPixel > -void cpPluginsITKImageGenericFilters_1::CastImageFilter:: -_GD1( _TInput* input ) -{ - typedef itk::Image< _TOutputPixel, _TInput::ImageDimension > _TOutput; - typedef itk::CastImageFilter< _TInput, _TOutput > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( input ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/CastImageFilter.h b/plugins/ITKImageGenericFilters_1/CastImageFilter.h deleted file mode 100644 index 973e0d9..0000000 --- a/plugins/ITKImageGenericFilters_1/CastImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKImageGenericFilters_1__CastImageFilter__h__ -#define __cpPluginsITKImageGenericFilters_1__CastImageFilter__h__ - -#include -#include - -namespace cpPluginsITKImageGenericFilters_1 -{ - /** - */ - class cpPlugins_ITKImageGenericFilters_1_EXPORT CastImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - CastImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageFilters - ); - - protected: - template< class _TInput > - inline void _GD0( _TInput* input ); - - template< class _TInput, class _TOutputPixel > - inline void _GD1( _TInput* input ); - }; - -} // ecapseman - -#endif // __cpPluginsITKImageGenericFilters_1__CastImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/ITKImageGenericFilters_1.i b/plugins/ITKImageGenericFilters_1/ITKImageGenericFilters_1.i deleted file mode 100644 index 8c62830..0000000 --- a/plugins/ITKImageGenericFilters_1/ITKImageGenericFilters_1.i +++ /dev/null @@ -1,21 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkUnaryFunctorImageFilter:h|hxx - -define filters_1=CastImageFilter;ShiftScaleImageFilter -define i_scalars=#scalar_types# -define o_scalars=#scalar_types# - -tinclude itk#filters_1#:h|hxx -instances itk::#filters_1#< itk::Image< #i_scalars#, #pdims# >, itk::Image< #o_scalars#, #pdims# > > - -tinclude itkRegionOfInterestImageFilter:h|hxx -instances itk::RegionOfInterestImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# > > - -tinclude itkMinimumMaximumImageCalculator:h|hxx -instances itk::MinimumMaximumImageCalculator< itk::Image< #scalar_types#, #pdims# > > - -tinclude cpExtensions/Algorithms/ImageToBoundingBoxFromThreshold:h|hxx -instances cpExtensions::Algorithms::ImageToBoundingBoxFromThreshold< itk::Image< #scalar_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.cxx b/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.cxx deleted file mode 100644 index a4e815b..0000000 --- a/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.cxx +++ /dev/null @@ -1,63 +0,0 @@ -#include -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::ImageToBoundingBoxFromThreshold:: -ImageToBoundingBoxFromThreshold( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::BoundingBox >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "LowerThreshold", 0 ); - this->m_Parameters.ConfigureAsReal( "UpperThreshold", 1 ); - this->m_Parameters.ConfigureAsUint( "PAD", 0 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::ImageToBoundingBoxFromThreshold:: -~ImageToBoundingBoxFromThreshold( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageGenericFilters_1::ImageToBoundingBoxFromThreshold:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKImageGenericFilters_1::ImageToBoundingBoxFromThreshold:: -_GD0( _TImage* image ) -{ - typedef - cpExtensions::Algorithms::ImageToBoundingBoxFromThreshold< _TImage > - _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetImage( image ); - filter->SetLowerThreshold( this->m_Parameters.GetReal( "LowerThreshold" ) ); - filter->SetUpperThreshold( this->m_Parameters.GetReal( "UpperThreshold" ) ); - filter->SetPAD( this->m_Parameters.GetUint( "PAD" ) ); - filter->Compute( ); - - // Create output - auto reg = filter->GetRegion( ); - auto bb = this->GetOutput< cpInstances::DataObjects::BoundingBox >( "Output" ); - typename _TImage::PointType p0, p1; - image->TransformIndexToPhysicalPoint( reg.GetIndex( ), p0 ); - image->TransformIndexToPhysicalPoint( reg.GetIndex( ) + reg.GetSize( ), p1 ); - bb->SetMinimum( p0 ); - bb->SetMaximum( p1 ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.h b/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.h deleted file mode 100644 index 92c8613..0000000 --- a/plugins/ITKImageGenericFilters_1/ImageToBoundingBoxFromThreshold.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKImageGenericFilters_1__ImageToBoundingBoxFromThreshold__h__ -#define __cpPluginsITKImageGenericFilters_1__ImageToBoundingBoxFromThreshold__h__ - -#include -#include - -namespace cpPluginsITKImageGenericFilters_1 -{ - /** - */ - class cpPlugins_ITKImageGenericFilters_1_EXPORT ImageToBoundingBoxFromThreshold - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - ImageToBoundingBoxFromThreshold, - cpPlugins::Pipeline::ProcessObject, - ImageFeatures - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKImageGenericFilters_1__ImageToBoundingBoxFromThreshold__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.cxx b/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.cxx deleted file mode 100644 index c30cad3..0000000 --- a/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.cxx +++ /dev/null @@ -1,120 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::MinimumMaximumImageCalculator:: -MinimumMaximumImageCalculator( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - typedef cpInstances::DataObjects::Mesh _TMesh; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TMesh >( "Maximum" ); - this->_ConfigureOutput< _TMesh >( "Minimum" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::MinimumMaximumImageCalculator:: -~MinimumMaximumImageCalculator( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageGenericFilters_1::MinimumMaximumImageCalculator:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKImageGenericFilters_1::MinimumMaximumImageCalculator:: -_GD0( _TImage* input ) -{ - typedef itk::MinimumMaximumImageCalculator< _TImage > _TFilter; - typedef typename _TImage::IndexType _TIndex; - typedef typename _TImage::PointType _TPoint; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetImage( input ); - filter->Compute( ); - - _TIndex min_idx = filter->GetIndexOfMinimum( ); - _TIndex max_idx = filter->GetIndexOfMaximum( ); - - _TPoint min_pnt, max_pnt; - input->TransformIndexToPhysicalPoint( min_idx, min_pnt ); - input->TransformIndexToPhysicalPoint( max_idx, max_pnt ); - - auto min_pd = this->GetOutputData< vtkPolyData >( "Minimum" ); - if( min_pd == NULL ) - { - auto points = vtkSmartPointer< vtkPoints >::New( ); - auto verts = vtkSmartPointer< vtkCellArray >::New( ); - auto lines = vtkSmartPointer< vtkCellArray >::New( ); - auto polys = vtkSmartPointer< vtkCellArray >::New( ); - auto strips = vtkSmartPointer< vtkCellArray >::New( ); - auto pd = vtkSmartPointer< vtkPolyData >::New( ); - pd->SetPoints( points ); - pd->SetVerts( verts ); - pd->SetLines( lines ); - pd->SetPolys( polys ); - pd->SetStrips( strips ); - - points->InsertNextPoint( 0, 0, 0 ); - verts->InsertNextCell( 1 ); - verts->InsertCellPoint( 0 ); - - this->GetOutput( "Minimum" )->SetVTK( pd ); - min_pd = this->GetOutputData< vtkPolyData >( "Minimum" ); - - } // fi - - if( _TImage::ImageDimension == 1 ) - min_pd->GetPoints( )->SetPoint( 0, min_pnt[ 0 ], 0, 0 ); - else if( _TImage::ImageDimension == 2 ) - min_pd->GetPoints( )->SetPoint( 0, min_pnt[ 0 ], min_pnt[ 1 ], 0 ); - else if( _TImage::ImageDimension > 2 ) - min_pd->GetPoints( )->SetPoint( 0, min_pnt[ 0 ], min_pnt[ 1 ], min_pnt[ 2 ] ); - - auto max_pd = this->GetOutputData< vtkPolyData >( "Maximum" ); - if( max_pd == NULL ) - { - auto points = vtkSmartPointer< vtkPoints >::New( ); - auto verts = vtkSmartPointer< vtkCellArray >::New( ); - auto lines = vtkSmartPointer< vtkCellArray >::New( ); - auto polys = vtkSmartPointer< vtkCellArray >::New( ); - auto strips = vtkSmartPointer< vtkCellArray >::New( ); - auto pd = vtkSmartPointer< vtkPolyData >::New( ); - pd->SetPoints( points ); - pd->SetVerts( verts ); - pd->SetLines( lines ); - pd->SetPolys( polys ); - pd->SetStrips( strips ); - - points->InsertNextPoint( 0, 0, 0 ); - verts->InsertNextCell( 1 ); - verts->InsertCellPoint( 0 ); - - this->GetOutput( "Maximum" )->SetVTK( pd ); - max_pd = this->GetOutputData< vtkPolyData >( "Maximum" ); - - } // fi - - if( _TImage::ImageDimension == 1 ) - max_pd->GetPoints( )->SetPoint( 0, max_pnt[ 0 ], 0, 0 ); - else if( _TImage::ImageDimension == 2 ) - max_pd->GetPoints( )->SetPoint( 0, max_pnt[ 0 ], max_pnt[ 1 ], 0 ); - else if( _TImage::ImageDimension > 2 ) - max_pd->GetPoints( )->SetPoint( 0, max_pnt[ 0 ], max_pnt[ 1 ], max_pnt[ 2 ] ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.h b/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.h deleted file mode 100644 index a52c685..0000000 --- a/plugins/ITKImageGenericFilters_1/MinimumMaximumImageCalculator.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKImageGenericFilters_1__MinimumMaximumImageCalculator__h__ -#define __cpPluginsITKImageGenericFilters_1__MinimumMaximumImageCalculator__h__ - -#include -#include - -namespace cpPluginsITKImageGenericFilters_1 -{ - /** - */ - class cpPlugins_ITKImageGenericFilters_1_EXPORT MinimumMaximumImageCalculator - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - MinimumMaximumImageCalculator, - cpPlugins::Pipeline::ProcessObject, - ImageFeatures - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* input ); - }; - -} // ecapseman - -#endif // __cpPluginsImageGenericFilters__MinimumMaximumImageCalculator__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.cxx b/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.cxx deleted file mode 100644 index 52ec23b..0000000 --- a/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.cxx +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::RegionOfInterestImageFilter:: -RegionOfInterestImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - typedef cpInstances::DataObjects::BoundingBox _TBBox; - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureInput< _TBBox >( "BoundingBox", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageGenericFilters_1::RegionOfInterestImageFilter:: -~RegionOfInterestImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageGenericFilters_1::RegionOfInterestImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKImageGenericFilters_1::RegionOfInterestImageFilter:: -_GD0( _TImage* input ) -{ - typedef cpInstances::DataObjects::BoundingBox _TBBox; - typedef itk::RegionOfInterestImageFilter< _TImage, _TImage > _TFilter; - typedef typename _TImage::IndexType _TIndex; - typedef typename _TImage::PointType _TPoint; - typedef typename _TImage::RegionType _TRegion; - typedef typename _TImage::SizeType _TSize; - - auto bb = this->GetInput< _TBBox >( "BoundingBox" ); - - _TRegion in_region = input->GetRequestedRegion( ); - _TIndex in_i0 = in_region.GetIndex( ); - _TIndex in_i1 = in_i0 + in_region.GetSize( ); - _TIndex i0, i1; - input->TransformPhysicalPointToIndex( bb->GetMinimum< _TPoint >( ), i0 ); - input->TransformPhysicalPointToIndex( bb->GetMaximum< _TPoint >( ), i1 ); - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - { - if( i0[ d ] < in_i0[ d ] ) i0[ d ] = in_i0[ d ]; - if( i1[ d ] > in_i1[ d ] ) i1[ d ] = in_i1[ d ]; - - } // rof - - _TSize size; - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - size[ d ] = i1[ d ] - i0[ d ]; - - _TRegion region; - region.SetIndex( i0 ); - region.SetSize( size ); - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( input ); - filter->SetRegionOfInterest( region ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.h b/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.h deleted file mode 100644 index 5d29887..0000000 --- a/plugins/ITKImageGenericFilters_1/RegionOfInterestImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKImageGenericFilters_1__RegionOfInterestImageFilter__h__ -#define __cpPluginsITKImageGenericFilters_1__RegionOfInterestImageFilter__h__ - -#include -#include - -namespace cpPluginsITKImageGenericFilters_1 -{ - /** - */ - class cpPlugins_ITKImageGenericFilters_1_EXPORT RegionOfInterestImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - RegionOfInterestImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* input ); - }; - -} // ecapseman - -#endif // __cpPluginsITKImageGenericFilters_1__RegionOfInterestImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.cxx b/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.cxx deleted file mode 100644 index 16c64da..0000000 --- a/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.cxx +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -BSplineInterpolateImageFunction( ) - : Superclass( ) -{ - this->m_Parameters.ConfigureAsUint( "SplineOrder", 3 ); - this->m_Parameters.ConfigureAsBool( "UseImageDirection", true ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -~BSplineInterpolateImageFunction( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -CreateInterpolator( - itk::LightObject* image, const std::string& precision_type - ) -{ - this->m_PrecisionType = precision_type; - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( image, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -_GenerateData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -_GD0( _TImage* image ) -{ - if( this->m_PrecisionType == "float" ) - this->_GD1< _TImage, float >( image ); - else if( this->m_PrecisionType == "double" ) - this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKImageInterpolators::BSplineInterpolateImageFunction:: -_GD1( _TImage* image ) -{ - typedef itk::BSplineInterpolateImageFunction< _TImage, _TScalar, _TScalar > _TFunction; - - auto function = this->_CreateITK< _TFunction >( ); - function->SetSplineOrder( this->m_Parameters.GetUint( "SplineOrder" ) ); - function->SetUseImageDirection( this->m_Parameters.GetBool( "UseImageDirection" ) ); - this->GetOutput( "Output" )->SetITK( function ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.h b/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.h deleted file mode 100644 index 79ac05e..0000000 --- a/plugins/ITKImageInterpolators/BSplineInterpolateImageFunction.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef __cpPluginsITKImageInterpolators__BSplineInterpolateImageFunction__h__ -#define __cpPluginsITKImageInterpolators__BSplineInterpolateImageFunction__h__ - -#include -#include - -namespace cpPluginsITKImageInterpolators -{ - /** - */ - class cpPlugins_ITKImageInterpolators_EXPORT BSplineInterpolateImageFunction - : public InterpolateImageFunction - { - cpPluginsObject( - BSplineInterpolateImageFunction, - InterpolateImageFunction, - ITKImageInterpolators - ); - - public: - virtual void CreateInterpolator( - itk::LightObject* image, - const std::string& precision_type - ) override; - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKImageInterpolators__BSplineInterpolateImageFunction__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/ITKImageInterpolators.i b/plugins/ITKImageInterpolators/ITKImageInterpolators.i deleted file mode 100644 index c6c5f9c..0000000 --- a/plugins/ITKImageInterpolators/ITKImageInterpolators.i +++ /dev/null @@ -1,25 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define v=FixedArray -define i_real=#real_types# -define o_real=#real_types# -define interp=Linear - -tinclude itkImageFunction:h|hxx -tinclude itk#interp#InterpolateImageFunction:h|hxx -tinclude itkVectorLinearInterpolateImageFunction:h|hxx - -cinclude itk#v#.h -cinclude itkImage.h - -instances itk::ImageFunction< itk::Image< #scalar_types#, #pdims# >, #i_real#, #o_real# > -instances itk::#interp#InterpolateImageFunction< itk::Image< #scalar_types#, #pdims# >, #real_types# > - -instances itk::VectorLinearInterpolateImageFunction< itk::Image< itk::#v#< #i_real#, #pdims# >, #pdims# >, #o_real# > - -tinclude itkBSplineDecompositionImageFilter:h|hxx -tinclude itkBSplineInterpolateImageFunction:h|hxx -instances itk::BSplineInterpolateImageFunction< itk::Image< #scalar_types#, #pdims# >, #real_types#, #real_types# > -instances itk::BSplineDecompositionImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #real_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/InterpolateImageFunction.cxx b/plugins/ITKImageInterpolators/InterpolateImageFunction.cxx deleted file mode 100644 index b58fba5..0000000 --- a/plugins/ITKImageInterpolators/InterpolateImageFunction.cxx +++ /dev/null @@ -1,39 +0,0 @@ -#include - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::InterpolateImageFunction:: -SetITK( itk::LightObject* o ) -{ - if( this->m_ITK.GetPointer( ) != o ) - this->m_ITK = o; -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::InterpolateImageFunction:: -SetVTK( vtkObjectBase* o ) -{ - if( this->m_VTK.GetPointer( ) != o ) - this->m_VTK = o; -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::InterpolateImageFunction:: -InterpolateImageFunction( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpPlugins::Pipeline::DataObject >( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::InterpolateImageFunction:: -~InterpolateImageFunction( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::InterpolateImageFunction:: -_GenerateData( ) -{ -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/InterpolateImageFunction.h b/plugins/ITKImageInterpolators/InterpolateImageFunction.h deleted file mode 100644 index ebf8f52..0000000 --- a/plugins/ITKImageInterpolators/InterpolateImageFunction.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef __cpPluginsITKImageInterpolators__InterpolateImageFunction__h__ -#define __cpPluginsITKImageInterpolators__InterpolateImageFunction__h__ - -#include -#include - -namespace cpPluginsITKImageInterpolators -{ - /** - */ - class cpPlugins_ITKImageInterpolators_EXPORT InterpolateImageFunction - : public cpPlugins::Pipeline::ProcessObject - { - public: - typedef InterpolateImageFunction Self; - typedef cpPlugins::Pipeline::ProcessObject Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer< const Self > ConstPointer; - - public: - itkTypeMacro( BaseFilter, cpPlugins::Pipeline::ProcessObject ); - cpPlugins_Id_Macro( InterpolateImageFunction, ImageInterpolators ); - - public: - virtual void SetITK( itk::LightObject* o ) override; - virtual void SetVTK( vtkObjectBase* o ) override; - - protected: - InterpolateImageFunction( ); - virtual ~InterpolateImageFunction( ); - - public: - virtual void CreateInterpolator( - itk::LightObject* image, - const std::string& precision_type - ) = 0; - - protected: - virtual void _GenerateData( ) override; - - private: - // Purposely not implemented. - InterpolateImageFunction( const Self& other ); - Self& operator=( const Self& other ); - - protected: - std::string m_PrecisionType; - }; - -} // ecapseman - -#endif // __cpPluginsITKImageInterpolators__InterpolateImageFunction__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.cxx b/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.cxx deleted file mode 100644 index 5317a29..0000000 --- a/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.cxx +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -LinearInterpolateImageFunction( ) - : Superclass( ) -{ -} - -// ------------------------------------------------------------------------- -cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -~LinearInterpolateImageFunction( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -CreateInterpolator( - itk::LightObject* image, const std::string& precision_type - ) -{ - this->m_PrecisionType = precision_type; - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( image, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -void cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -_GenerateData( ) -{ -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -_GD0( _TImage* image ) -{ - if( this->m_PrecisionType == "float" ) - this->_GD1< _TImage, float >( image ); - else if( this->m_PrecisionType == "double" ) - this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKImageInterpolators::LinearInterpolateImageFunction:: -_GD1( _TImage* image ) -{ - typedef itk::LinearInterpolateImageFunction< _TImage, _TScalar > _TFunction; - - auto function = this->_CreateITK< _TFunction >( ); - this->GetOutput( "Output" )->SetITK( function ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.h b/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.h deleted file mode 100644 index d13d4b7..0000000 --- a/plugins/ITKImageInterpolators/LinearInterpolateImageFunction.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef __cpPluginsITKImageInterpolators__LinearInterpolateImageFunction__h__ -#define __cpPluginsITKImageInterpolators__LinearInterpolateImageFunction__h__ - -#include -#include - -namespace cpPluginsITKImageInterpolators -{ - /** - */ - class cpPlugins_ITKImageInterpolators_EXPORT LinearInterpolateImageFunction - : public InterpolateImageFunction - { - cpPluginsObject( - LinearInterpolateImageFunction, - InterpolateImageFunction, - ITKImageInterpolators - ); - - public: - virtual void CreateInterpolator( - itk::LightObject* image, - const std::string& precision_type - ) override; - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKImageInterpolators__LinearInterpolateImageFunction__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKLevelSetFilters/ITKLevelSetFilters.i b/plugins/ITKLevelSetFilters/ITKLevelSetFilters.i deleted file mode 100644 index a1c4a75..0000000 --- a/plugins/ITKLevelSetFilters/ITKLevelSetFilters.i +++ /dev/null @@ -1,28 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define base=ZeroCrossingImageFilter;SparseFieldLevelSetImageFilter -define filters=SegmentationLevelSetImageFilter;ThresholdSegmentationLevelSetImageFilter;LaplacianSegmentationLevelSetImageFilter -define functions=LevelSetFunction -define ls_functions=SegmentationLevelSetFunction;ThresholdSegmentationLevelSetFunction;LaplacianSegmentationLevelSetFunction - -define i_reals=#real_types# -define o_reals=#real_types# - -tinclude itk#functions#:h|hxx -tinclude itk#ls_functions#:h|hxx -tinclude itk#base#:h|hxx -tinclude itk#filters#:h|hxx -tinclude itkSparseFieldLayer:h|hxx -tinclude itkObjectStore:h|hxx - -cinclude itkLinearInterpolateImageFunction.hxx - -instances itk::SparseFieldLayer< itk::SparseFieldLevelSetNode< itk::Index< #pdims# > > > -instances itk::ObjectStore< itk::SparseFieldLevelSetNode< itk::Index< #pdims# > > > - -instances itk::#functions#< itk::Image< #i_reals#, #pdims# > > -instances itk::#ls_functions#< itk::Image< #i_reals#, #pdims# >, itk::Image< #o_reals#, #pdims# > > -instances itk::#base#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #i_reals#, #pdims# > > -instances itk::#filters#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #i_reals#, #pdims# >, #o_reals# > - -** eof - $RCSfile$ diff --git a/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.cxx b/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.cxx deleted file mode 100644 index c45c75a..0000000 --- a/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.cxx +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKLevelSetFilters::LaplacianSegmentationLevelSetImageFilter:: -LaplacianSegmentationLevelSetImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Feature", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "PropagationScaling", 1 ); - this->m_Parameters.ConfigureAsReal( "CurvatureScaling", 1 ); - this->m_Parameters.ConfigureAsReal( "MaximumRMSError", 0.02 ); - this->m_Parameters.ConfigureAsReal( "IsoSurfaceValue", 0 ); - this->m_Parameters.ConfigureAsUint( "NumberOfIterations", 100 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKLevelSetFilters::LaplacianSegmentationLevelSetImageFilter:: -~LaplacianSegmentationLevelSetImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKLevelSetFilters::LaplacianSegmentationLevelSetImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_RealPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKLevelSetFilters::LaplacianSegmentationLevelSetImageFilter:: -_GD0( _TImage* image ) -{ - auto f = this->GetInputData( "Feature" ); - cpPlugins_Demangle_Image_RealPixels_2( f, _GD1, _TImage::ImageDimension, image ) - this->_Error( "Invalid feature image." ); -} - -// ------------------------------------------------------------------------- -template< class _TFeature, class _TImage > -void cpPluginsITKLevelSetFilters::LaplacianSegmentationLevelSetImageFilter:: -_GD1( _TFeature* feature, _TImage* image ) -{ - typedef typename _TFeature::PixelType _TScalar; - typedef - itk::LaplacianSegmentationLevelSetImageFilter< _TImage, _TFeature, _TScalar > - _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetFeatureImage( feature ); - filter->SetPropagationScaling( this->m_Parameters.GetReal( "PropagationScaling" ) ); - filter->SetCurvatureScaling( this->m_Parameters.GetReal( "CurvatureScaling" ) ); - filter->SetMaximumRMSError( this->m_Parameters.GetReal( "MaximumRMSError" ) ); - filter->SetIsoSurfaceValue( this->m_Parameters.GetReal( "IsoSurfaceValue" ) ); - filter->SetNumberOfIterations( this->m_Parameters.GetUint( "NumberOfIterations" ) ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.h b/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.h deleted file mode 100644 index d82aa9b..0000000 --- a/plugins/ITKLevelSetFilters/LaplacianSegmentationLevelSetImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKLevelSetFilters__LaplacianSegmentationLevelSetImageFilter__h__ -#define __cpPluginsITKLevelSetFilters__LaplacianSegmentationLevelSetImageFilter__h__ - -#include -#include - -namespace cpPluginsITKLevelSetFilters -{ - /** - */ - class cpPlugins_ITKLevelSetFilters_EXPORT LaplacianSegmentationLevelSetImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - LaplacianSegmentationLevelSetImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageLevelSetFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TFeature, class _TImage > - inline void _GD1( _TFeature* feature, _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKLevelSetFilters__LaplacianSegmentationLevelSetImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.cxx b/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.cxx deleted file mode 100644 index 9847f54..0000000 --- a/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.cxx +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKLevelSetFilters::ThresholdSegmentationLevelSetImageFilter:: -ThresholdSegmentationLevelSetImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Feature", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "PropagationScaling", 1 ); - this->m_Parameters.ConfigureAsReal( "CurvatureScaling", 1 ); - this->m_Parameters.ConfigureAsReal( "MaximumRMSError", 0.02 ); - this->m_Parameters.ConfigureAsReal( "UpperThreshold", 1 ); - this->m_Parameters.ConfigureAsReal( "LowerThreshold", 0 ); - this->m_Parameters.ConfigureAsReal( "IsoSurfaceValue", 0 ); - this->m_Parameters.ConfigureAsUint( "NumberOfIterations", 100 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKLevelSetFilters::ThresholdSegmentationLevelSetImageFilter:: -~ThresholdSegmentationLevelSetImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKLevelSetFilters::ThresholdSegmentationLevelSetImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_RealPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image dimension." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKLevelSetFilters::ThresholdSegmentationLevelSetImageFilter:: -_GD0( _TImage* image ) -{ - auto f = this->GetInputData( "Feature" ); - cpPlugins_Demangle_Image_RealPixels_2( f, _GD1, _TImage::ImageDimension, image ) - this->_Error( "Invalid feature image." ); -} - -// ------------------------------------------------------------------------- -template< class _TFeature, class _TImage > -void cpPluginsITKLevelSetFilters::ThresholdSegmentationLevelSetImageFilter:: -_GD1( _TFeature* feature, _TImage* image ) -{ - typedef typename _TFeature::PixelType _TScalar; - typedef - itk::ThresholdSegmentationLevelSetImageFilter< _TImage, _TFeature, _TScalar > - _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetFeatureImage( feature ); - filter->SetPropagationScaling( this->m_Parameters.GetReal( "PropagationScaling" ) ); - filter->SetCurvatureScaling( this->m_Parameters.GetReal( "CurvatureScaling" ) ); - filter->SetMaximumRMSError( this->m_Parameters.GetReal( "MaximumRMSError" ) ); - filter->SetUpperThreshold( this->m_Parameters.GetReal( "UpperThreshold" ) ); - filter->SetLowerThreshold( this->m_Parameters.GetReal( "LowerThreshold" ) ); - filter->SetIsoSurfaceValue( this->m_Parameters.GetReal( "IsoSurfaceValue" ) ); - filter->SetNumberOfIterations( this->m_Parameters.GetUint( "NumberOfIterations" ) ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.h b/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.h deleted file mode 100644 index c8a071d..0000000 --- a/plugins/ITKLevelSetFilters/ThresholdSegmentationLevelSetImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKLevelSetFilters__ThresholdSegmentationLevelSetImageFilter__h__ -#define __cpPluginsITKLevelSetFilters__ThresholdSegmentationLevelSetImageFilter__h__ - -#include -#include - -namespace cpPluginsITKLevelSetFilters -{ - /** - */ - class cpPlugins_ITKLevelSetFilters_EXPORT ThresholdSegmentationLevelSetImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - ThresholdSegmentationLevelSetImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageLevelSetFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TFeature, class _TImage > - inline void _GD1( _TFeature* feature, _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKLevelSetFilters__ThresholdSegmentationLevelSetImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKMorphology/ITKMorphology.i b/plugins/ITKMorphology/ITKMorphology.i deleted file mode 100644 index 212fd21..0000000 --- a/plugins/ITKMorphology/ITKMorphology.i +++ /dev/null @@ -1,7 +0,0 @@ -** TODO: -header #undef ITK_MANUAL_INSTANTIATION - -tinclude itkBinaryFillholeImageFilter:h|hxx -instances itk::BinaryFillholeImageFilter< itk::Image< #scalar_types#, #vdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKNeighborhoodOperatorFilters/ITKNeighborhoodOperatorFilters.i b/plugins/ITKNeighborhoodOperatorFilters/ITKNeighborhoodOperatorFilters.i deleted file mode 100644 index 943b07f..0000000 --- a/plugins/ITKNeighborhoodOperatorFilters/ITKNeighborhoodOperatorFilters.i +++ /dev/null @@ -1,19 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define filters_1=LaplacianImageFilter -define i_reals=#real_types# -define o_reals=#real_types# - -tinclude itkNeighborhoodInnerProduct:h|hxx -instances itk::NeighborhoodInnerProduct< itk::Image< float, #pdims# >, float, double > - -tinclude itkNeighborhoodOperatorImageFilter:h|hxx -instances itk::NeighborhoodOperatorImageFilter< itk::Image< float, #pdims# >, itk::Image< float, #pdims# >, float > - -tinclude itkLaplacianOperator:h|hxx -instances itk::LaplacianOperator< float, #pdims#, itk::NeighborhoodAllocator< float > > - -tinclude itk#filters_1#:h|hxx -instances itk::#filters_1#< itk::Image< #i_reals#, #pdims# >, itk::Image< #o_reals#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.cxx b/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.cxx deleted file mode 100644 index 7dcf749..0000000 --- a/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.cxx +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKParaMorphology::BinaryDilateParaImageFilter:: -BinaryDilateParaImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - this->m_Parameters.ConfigureAsReal( "Radius", 3 ); - this->m_Parameters.ConfigureAsBool( "Circular", true ); - this->m_Parameters.ConfigureAsBool( "UseImageSpacing", false ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKParaMorphology::BinaryDilateParaImageFilter:: -~BinaryDilateParaImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKParaMorphology::BinaryDilateParaImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "No valid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKParaMorphology::BinaryDilateParaImageFilter:: -_GD0( _TImage* image ) -{ - typedef itk::BinaryDilateParaImageFilter< _TImage > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetRadius( this->m_Parameters.GetReal( "Radius" ) ); - filter->SetCircular( this->m_Parameters.GetBool( "Circular" ) ); - filter->SetUseImageSpacing( this->m_Parameters.GetBool( "UseImageSpacing" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.h b/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.h deleted file mode 100644 index 1325985..0000000 --- a/plugins/ITKParaMorphology/BinaryDilateParaImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKParaMorphology__BinaryDilateParaImageFilter__h__ -#define __cpPluginsITKParaMorphology__BinaryDilateParaImageFilter__h__ - -#include -#include - -namespace cpPluginsITKParaMorphology -{ - /** - */ - class cpPlugins_ITKParaMorphology_EXPORT BinaryDilateParaImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryDilateParaImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageMorphology - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKParaMorphology__BinaryDilateParaImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.cxx b/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.cxx deleted file mode 100644 index 30fb4b8..0000000 --- a/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.cxx +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKParaMorphology::BinaryErodeParaImageFilter:: -BinaryErodeParaImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - this->m_Parameters.ConfigureAsReal( "Radius", 3 ); - this->m_Parameters.ConfigureAsBool( "Circular", true ); - this->m_Parameters.ConfigureAsBool( "UseImageSpacing", false ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKParaMorphology::BinaryErodeParaImageFilter:: -~BinaryErodeParaImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKParaMorphology::BinaryErodeParaImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "No valid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKParaMorphology::BinaryErodeParaImageFilter:: -_GD0( _TImage* image ) -{ - typedef itk::BinaryErodeParaImageFilter< _TImage > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetRadius( this->m_Parameters.GetReal( "Radius" ) ); - filter->SetCircular( this->m_Parameters.GetBool( "Circular" ) ); - filter->SetUseImageSpacing( this->m_Parameters.GetBool( "UseImageSpacing" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.h b/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.h deleted file mode 100644 index adae5e9..0000000 --- a/plugins/ITKParaMorphology/BinaryErodeParaImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKParaMorphology__BinaryErodeParaImageFilter__h__ -#define __cpPluginsITKParaMorphology__BinaryErodeParaImageFilter__h__ - -#include -#include - -namespace cpPluginsITKParaMorphology -{ - /** - */ - class cpPlugins_ITKParaMorphology_EXPORT BinaryErodeParaImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryErodeParaImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageMorphology - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKParaMorphology__BinaryErodeParaImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKParaMorphology/ITKParaMorphology.i b/plugins/ITKParaMorphology/ITKParaMorphology.i deleted file mode 100644 index fade5c4..0000000 --- a/plugins/ITKParaMorphology/ITKParaMorphology.i +++ /dev/null @@ -1,18 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define itk_filters=BinaryDilateParaImageFilter;BinaryErodeParaImageFilter -define i_scalars=#scalar_types# -define o_scalars=#scalar_types# -define booleans=false;true - -tinclude itkParabolicErodeDilateImageFilter:h|hxx -tinclude itk#itk_filters#:h|hxx - -cinclude itkUnaryFunctorImageFilter.hxx - -instances itk::ParabolicErodeDilateImageFilter< itk::Image< #i_scalars#, #pdims# >, #booleans#, itk::Image< #o_scalars#, #pdims# > > - -instances itk::#itk_filters#< itk::Image< #i_scalars#, #pdims# >, itk::Image< #o_scalars#, #pdims# > > - - -** eof - $RCSfile$ diff --git a/plugins/ITKRasterFilters/ITKRasterFilters.i b/plugins/ITKRasterFilters/ITKRasterFilters.i deleted file mode 100644 index 11cda00..0000000 --- a/plugins/ITKRasterFilters/ITKRasterFilters.i +++ /dev/null @@ -1,9 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkTriangleMeshToBinaryImageFilter:h|hxx -tinclude cpExtensions/Algorithms/RasterContourFilter:h|hxx - -instances itk::TriangleMeshToBinaryImageFilter< itk::Mesh< #real_types#, 3 >, itk::Image< #scalar_types#, 3 > > -instances cpExtensions::Algorithms::RasterContourFilter< itk::Image< #scalar_types#, 2 > > - -** eof - $RCSfile$ diff --git a/plugins/ITKRasterFilters/RasterImageFilter.cxx b/plugins/ITKRasterFilters/RasterImageFilter.cxx deleted file mode 100644 index 097566c..0000000 --- a/plugins/ITKRasterFilters/RasterImageFilter.cxx +++ /dev/null @@ -1,160 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKRasterFilters::RasterImageFilter:: -RasterImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Mesh _TMesh; - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TMesh >( "Input", true, false ); - this->_ConfigureInput< _TImage >( "TemplateImage", false, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "InsideValue", 1 ); - this->m_Parameters.ConfigureAsReal( "OutsideValue", 0 ); - this->m_Parameters.ConfigureAsScalarTypesChoices( "OutputPixelType" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKRasterFilters::RasterImageFilter:: -~RasterImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKRasterFilters::RasterImageFilter:: -_GenerateData( ) -{ - auto mesh = this->GetInputData< vtkPolyData >( "Input" ); - double bounds[ 6 ]; - mesh->GetBounds( bounds ); - double zdiff = std::fabs( bounds[ 5 ] - bounds[ 4 ] ); - if( zdiff > 1e-5 ) - { - cpPlugins_Demangle_Mesh_Meshes_1( - this->GetInputData( "Input" ), _GD0_3D, 3 - ) - this->_Error( "Invalid input image dimension." ); - } - else - this->_GD0_2D( mesh ); -} - -// ------------------------------------------------------------------------- -template< class _TMesh > -void cpPluginsITKRasterFilters::RasterImageFilter:: -_GD0_2D( _TMesh* mesh ) -{ - std::string p_type = - this->m_Parameters.GetSelectedChoice( "OutputPixelType" ); - if( p_type == "char" ) this->_GD1_2D< _TMesh, char >( mesh ); - else if( p_type == "short" ) this->_GD1_2D< _TMesh, short >( mesh ); - else if( p_type == "int" ) this->_GD1_2D< _TMesh, int >( mesh ); - else if( p_type == "long" ) this->_GD1_2D< _TMesh, long >( mesh ); - else if( p_type == "uchar" ) this->_GD1_2D< _TMesh, unsigned char >( mesh ); - else if( p_type == "ushort" ) this->_GD1_2D< _TMesh, unsigned short >( mesh ); - else if( p_type == "uint" ) this->_GD1_2D< _TMesh, unsigned int >( mesh ); - else if( p_type == "ulong" ) this->_GD1_2D< _TMesh, unsigned long >( mesh ); - else if( p_type == "float" ) this->_GD1_2D< _TMesh, float >( mesh ); - else if( p_type == "double" ) this->_GD1_2D< _TMesh, double >( mesh ); -} - -// ------------------------------------------------------------------------- -template< class _TMesh, class _TPixelType > -void cpPluginsITKRasterFilters::RasterImageFilter:: -_GD1_2D( _TMesh* mesh ) -{ - typedef itk::Image< _TPixelType, 2 > _TImage; - typedef typename _TImage::Superclass _TBaseImage; - typedef cpExtensions::Algorithms::RasterContourFilter< _TImage > _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInsideValue( this->m_Parameters.GetReal( "InsideValue" ) ); - filter->SetOutsideValue( this->m_Parameters.GetReal( "OutsideValue" ) ); - filter->SetTemplate( this->GetInputData< _TBaseImage >( "TemplateImage" ) ); - filter->ClearPoints( ); - for( unsigned long i = 0; i < mesh->GetNumberOfPoints( ); ++i ) - { - double pnt[ 3 ]; - mesh->GetPoint( i, pnt ); - filter->AddPoint( pnt ); - - } // rof - - // Execute and connect output - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// ------------------------------------------------------------------------- -template< class _TMesh > -void cpPluginsITKRasterFilters::RasterImageFilter:: -_GD0_3D( _TMesh* mesh ) -{ - std::string p_type = - this->m_Parameters.GetSelectedChoice( "OutputPixelType" ); - if( p_type == "char" ) this->_GD1_3D< _TMesh, char >( mesh ); - else if( p_type == "short" ) this->_GD1_3D< _TMesh, short >( mesh ); - else if( p_type == "int" ) this->_GD1_3D< _TMesh, int >( mesh ); - else if( p_type == "long" ) this->_GD1_3D< _TMesh, long >( mesh ); - else if( p_type == "uchar" ) this->_GD1_3D< _TMesh, unsigned char >( mesh ); - else if( p_type == "ushort" ) this->_GD1_3D< _TMesh, unsigned short >( mesh ); - else if( p_type == "uint" ) this->_GD1_3D< _TMesh, unsigned int >( mesh ); - else if( p_type == "ulong" ) this->_GD1_3D< _TMesh, unsigned long >( mesh ); - else if( p_type == "float" ) this->_GD1_3D< _TMesh, float >( mesh ); - else if( p_type == "double" ) this->_GD1_3D< _TMesh, double >( mesh ); -} - -// ------------------------------------------------------------------------- -template< class _TMesh, class _TPixelType > -void cpPluginsITKRasterFilters::RasterImageFilter:: -_GD1_3D( _TMesh* mesh ) -{ - typedef itk::Image< _TPixelType, 3 > _TImage; - typedef typename _TImage::Superclass _TBaseImage; - typedef itk::TriangleMeshToBinaryImageFilter< _TMesh, _TImage > _TFilter; - - // Create filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - - // Compute bounding box - typename _TImage::DirectionType direction; - typename _TImage::PointType origin; - typename _TImage::SizeType size; - typename _TImage::SpacingType spac; - auto t_image = this->GetInputData< _TBaseImage >( "TemplateImage" ); - if( t_image == NULL ) - { - } - else - { - direction = t_image->GetDirection( ); - origin = t_image->GetOrigin( ); - size = t_image->GetLargestPossibleRegion( ).GetSize( ); - spac = t_image->GetSpacing( ); - - } // fi - - // Configure filter - filter->SetDirection( direction ); - filter->SetOrigin( origin ); - filter->SetSize( size ); - filter->SetSpacing( spac ); - filter->SetInsideValue( this->m_Parameters.GetReal( "InsideValue" ) ); - filter->SetOutsideValue( this->m_Parameters.GetReal( "OutsideValue" ) ); - - // Execute and connect output - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKRasterFilters/RasterImageFilter.h b/plugins/ITKRasterFilters/RasterImageFilter.h deleted file mode 100644 index f9e6f0d..0000000 --- a/plugins/ITKRasterFilters/RasterImageFilter.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef __cpPluginsITKRasterFilters__RasterImageFilter__h__ -#define __cpPluginsITKRasterFilters__RasterImageFilter__h__ - -#include -#include - -namespace cpPluginsITKRasterFilters -{ - /** - */ - class cpPlugins_ITKRasterFilters_EXPORT RasterImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - RasterImageFilter, - cpPlugins::Pipeline::ProcessObject, - MeshToImageFilters - ); - - protected: - template< class _TMesh > - inline void _GD0_2D( _TMesh* mesh ); - - template< class _TMesh, class _TPixelType > - inline void _GD1_2D( _TMesh* mesh ); - - template< class _TMesh > - inline void _GD0_3D( _TMesh* mesh ); - - template< class _TMesh, class _TPixelType > - inline void _GD1_3D( _TMesh* mesh ); - - - /* TODO - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - */ - }; - -} // ecapseman - -#endif // __cpPluginsITKRasterFilters__RasterImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKSeparableFilters/ITKSeparableFilters.i b/plugins/ITKSeparableFilters/ITKSeparableFilters.i deleted file mode 100644 index ad1c5f5..0000000 --- a/plugins/ITKSeparableFilters/ITKSeparableFilters.i +++ /dev/null @@ -1,7 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define filters=RecursiveSeparableImageFilter;RecursiveGaussianImageFilter;SmoothingRecursiveGaussianImageFilter -tinclude itk#filters#:h|hxx -instances itk::#filters#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #real_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.cxx b/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.cxx deleted file mode 100644 index 5b79eaa..0000000 --- a/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.cxx +++ /dev/null @@ -1,74 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKSeparableFilters::SmoothingRecursiveGaussianImageFilter:: -SmoothingRecursiveGaussianImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - this->m_Parameters.ConfigureAsRealList( "SigmaArray" ); - this->m_Parameters.ConfigureAsRealTypesChoices( "OutputResolution" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKSeparableFilters::SmoothingRecursiveGaussianImageFilter:: -~SmoothingRecursiveGaussianImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKSeparableFilters::SmoothingRecursiveGaussianImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image dimension." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKSeparableFilters::SmoothingRecursiveGaussianImageFilter:: -_GD0( _TImage* image ) -{ - std::string out_res = - this->m_Parameters.GetSelectedChoice( "OutputResolution" ); - if( out_res == "float" ) this->_GD1< _TImage, float >( image ); - if( out_res == "double" ) this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKSeparableFilters::SmoothingRecursiveGaussianImageFilter:: -_GD1( _TImage* image ) -{ - typedef itk::Image< _TScalar, _TImage::ImageDimension > _TOutput; - typedef - itk::SmoothingRecursiveGaussianImageFilter< _TImage, _TOutput > - _TFilter; - typedef typename _TFilter::SigmaArrayType _TSigmas; - - auto param_sigmas = this->m_Parameters.GetRealList( "SigmaArray" ); - unsigned int dim = - ( param_sigmas.size( ) < _TImage::ImageDimension )? - param_sigmas.size( ): - _TImage::ImageDimension; - _TSigmas sigmas; - sigmas.Fill( param_sigmas[ dim - 1 ] ); - for( unsigned d = 0; d < dim; ++d ) - sigmas[ d ] = param_sigmas[ d ]; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetSigmaArray( sigmas ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.h b/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.h deleted file mode 100644 index edac699..0000000 --- a/plugins/ITKSeparableFilters/SmoothingRecursiveGaussianImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKSeparableFilters__SmoothingRecursiveGaussianImageFilter__h__ -#define __cpPluginsITKSeparableFilters__SmoothingRecursiveGaussianImageFilter__h__ - -#include -#include - -namespace cpPluginsITKSeparableFilters -{ - /** - */ - class cpPlugins_ITKSeparableFilters_EXPORT SmoothingRecursiveGaussianImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SmoothingRecursiveGaussianImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageSeparableFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKSeparableFilters__SmoothingRecursiveGaussianImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKSliceFilters/CPRImageFilter.cxx b/plugins/ITKSliceFilters/CPRImageFilter.cxx deleted file mode 100644 index 9e6b8a8..0000000 --- a/plugins/ITKSliceFilters/CPRImageFilter.cxx +++ /dev/null @@ -1,63 +0,0 @@ -#include - -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKSliceFilters::CPRImageFilter:: -CPRImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - typedef cpInstances::DataObjects::Simple3DCurve _TCurve; - this->_ConfigureInput< _TImage >( "Image", true, false ); - this->_ConfigureInput< _TCurve >( "Curve", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - this->m_Parameters.ConfigureAsReal( "SliceRadius", 1 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKSliceFilters::CPRImageFilter:: -~CPRImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKSliceFilters::CPRImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Image" ); - cpPlugins_Demangle_Image_ScalarPixels_1( o, _GD0, 3 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKSliceFilters::CPRImageFilter:: -_GD0( _TImage* image ) -{ - auto o = this->GetInputData( "Curve" ); - cpPlugins_Demangle_Simple3DCurve_All_2( o, _GD1, image ) - this->_Error( "Invalid input curve." ); -} - -// ------------------------------------------------------------------------- -template< class _TCurve, class _TImage > -void cpPluginsITKSliceFilters::CPRImageFilter:: -_GD1( _TCurve* curve, _TImage* image ) -{ - typedef cpExtensions::Algorithms::CPRImageFilter< _TImage, _TCurve > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetCurve( curve ); - filter->SetSliceRadius( this->m_Parameters.GetReal( "SliceRadius" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKSliceFilters/CPRImageFilter.h b/plugins/ITKSliceFilters/CPRImageFilter.h deleted file mode 100644 index a2d0802..0000000 --- a/plugins/ITKSliceFilters/CPRImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKSliceFilters__CPRImageFilter__h__ -#define __cpPluginsITKSliceFilters__CPRImageFilter__h__ - -#include -#include - -namespace cpPluginsITKSliceFilters -{ - /** - */ - class cpPlugins_ITKSliceFilters_EXPORT CPRImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - CPRImageFilter, - cpPlugins::Pipeline::ProcessObject, - ITKSliceFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TCurve, class _TImage > - inline void _GD1( _TCurve* curve, _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKSliceFilters__CPRImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKSliceFilters/ITKSliceFilters.i b/plugins/ITKSliceFilters/ITKSliceFilters.i deleted file mode 100644 index ee71b1c..0000000 --- a/plugins/ITKSliceFilters/ITKSliceFilters.i +++ /dev/null @@ -1,20 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude itkImageToImageFilter:h|hxx -tinclude itkInPlaceImageFilter:h|hxx -instances itk::ImageToImageFilter< itk::Image< #scalar_types#, 3 >, itk::Image< #scalar_types#, 2 > > -instances itk::InPlaceImageFilter< itk::Image< #scalar_types#, 3 >, itk::Image< #scalar_types#, 2 > > - -tinclude itkResampleImageFilter:h|hxx -instances itk::ResampleImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# >, #real_types#, #real_types# > - -tinclude cpExtensions/Algorithms/IsoImageSlicer:h|hxx -tinclude itkExtractImageFilter:h|hxx -tinclude itkJoinSeriesImageFilter:h|hxx -tinclude itkImageAlgorithm:h|hxx - -cinclude cpExtensions/DataStructures/Simple3DCurve.h -tinclude cpExtensions/Algorithms/CPRImageFilter:h|hxx -instances cpExtensions::Algorithms::CPRImageFilter< itk::Image< #scalar_types#, 3 >, cpExtensions::DataStructures::Simple3DCurve< #real_types# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKSliceFilters/IsoResampleImageFilter.cxx b/plugins/ITKSliceFilters/IsoResampleImageFilter.cxx deleted file mode 100644 index 0e451db..0000000 --- a/plugins/ITKSliceFilters/IsoResampleImageFilter.cxx +++ /dev/null @@ -1,109 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsITKSliceFilters::IsoResampleImageFilter:: -IsoResampleImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureInput< cpPlugins::Pipeline::DataObject >( "Interpolator", false, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "Scale", 1 ); - this->m_Parameters.ConfigureAsBool( "ScaleFromMinimumSpacing", true ); - this->m_Parameters.ConfigureAsRealTypesChoices( "PrecisionType" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKSliceFilters::IsoResampleImageFilter:: -~IsoResampleImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKSliceFilters::IsoResampleImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKSliceFilters::IsoResampleImageFilter:: -_GD0( _TImage* image ) -{ - typedef cpPluginsITKImageInterpolators::InterpolateImageFunction _TInterpolator; - - std::string p_type = this->m_Parameters.GetSelectedChoice( "PrecisionType" ); - auto interpolator = dynamic_cast< _TInterpolator* >( - this->GetInput( "Interpolator" )->GetSource( ) - ); - if( interpolator != NULL ) - interpolator->CreateInterpolator( image, p_type ); - if ( p_type == "float" ) this->_GD1< _TImage, float >( image ); - else if( p_type == "double" ) this->_GD1< _TImage, double >( image ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TScalar > -void cpPluginsITKSliceFilters::IsoResampleImageFilter:: -_GD1( _TImage* image ) -{ - typedef itk::IdentityTransform< _TScalar, _TImage::ImageDimension > _TTransform; - typedef itk::ResampleImageFilter< _TImage, _TImage, _TScalar, _TScalar > _TFilter; - typedef typename _TFilter::InterpolatorType _TInterpolator; - - // Initial configuration - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - - // Associate transform - typename _TTransform::Pointer transform = _TTransform::New( ); - transform->SetIdentity( ); - filter->SetTransform( transform ); - - // Compute new spacing - typename _TImage::SpacingType in_spac = image->GetSpacing( ); - double val_spac = in_spac[ 0 ]; - if( this->m_Parameters.GetBool( "ScaleFromMinimumSpacing" ) ) - for( unsigned int d = 1; d < _TImage::ImageDimension; ++d ) - val_spac = ( in_spac[ d ] < val_spac )? in_spac[ d ]: val_spac; - else - for( unsigned int d = 1; d < _TImage::ImageDimension; ++d ) - val_spac = ( in_spac[ d ] > val_spac )? in_spac[ d ]: val_spac; - val_spac *= this->m_Parameters.GetReal( "Scale" ); - typename _TImage::SpacingType out_spac; - out_spac.Fill( val_spac ); - filter->SetOutputSpacing( out_spac ); - - // Compute new size - typename _TImage::SizeType in_size = image->GetRequestedRegion( ).GetSize( ); - typename _TImage::SizeType out_size; - for( unsigned int d = 0; d < _TImage::ImageDimension; ++d ) - out_size[ d ] = ( unsigned long )( - double( in_size[ d ] ) * double( in_spac[ d ] ) / val_spac - ); - filter->SetSize( out_size ); - - // New origin - filter->SetOutputOrigin( image->GetOrigin( ) ); - - // Set interpolator - auto interpolator = this->GetInputData< _TInterpolator >( "Interpolator" ); - if( interpolator != NULL ) - filter->SetInterpolator( interpolator ); - - // Update - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKSliceFilters/IsoResampleImageFilter.h b/plugins/ITKSliceFilters/IsoResampleImageFilter.h deleted file mode 100644 index 238e7f5..0000000 --- a/plugins/ITKSliceFilters/IsoResampleImageFilter.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __cpPluginsITKSliceFilters__IsoResampleImageFilter__h__ -#define __cpPluginsITKSliceFilters__IsoResampleImageFilter__h__ - -#include -#include - -namespace cpPluginsITKSliceFilters -{ - /** - */ - class cpPlugins_ITKSliceFilters_EXPORT IsoResampleImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - IsoResampleImageFilter, - cpPlugins::Pipeline::ProcessObject, - ITKSliceFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - - template< class _TImage, class _TScalar > - inline void _GD1( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKSliceFilters__IsoResampleImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/AbsImageFilter.cxx b/plugins/ITKUnaryFunctorFilters/AbsImageFilter.cxx deleted file mode 100644 index 6e7c27c..0000000 --- a/plugins/ITKUnaryFunctorFilters/AbsImageFilter.cxx +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::AbsImageFilter:: -AbsImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::AbsImageFilter:: -~AbsImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKUnaryFunctorFilters::AbsImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKUnaryFunctorFilters::AbsImageFilter:: -_GD0( _TImage* image ) -{ - typedef itk::AbsImageFilter< _TImage, _TImage > _TFilter; - - // Configure filter - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/AbsImageFilter.h b/plugins/ITKUnaryFunctorFilters/AbsImageFilter.h deleted file mode 100644 index 2738512..0000000 --- a/plugins/ITKUnaryFunctorFilters/AbsImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKUnaryFunctorFilters__AbsImageFilter__h__ -#define __cpPluginsITKUnaryFunctorFilters__AbsImageFilter__h__ - -#include -#include - -namespace cpPluginsITKUnaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKUnaryFunctorFilters_EXPORT AbsImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - AbsImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKUnaryFunctorFilters__AbsImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.cxx b/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.cxx deleted file mode 100644 index 50c0338..0000000 --- a/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.cxx +++ /dev/null @@ -1,65 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::BinaryThresholdImageFilter:: -BinaryThresholdImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "LowerThresholdValue", 0 ); - this->m_Parameters.ConfigureAsReal( "UpperThresholdValue", 1 ); - this->m_Parameters.ConfigureAsUint( "InsideValue", 1 ); - this->m_Parameters.ConfigureAsUint( "OutsideValue", 0 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::BinaryThresholdImageFilter:: -~BinaryThresholdImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKUnaryFunctorFilters::BinaryThresholdImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKUnaryFunctorFilters::BinaryThresholdImageFilter:: -_GD0( _TImage* image ) -{ - typedef unsigned char _TBin; - typedef itk::Image< unsigned char, _TImage::ImageDimension > _TBinImage; - typedef itk::BinaryThresholdImageFilter< _TImage, _TBinImage > _TFilter; - typedef typename _TImage::PixelType _TPixel; - - // Get parameters - _TPixel lt = _TPixel( this->m_Parameters.GetReal( "LowerThresholdValue" ) ); - _TPixel ut = _TPixel( this->m_Parameters.GetReal( "UpperThresholdValue" ) ); - _TBin iv = _TBin( this->m_Parameters.GetUint( "InsideValue" ) ); - _TBin ov = _TBin( this->m_Parameters.GetUint( "OutsideValue" ) ); - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetLowerThreshold( lt ); - filter->SetUpperThreshold( ut ); - filter->SetInsideValue( iv ); - filter->SetOutsideValue( ov ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.h b/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.h deleted file mode 100644 index a2a0773..0000000 --- a/plugins/ITKUnaryFunctorFilters/BinaryThresholdImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKUnaryFunctorFilters__BinaryThresholdImageFilter__h__ -#define __cpPluginsITKUnaryFunctorFilters__BinaryThresholdImageFilter__h__ - -#include -#include - -namespace cpPluginsITKUnaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKUnaryFunctorFilters_EXPORT BinaryThresholdImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - BinaryThresholdImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageThresholdFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKUnaryFunctorFilters__BinaryThresholdImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/ITKUnaryFunctorFilters.i b/plugins/ITKUnaryFunctorFilters/ITKUnaryFunctorFilters.i deleted file mode 100644 index 4bf7475..0000000 --- a/plugins/ITKUnaryFunctorFilters/ITKUnaryFunctorFilters.i +++ /dev/null @@ -1,33 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -define all_ints=#int_types#;#uint_types# -define a_filters=Abs -define a_functor=Abs -define b_filters=Not -define b_functor=NOT - -tinclude itkUnaryFunctorImageFilter:h|hxx -cinclude itk#a_filters#ImageFilter.h -cinclude itk#b_filters#ImageFilter.h - -instances itk::UnaryFunctorImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# >, itk::Functor::#a_functor#< #scalar_types#, #scalar_types# > > - -instances itk::UnaryFunctorImageFilter< itk::Image< #all_ints#, #pdims# >, itk::Image< #all_ints#, #pdims# >, itk::Functor::#b_functor#< #all_ints#, #all_ints# > > - -cinclude itkBinaryNotImageFilter.h -instances itk::UnaryFunctorImageFilter< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# >, itk::Functor::BinaryNot< #scalar_types# > > - -define oa_filters=InvertIntensityImageFilter -tinclude itk#oa_filters#:h|hxx -instances itk::#oa_filters#< itk::Image< #scalar_types#, #pdims# >, itk::Image< #scalar_types#, #pdims# > > - -define oam_filters=BinaryThresholdImageFilter -define i_scalars=#scalar_types# -define o_scalars=#scalar_types# -tinclude itk#oam_filters#:h|hxx -instances itk::#oam_filters#< itk::Image< #i_scalars#, #pdims# >, itk::Image< #o_scalars#, #pdims# > > - -tinclude cpExtensions/Algorithms/UnaryThresholdImageFilter:h|hxx -instances cpExtensions::Algorithms::UnaryThresholdImageFilter< itk::Image< #scalar_types#, #pdims# > > - -** eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.cxx b/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.cxx deleted file mode 100644 index e9e61b9..0000000 --- a/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.cxx +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::InvertIntensityImageFilter:: -InvertIntensityImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - this->m_Parameters.ConfigureAsUint( "Maximum", 1 ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::InvertIntensityImageFilter:: -~InvertIntensityImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKUnaryFunctorFilters::InvertIntensityImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKUnaryFunctorFilters::InvertIntensityImageFilter:: -_GD0( _TImage* image ) -{ - typedef itk::InvertIntensityImageFilter< _TImage > _TFilter; - - // Configure filter - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetMaximum( this->m_Parameters.GetUint( "Maximum" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.h b/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.h deleted file mode 100644 index 3158c0d..0000000 --- a/plugins/ITKUnaryFunctorFilters/InvertIntensityImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKUnaryFunctorFilters__InvertIntensityImageFilter__h__ -#define __cpPluginsITKUnaryFunctorFilters__InvertIntensityImageFilter__h__ - -#include -#include - -namespace cpPluginsITKUnaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKUnaryFunctorFilters_EXPORT InvertIntensityImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - InvertIntensityImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageBooleanFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKUnaryFunctorFilters__InvertIntensityImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.cxx b/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.cxx deleted file mode 100644 index 8c28321..0000000 --- a/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.cxx +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::UnaryBooleanImageFilter:: -UnaryBooleanImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - - std::vector< std::string > choices; - choices.push_back( "Not" ); - this->m_Parameters.ConfigureAsChoices( "Operator", choices ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::UnaryBooleanImageFilter:: -~UnaryBooleanImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKUnaryFunctorFilters::UnaryBooleanImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_IntPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKUnaryFunctorFilters::UnaryBooleanImageFilter:: -_GD0( _TImage* image ) -{ - typedef itk::NotImageFilter< _TImage, _TImage > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.h b/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.h deleted file mode 100644 index db3ccbc..0000000 --- a/plugins/ITKUnaryFunctorFilters/UnaryBooleanImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKUnaryFunctorFilters__UnaryBooleanImageFilter__h__ -#define __cpPluginsITKUnaryFunctorFilters__UnaryBooleanImageFilter__h__ - -#include -#include - -namespace cpPluginsITKUnaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKUnaryFunctorFilters_EXPORT UnaryBooleanImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - UnaryBooleanImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageBooleanFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image1 ); - }; - -} // ecapseman - -#endif // __cpPluginsITKUnaryFunctorFilters__UnaryBooleanImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.cxx b/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.cxx deleted file mode 100644 index d119094..0000000 --- a/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.cxx +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::UnaryThresholdImageFilter:: -UnaryThresholdImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - - this->m_Parameters.ConfigureAsReal( "Threshold", 0 ); - this->m_Parameters.ConfigureAsReal( "InsideValue", 1 ); - this->m_Parameters.ConfigureAsReal( "OutsideValue", 0 ); - this->m_Parameters.ConfigureAsBool( "Strict", false ); -} - -// ------------------------------------------------------------------------- -cpPluginsITKUnaryFunctorFilters::UnaryThresholdImageFilter:: -~UnaryThresholdImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsITKUnaryFunctorFilters::UnaryThresholdImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -template< class _TImage > -void cpPluginsITKUnaryFunctorFilters::UnaryThresholdImageFilter:: -_GD0( _TImage* image ) -{ - typedef - cpExtensions::Algorithms::UnaryThresholdImageFilter< _TImage > - _TFilter; - - // Configure filter - _TFilter* filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( image ); - filter->SetThreshold( this->m_Parameters.GetReal( "Threshold" ) ); - filter->SetInsideValue( this->m_Parameters.GetReal( "InsideValue" ) ); - filter->SetOutsideValue( this->m_Parameters.GetReal( "OutsideValue" ) ); - filter->SetStrict( this->m_Parameters.GetBool( "Strict" ) ); - filter->Update( ); - - // Connect output - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.h b/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.h deleted file mode 100644 index f99e518..0000000 --- a/plugins/ITKUnaryFunctorFilters/UnaryThresholdImageFilter.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __cpPluginsITKUnaryFunctorFilters__UnaryThresholdImageFilter__h__ -#define __cpPluginsITKUnaryFunctorFilters__UnaryThresholdImageFilter__h__ - -#include -#include - -namespace cpPluginsITKUnaryFunctorFilters -{ - /** - */ - class cpPlugins_ITKUnaryFunctorFilters_EXPORT UnaryThresholdImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - UnaryThresholdImageFilter, - cpPlugins::Pipeline::ProcessObject, - ImageThresholdFilters - ); - - protected: - template< class _TImage > - inline void _GD0( _TImage* image ); - }; - -} // ecapseman - -#endif // __cpPluginsITKUnaryFunctorFilters__UnaryThresholdImageFilter__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/CylinderSource.cxx b/plugins/VTKFilters/CylinderSource.cxx deleted file mode 100644 index d8939cf..0000000 --- a/plugins/VTKFilters/CylinderSource.cxx +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::CylinderSource:: -CylinderSource( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpInstances::DataObjects::Mesh >( "Output" ); - this->m_Parameters.ConfigureAsReal( "Height", 1 ); - this->m_Parameters.ConfigureAsReal( "Radius", 1 ); - this->m_Parameters.ConfigureAsUint( "Resolution", 8 ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::CylinderSource:: -~CylinderSource( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKFilters::CylinderSource:: -_GenerateData( ) -{ - auto src = this->_CreateVTK< vtkCylinderSource >( ); - src->SetHeight( this->m_Parameters.GetReal( "Height" ) ); - src->SetRadius( this->m_Parameters.GetReal( "Radius" ) ); - src->SetResolution( this->m_Parameters.GetUint( "Resolution" ) ); - src->Update( ); - this->GetOutput( "Output" )->SetVTK( src->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/CylinderSource.h b/plugins/VTKFilters/CylinderSource.h deleted file mode 100644 index 5c25ee5..0000000 --- a/plugins/VTKFilters/CylinderSource.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __cpPluginsVTKFilters__CylinderSource__h__ -#define __cpPluginsVTKFilters__CylinderSource__h__ - -#include -#include - -namespace cpPluginsVTKFilters -{ - /** - */ - class cpPlugins_VTKFilters_EXPORT CylinderSource - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - CylinderSource, - cpPlugins::Pipeline::ProcessObject, - MeshSources - ); - }; - -} // ecapseman - -#endif // __cpPluginsVTKFilters__CylinderSource__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/MarchingCubes.cxx b/plugins/VTKFilters/MarchingCubes.cxx deleted file mode 100644 index b01a9dc..0000000 --- a/plugins/VTKFilters/MarchingCubes.cxx +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::MarchingCubes:: -MarchingCubes( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Input", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Mesh >( "Output" ); - this->m_Parameters.ConfigureAsRealList( "Thresholds" ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::MarchingCubes:: -~MarchingCubes( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKFilters::MarchingCubes:: -_GenerateData( ) -{ - // Get input - auto image = this->GetInput( "Input" ); - vtkImageData* vtk_image = image->GetVTK< vtkImageData >( ); - if( vtk_image == NULL ) - this->_Error( "Input does not have a valid VTK conversion." ); - - std::vector< double > values = - this->m_Parameters.GetRealList( "Thresholds" ); - vtkPolyData* pd = NULL; - if( vtk_image->GetDataDimension( ) == 2 ) - { - vtkMarchingSquares* ms = this->_CreateVTK< vtkMarchingSquares >( ); - ms->SetInputData( vtk_image ); - for( unsigned int i = 0; i < values.size( ); ++i ) - ms->SetValue( i, values[ i ] ); - ms->Update( ); - pd = ms->GetOutput( ); - } - else if( vtk_image->GetDataDimension( ) == 3 ) - { - vtkMarchingCubes* mc = this->_CreateVTK< vtkMarchingCubes >( ); - mc->ComputeNormalsOff( ); - mc->SetInputData( vtk_image ); - for( unsigned int i = 0; i < values.size( ); ++i ) - mc->SetValue( i, values[ i ] ); - mc->Update( ); - pd = mc->GetOutput( ); - } - else - this->_Error( "Input data does not have a valid dimension." ); - - // Connect output - this->GetOutput( "Output" )->SetVTK( pd ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/MarchingCubes.h b/plugins/VTKFilters/MarchingCubes.h deleted file mode 100644 index 693909a..0000000 --- a/plugins/VTKFilters/MarchingCubes.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __cpPluginsVTKFilters__MarchingCubes__h__ -#define __cpPluginsVTKFilters__MarchingCubes__h__ - -#include -#include - -namespace cpPluginsVTKFilters -{ - /** - */ - class cpPlugins_VTKFilters_EXPORT MarchingCubes - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - MarchingCubes, - cpPlugins::Pipeline::ProcessObject, - ImageToMeshFilters - ); - }; - -} // ecapseman - -#endif // __cpPluginsVTKFilters__MarchingCubes__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/SphereSource.cxx b/plugins/VTKFilters/SphereSource.cxx deleted file mode 100644 index 0eaac1b..0000000 --- a/plugins/VTKFilters/SphereSource.cxx +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::SphereSource:: -SphereSource( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpInstances::DataObjects::Mesh >( "Output" ); - this->m_Parameters.ConfigureAsReal( "Radius", 1 ); - this->m_Parameters.ConfigureAsUint( "PhiResolution", 8 ); - this->m_Parameters.ConfigureAsUint( "ThetaResolution", 8 ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKFilters::SphereSource:: -~SphereSource( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKFilters::SphereSource:: -_GenerateData( ) -{ - auto src = this->_CreateVTK< vtkSphereSource >( ); - src->SetRadius( this->m_Parameters.GetReal( "Radius" ) ); - src->SetPhiResolution( this->m_Parameters.GetUint( "PhiResolution" ) ); - src->SetThetaResolution( this->m_Parameters.GetUint( "ThetaResolution" ) ); - src->Update( ); - this->GetOutput( "Output" )->SetVTK( src->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKFilters/SphereSource.h b/plugins/VTKFilters/SphereSource.h deleted file mode 100644 index b0c7ac4..0000000 --- a/plugins/VTKFilters/SphereSource.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef __cpPluginsVTKFilters__SphereSource__h__ -#define __cpPluginsVTKFilters__SphereSource__h__ - -#include -#include - -namespace cpPluginsVTKFilters -{ - /** - */ - class cpPlugins_VTKFilters_EXPORT SphereSource - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SphereSource, - cpPlugins::Pipeline::ProcessObject, - MeshSources - ); - }; - -} // ecapseman - -#endif // __cpPluginsVTKFilters__SphereSource__h__ - - -// eof - $RCSfile$ diff --git a/plugins/VTKIO/MeshReader.cxx b/plugins/VTKIO/MeshReader.cxx deleted file mode 100644 index 59d2a50..0000000 --- a/plugins/VTKIO/MeshReader.cxx +++ /dev/null @@ -1,60 +0,0 @@ -#include -#include -#include - -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsVTKIO::MeshReader:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::OpenFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::OpenFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsVTKIO::MeshReader:: -MeshReader( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpInstances::DataObjects::Mesh >( "Output" ); - this->m_Parameters.Clear( ); - this->m_Parameters.ConfigureAsOpenFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "Mesh files (*.vtk)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKIO::MeshReader:: -~MeshReader( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKIO::MeshReader:: -_GenerateData( ) -{ - auto f = this->_CreateVTK< vtkPolyDataReader >( ); - f->SetFileName( this->m_Parameters.GetOpenFileName( "FileName" ).c_str( ) ); - f->Update( ); - this->GetOutput( "Output" )->SetVTK( f->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKIO/MeshReader.h b/plugins/VTKIO/MeshReader.h deleted file mode 100644 index e75cb7d..0000000 --- a/plugins/VTKIO/MeshReader.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __cpPluginsVTKIO__MeshReader__h__ -#define __cpPluginsVTKIO__MeshReader__h__ - -#include -#include - -namespace cpPluginsVTKIO -{ - /** - */ - class cpPlugins_VTKIO_EXPORT MeshReader - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( MeshReader, cpPlugins::Pipeline::ProcessObject, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - }; - -} // ecapseman - -#endif // __cpPluginsVTKIO__MeshReader__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKIO/MeshWriter.cxx b/plugins/VTKIO/MeshWriter.cxx deleted file mode 100644 index fa44b2d..0000000 --- a/plugins/VTKIO/MeshWriter.cxx +++ /dev/null @@ -1,65 +0,0 @@ -#include -#include -#include - -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginsVTKIO::MeshWriter:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::SaveFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::SaveFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginsVTKIO::MeshWriter:: -MeshWriter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Mesh >( "Input", true, false ); - this->m_Parameters.Clear( ); - this->m_Parameters.ConfigureAsSaveFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "Mesh files (*.vtk)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKIO::MeshWriter:: -~MeshWriter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKIO::MeshWriter:: -_GenerateData( ) -{ - auto mesh = this->GetInputData< vtkPolyData >( "Input" ); - if( mesh == NULL ) - this->_Error( "Invalid input mesh." ); - - auto f = this->_CreateVTK< vtkPolyDataWriter >( ); - f->SetFileName( this->m_Parameters.GetSaveFileName( "FileName" ).c_str( ) ); - f->SetInputData( mesh ); - f->SetFileTypeToBinary( ); - f->Update( ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKIO/MeshWriter.h b/plugins/VTKIO/MeshWriter.h deleted file mode 100644 index 05c14de..0000000 --- a/plugins/VTKIO/MeshWriter.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __cpPluginsVTKIO__MeshWriter__h__ -#define __cpPluginsVTKIO__MeshWriter__h__ - -#include -#include - -namespace cpPluginsVTKIO -{ - /** - */ - class cpPlugins_VTKIO_EXPORT MeshWriter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( MeshWriter, cpPlugins::Pipeline::ProcessObject, IO ); - - public: - virtual QDialog* CreateQDialog( ) override; - }; - -} // ecapseman - -#endif // __cpPluginsVTKIO__MeshWriter__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/LineWidget.cxx b/plugins/VTKWidgets/LineWidget.cxx deleted file mode 100644 index 24928e6..0000000 --- a/plugins/VTKWidgets/LineWidget.cxx +++ /dev/null @@ -1,173 +0,0 @@ -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::LineWidget:: -Clear( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::LineWidget:: -SetEnabled( bool v ) -{ - auto wdg = this->GetVTK< vtkLineWidget2 >( ); - if( wdg != NULL ) - { - wdg->SetEnabled( v ); - wdg->GetInteractor( )->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpPluginsVTKWidgets::LineWidget:: -GetEnabled( ) const -{ - auto wdg = this->GetVTK< const vtkLineWidget2 >( ); - if( wdg != NULL ) - { - vtkLineWidget2* w = const_cast< vtkLineWidget2* >( wdg ); - return( w->GetEnabled( ) != 0 ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::LineWidget:: -LineWidget( ) - : Superclass( ) -{ - typedef cpPlugins::Pipeline::DataObject _TData; - typedef cpInstances::DataObjects::Mesh _TMesh; - - this->_ConfigureInput< _TData >( "Input", false, false ); - this->_ConfigureOutput< _TMesh >( "Output" ); - - // Create output data - auto line = this->_CreateVTK< vtkPolyData >( ); - line->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - line->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - line->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - line->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - line->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - this->GetOutput( "Output" )->SetVTK( line ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::LineWidget:: -~LineWidget( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::LineWidget:: -_GenerateData( ) -{ - if( this->m_Interactors.size( ) == 0 ) - this->_Error( "Give at least one valid interactor." ); - - auto image = this->GetInputData< vtkImageData >( "Input" ); - if( image != NULL ) this->_GD_Image( image ); - else this->_Error( "Do not know how to create this widget." ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::LineWidget:: -TValidProps cpPluginsVTKWidgets::LineWidget:: -_GetValidActors( vtkObject* source ) -{ - TValidProps valid_props; - auto iIt = this->m_Interactors.begin( ); - for( ; iIt != this->m_Interactors.end( ); ++iIt ) - { - auto r = ( *iIt )->GetInteractorStyle( )->GetCurrentRenderer( ); - if( r != NULL ) - { - auto props = r->GetViewProps( ); - if( props != NULL ) - { - props->InitTraversal( ); - while( vtkProp* prop = props->GetNextProp( ) ) - { - auto image_actor = dynamic_cast< vtkImageSlice* >( prop ); - auto mesh_actor = dynamic_cast< vtkActor* >( prop ); - vtkObject* input = NULL; - if( image_actor != NULL ) - { - auto mapper = image_actor->GetMapper( ); - if( mapper != NULL ) - input = mapper->GetInput( ); - } - else if( mesh_actor != NULL ) - { - auto mapper = mesh_actor->GetMapper( ); - if( mapper != NULL ) - input = mapper->GetInput( ); - - } // fi - if( input != NULL ) - valid_props[ *iIt ].insert( prop ); - - } // elihw - - } // fi - - } // fi - - } // rof - return( valid_props ); -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::LineWidget:: -_GD_Image( vtkImageData* image ) -{ - auto valid_props = this->_GetValidActors( image ); - if( valid_props.size( ) == 0 ) - this->_Error( "Given image does not have a valid associated actor." ); - - vtkSmartPointer< vtkLineWidget2 > wdg = this->GetVTK< vtkLineWidget2 >( ); - if( wdg.GetPointer( ) == NULL ) - { - auto vIt = valid_props.begin( ); - auto actor = dynamic_cast< vtkImageSlice* >( *( vIt->second.begin( ) ) ); - - double bnds[ 6 ]; - actor->GetBounds( bnds ); - double p0[ 3 ], p1[ 3 ]; - p0[ 0 ] = bnds[ 0 ]; - p0[ 1 ] = bnds[ 2 ]; - p0[ 2 ] = bnds[ 4 ]; - p1[ 0 ] = bnds[ 1 ]; - p1[ 1 ] = bnds[ 3 ]; - p1[ 2 ] = bnds[ 5 ]; - - auto rep = vtkSmartPointer< vtkLineRepresentation >::New( ); - rep->SetPoint1WorldPosition( p0 ); - rep->SetPoint2WorldPosition( p1 ); - rep->PlaceWidget( bnds ); - - wdg = this->_CreateVTK< vtkLineWidget2 >( ); - wdg->SetInteractor( valid_props.begin( )->first ); - wdg->SetRepresentation( rep ); - wdg->EnabledOn( ); - } - else - dynamic_cast< vtkLineRepresentation* >( wdg->GetRepresentation( ) )-> - GetPolyData( this->GetOutputData< vtkPolyData >( "Output" ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/LineWidget.h b/plugins/VTKWidgets/LineWidget.h deleted file mode 100644 index 6c83cc5..0000000 --- a/plugins/VTKWidgets/LineWidget.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef __cpPluginsVTKWidgets__LineWidget__h__ -#define __cpPluginsVTKWidgets__LineWidget__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkImageData; -class vtkProp; - -// ------------------------------------------------------------------------- -namespace cpPluginsVTKWidgets -{ - /** - */ - class cpPlugins_VTKWidgets_EXPORT LineWidget - : public cpPlugins::Pipeline::Widget - { - cpPluginsObject( LineWidget, cpPlugins::Pipeline::Widget, Widgets ); - - public: - virtual void Clear( ) override; - virtual void SetEnabled( bool v ) override; - virtual bool GetEnabled( ) const override; - - protected: - typedef std::set< vtkProp* > TProps; - typedef std::map< vtkRenderWindowInteractor*, TProps > TValidProps; - - protected: - TValidProps _GetValidActors( vtkObject* source ); - void _GD_Image( vtkImageData* image ); - }; - -} // ecapseman - -#endif // __cpPluginsVTKWidgets__LineWidget__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/SeedWidget.cxx b/plugins/VTKWidgets/SeedWidget.cxx deleted file mode 100644 index d0db73e..0000000 --- a/plugins/VTKWidgets/SeedWidget.cxx +++ /dev/null @@ -1,380 +0,0 @@ -#include - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget:: -Clear( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget:: -SetEnabled( bool v ) -{ - for( auto w = this->m_Widgets.begin( ); w != this->m_Widgets.end( ); ++w ) - { - if( v ) w->second->RestartInteraction( ); - else w->second->CompleteInteraction( ); - w->second->SetEnabled( v ); - w->second->Render( ); - - } // rof -} - -// ------------------------------------------------------------------------- -bool cpPluginsVTKWidgets::SeedWidget:: -GetEnabled( ) const -{ - if( this->m_Widgets.size( ) > 0 ) - { - auto i = this->m_Widgets.begin( ); - TWidget* w = const_cast< TWidget* >( i->second.GetPointer( ) ); - return( w->GetEnabled( ) != 0 ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SeedWidget:: -SeedWidget( ) - : Superclass( ) -{ - typedef cpPlugins::Pipeline::DataObject _TData; - typedef cpInstances::DataObjects::Mesh _TMesh; - - // Create ports - this->_ConfigureInput< _TData >( "Input", false, false ); - this->_ConfigureOutput< _TMesh >( "Output" ); - - // Create output data - auto out = this->_CreateVTK< vtkPolyData >( ); - out->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - out->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - out->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - this->GetOutput( "Output" )->SetVTK( out ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SeedWidget:: -~SeedWidget( ) -{ - /* TODO - for( auto w = this->m_Widgets.begin( ); w != this->m_Widgets.end( ); ++w ) - w->second->EnabledOff( ); - this->m_Widgets.clear( ); - */ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget:: -_GenerateData( ) -{ - auto image = this->GetInputData< vtkImageData >( "Input" ); - if( image != NULL ) - this->_GD0_Image( image ); - else - this->_Error( "Invalid input image." ); -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget:: -_GD0_Image( vtkImageData* image ) -{ - auto seeds = this->GetOutputData< vtkPolyData >( "Output" ); - if( this->m_Widgets.size( ) == 0 ) - { - this->m_Command = vtkSmartPointer< TCallback >::New( ); - this->m_Command->SetSeeds( seeds ); - for( - auto inIt = this->m_Interactors.begin( ); - inIt != this->m_Interactors.end( ); - ++inIt - ) - { - auto rends = ( *inIt )->GetRenderWindow( )->GetRenderers( ); - std::set< TImageActor* > all_props; - if( rends != NULL ) - { - rends->InitTraversal( ); - while( vtkRenderer* ren = rends->GetNextItem( ) ) - { - auto props = ren->GetViewProps( ); - props->InitTraversal( ); - while( vtkProp* p = props->GetNextProp( ) ) - { - auto image_actor = dynamic_cast< TImageActor* >( p ); - if( image_actor != NULL ) - { - if( image_actor->GetImage( ) == image ) - all_props.insert( image_actor ); - - } // fi - - } // elihw - - } // elihw - - } // fi - if( all_props.size( ) == 1 ) - { - if( this->m_Widgets.find( *inIt ) == this->m_Widgets.end( ) ) - { - auto act = *( all_props.begin( ) ); - auto pla = vtkSmartPointer< TPlacer >::New( ); - auto hnd = vtkSmartPointer< THandleRep >::New( ); - auto rep = vtkSmartPointer< TSeedRep >::New( ); - auto wdg = vtkSmartPointer< TWidget >::New( ); - - pla->SetImageSlice( act ); - hnd->GetProperty( )->SetColor( 1, 0, 0 ); - hnd->SetPointPlacer( pla ); - rep->SetHandleRepresentation( hnd ); - wdg->SetRepresentation( rep ); - wdg->SetInteractor( *inIt ); - act->AddObserver( vtkCommand::InteractionEvent, this->m_Command ); - wdg->AddObserver( vtkCommand::PlacePointEvent, this->m_Command ); - wdg->AddObserver( vtkCommand::CursorChangedEvent, this->m_Command ); - this->m_Widgets[ *inIt ] = wdg; - - } // fi - - } // fi - - } // rof - - // Associate input text - std::string text = this->m_Parameters.GetString( "Text" ); - std::vector< std::string > tok1, tok2; - tok1 = cpPlugins::OS::String::Tokenize( text, "#" ); - if( tok1.size( ) > seeds->GetPoints( )->GetNumberOfPoints( ) ) - { - for( auto t1 = tok1.begin( ); t1 != tok1.end( ); ++t1 ) - { - if( *t1 != "" ) - { - tok2 = cpPlugins::OS::String::Tokenize( *t1, " " ); - double x[ 3 ]; - for( unsigned int d = 0; d < 3; ++d ) - { - if( d < tok2.size( ) ) - { - std::istringstream str( tok2[ d ] ); - str >> x[ d ]; - } - else - x[ d ] = double( 0 ); - - } // rof - - seeds->GetPoints( )->InsertNextPoint( x ); - seeds->GetVerts( )->InsertNextCell( 1 ); - seeds->GetVerts( )->InsertCellPoint( - seeds->GetPoints( )->GetNumberOfPoints( ) - 1 - ); - seeds->Modified( ); - - } // fi - - } // rof - - } // fi - } - else - { - double x[ 3 ]; - std::stringstream text; - for( long i = 0; i < seeds->GetNumberOfPoints( ); ++i ) - { - seeds->GetPoint( i, x ); - text << x[ 0 ] << " " << x[ 1 ] << " " << x[ 2 ] << "#"; - - } // rof - this->m_Parameters.SetString( "Text", text.str( ) ); - - } // fi -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SeedWidget::TCallback* -cpPluginsVTKWidgets::SeedWidget::TCallback:: -New( ) -{ - return( new TCallback ); -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget::TCallback:: -Execute( vtkObject* caller, unsigned long id, void* data ) -{ - static const double EPS = 1e-5; - auto src_act = dynamic_cast< TImageActor* >( caller ); - auto src_wdg = dynamic_cast< TWidget* >( caller ); - - if( id == vtkCommand::InteractionEvent && src_act != NULL ) - { - TWidget* widget = NULL; - TSeedRep* seed_rep = NULL; - - auto w = this->m_Widgets.begin( ); - while( w != this->m_Widgets.end( ) && widget == NULL ) - { - auto rep = - dynamic_cast< vtkSeedRepresentation* >( - ( *w )->GetRepresentation( ) - ); - if( rep != NULL ) - { - auto hnd = rep->GetHandleRepresentation( ); - if( hnd != NULL ) - { - auto pla = - dynamic_cast< SeedWidget::TPlacer* >( - hnd->GetPointPlacer( ) - ); - if( pla != NULL ) - { - auto act = pla->GetImageSlice( ); - if( act == src_act ) - { - widget = *w; - seed_rep = rep; - - } // fi - - } // fi - - } // fi - - } // fi - w++; - - } // elihw - - if( widget != NULL ) - { - // Cut through given seeds - auto plane = src_act->GetSlicePlane( ); - double x[ 3 ]; - std::vector< long > ids; - for( long i = 0; i < this->m_Seeds->GetNumberOfPoints( ); ++i ) - { - this->m_Seeds->GetPoint( i, x ); - double d = plane->DistanceToPlane( x ); - if( d <= EPS ) - ids.push_back( i ); - - } // rof - - // Erase seeds - widget->CompleteInteraction( ); - widget->EnabledOff( ); - int nSeeds = seed_rep->GetNumberOfSeeds (); - for( int i = 0; i < nSeeds; ++i ) - { - seed_rep->RemoveLastHandle( ); - widget->DeleteSeed( seed_rep->GetNumberOfSeeds( ) ); - - } // rof - - if( ids.size( ) > 0 ) - { - auto ren = widget->GetInteractor( )->FindPokedRenderer( - widget->GetInteractor( )->GetEventPosition( )[ 0 ], - widget->GetInteractor( )->GetEventPosition( )[ 1 ] - ); - - // Add seeds - seed_rep->BuildRepresentation( ); - for( auto id = ids.begin( ); id != ids.end( ); ++id ) - { - this->m_Seeds->GetPoint( *id, x ); - widget->ComputeWorldToDisplay( - ren, x[ 0 ], x[ 1 ], x[ 2 ], x - ); - x[ 2 ] = double( 0 ); - int s = seed_rep->CreateHandle( x ); - vtkHandleWidget* curr_hnd = widget->CreateNewHandle( ); - seed_rep->SetSeedDisplayPosition( s, x ); - curr_hnd->SetEnabled( 1 ); - - } // rof - - } // fi - - // Reactivate widget - widget->RestartInteraction( ); - widget->EnabledOn( ); - widget->Render( ); - - } // fi - } - else if( id == vtkCommand::PlacePointEvent && src_wdg != NULL ) - { - this->m_Widgets.insert( src_wdg ); - auto rep = - dynamic_cast< vtkSeedRepresentation* >( - src_wdg->GetRepresentation( ) - ); - if( rep != NULL ) - { - unsigned long nSeeds = rep->GetNumberOfSeeds( ); - if( nSeeds > 0 ) - { - double pos[ 3 ]; - rep->GetSeedWorldPosition( nSeeds - 1, pos ); - - this->m_Seeds->GetPoints( )->InsertNextPoint( pos ); - this->m_Seeds->GetVerts( )->InsertNextCell( 1 ); - this->m_Seeds->GetVerts( )->InsertCellPoint( - this->m_Seeds->GetPoints( )->GetNumberOfPoints( ) - 1 - ); - this->m_Seeds->Modified( ); - - } // fi - - } // fi - - } // fi -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SeedWidget::TCallback:: -SetSeeds( vtkPolyData* seeds ) -{ - this->m_Seeds = seeds; -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SeedWidget::TCallback:: -TCallback( ) - : vtkCommand( ), - m_Seeds( NULL ) -{ -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SeedWidget::TCallback:: -~TCallback( ) -{ -} - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/SeedWidget.h b/plugins/VTKWidgets/SeedWidget.h deleted file mode 100644 index b99face..0000000 --- a/plugins/VTKWidgets/SeedWidget.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef __cpPluginsVTKWidgets__SeedWidget__h__ -#define __cpPluginsVTKWidgets__SeedWidget__h__ - -#include -#include -#include - -// ------------------------------------------------------------------------- -class vtkImageData; -class vtkPointHandleRepresentation3D; -class vtkPolyData; -class vtkSeedRepresentation; -namespace cpExtensions -{ - namespace Interaction - { - class ImageSlicePointPlacer; - class SeedWidget; - } - namespace Visualization - { - class WindowLevelImageActor; - } -} - -// ------------------------------------------------------------------------- -namespace cpPluginsVTKWidgets -{ - /** - */ - class cpPlugins_VTKWidgets_EXPORT SeedWidget - : public cpPlugins::Pipeline::Widget - { - cpPluginsObject( SeedWidget, cpPlugins::Pipeline::Widget, Widgets ); - - public: - typedef vtkPointHandleRepresentation3D THandleRep; - typedef vtkSeedRepresentation TSeedRep; - typedef cpExtensions::Interaction::SeedWidget TWidget; - typedef cpExtensions::Interaction::ImageSlicePointPlacer TPlacer; - typedef cpExtensions::Visualization::WindowLevelImageActor TImageActor; - - public: - virtual void Clear( ) override; - virtual void SetEnabled( bool v ) override; - virtual bool GetEnabled( ) const override; - - protected: - /** - */ - class TCallback - : public vtkCommand - { - public: - static TCallback* New( ); - virtual void Execute( - vtkObject* caller, unsigned long id, void* data - ) override; - void SetSeeds( vtkPolyData* seeds ); - - protected: - TCallback( ); - virtual ~TCallback( ); - - protected: - vtkPolyData* m_Seeds; - std::set< TWidget* > m_Widgets; - }; - - protected: - inline void _GD0_Image( vtkImageData* image ); - - protected: - std::map< vtkRenderWindowInteractor*, vtkSmartPointer< TWidget > > m_Widgets; - vtkSmartPointer< TCallback > m_Command; - }; - -} // ecapseman - -#endif // __cpPluginsVTKWidgets__SeedWidget__h__ - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/SplineWidget.cxx b/plugins/VTKWidgets/SplineWidget.cxx deleted file mode 100644 index 5f82c7e..0000000 --- a/plugins/VTKWidgets/SplineWidget.cxx +++ /dev/null @@ -1,253 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SplineWidget:: -Clear( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SplineWidget:: -SetEnabled( bool v ) -{ - auto wdg = this->GetVTK< vtkSplineWidget >( ); - if( wdg != NULL ) - { - wdg->SetEnabled( v ); - wdg->GetInteractor( )->Render( ); - - } // fi -} - -// ------------------------------------------------------------------------- -bool cpPluginsVTKWidgets::SplineWidget:: -GetEnabled( ) const -{ - auto wdg = this->GetVTK< const vtkSplineWidget >( ); - if( wdg != NULL ) - { - vtkSplineWidget* w = const_cast< vtkSplineWidget* >( wdg ); - return( w->GetEnabled( ) != 0 ); - } - else - return( false ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SplineWidget:: -SplineWidget( ) - : Superclass( ), - m_Configured( false ) -{ - typedef cpPlugins::Pipeline::DataObject _TData; - typedef cpInstances::DataObjects::Mesh _TMesh; - - this->_ConfigureInput< _TData >( "Input", false, false ); - this->_ConfigureOutput< _TMesh >( "Output" ); - this->m_Contour = vtkSmartPointer< vtkPolyData >::New( ); - this->m_Contour->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - this->m_Contour->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - this->GetOutput( "Output" )->SetVTK( this->m_Contour ); - - this->m_Parameters.ConfigureAsBool( "Extend", false ); -} - -// ------------------------------------------------------------------------- -cpPluginsVTKWidgets::SplineWidget:: -~SplineWidget( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginsVTKWidgets::SplineWidget:: -_GenerateData( ) -{ - typedef cpExtensions::Visualization::WindowLevelImageActor _TActor; - - auto image = this->GetInputData< vtkImageData >( "Input" ); - if( image == NULL ) - this->_Error( "Invalid input image." ); - if( this->m_Interactors.size( ) == 0 ) - this->_Error( "Give at least one interactor." ); - - auto wdg = this->_CreateVTK< vtkSplineWidget >( ); - if( this->m_Configured ) - { - if( this->m_Parameters.GetBool( "Extend" ) ) - { - wdg->GetPolyData( this->m_Contour.GetPointer( ) ); - - typedef itk::Vector< double, 3 > _TVector; - typedef std::vector< _TVector > _TVectors; - - unsigned long nPoints = this->m_Contour->GetNumberOfPoints( ); - unsigned long support = nPoints / 10; - _TVectors pp, qp; - for( unsigned long i = 0; i < support; ++i ) - { - double p[ 3 ], q[ 3 ]; - this->m_Contour->GetPoint( i, p ); - this->m_Contour->GetPoint( nPoints - 1 - i, q ); - - _TVector pv, qv; - pv[ 0 ] = p[ 0 ]; - pv[ 1 ] = p[ 1 ]; - pv[ 2 ] = p[ 2 ]; - qv[ 0 ] = q[ 0 ]; - qv[ 1 ] = q[ 1 ]; - qv[ 2 ] = q[ 2 ]; - pp.push_back( pv ); - qp.push_back( qv ); - - } // rof - - _TVectors pt, qt; - pt.push_back( pp[ 1 ] - pp[ 0 ] ); - qt.push_back( qp[ 1 ] - qp[ 0 ] ); - for( unsigned long i = 1; i < support - 1; ++i ) - { - pt.push_back( pp[ i + 1 ] - pp[ i - 1 ] ); - qt.push_back( qp[ i + 1 ] - qp[ i - 1 ] ); - - } // rof - pt.push_back( pp[ support - 1 ] - pp[ support - 2 ] ); - qt.push_back( qp[ support - 1 ] - qp[ support - 2 ] ); - - _TVector t0( double( 0 ) ), t1( double( 0 ) ); - long real0 = 0, real1 = 0; - for( unsigned long i = 0; i < support; ++i ) - { - double n0 = pt[ i ].GetNorm( ); - if( n0 > double( 0 ) ) - { - t0 += pt[ i ] / n0; - real0++; - - } // fi - - double n1 = qt[ i ].GetNorm( ); - if( n1 > double( 0 ) ) - { - t1 += qt[ i ] / n1; - real1++; - - } // fi - - } // rof - - if( real0 > 0 ) - t0 /= double( -real0 ); - if( real1 > 0 ) - t1 /= double( -real1 ); - - t0 *= ( pp[ 0 ] - qp[ 0 ] ).GetNorm( ); - t1 *= ( pp[ 0 ] - qp[ 0 ] ).GetNorm( ); - - _TVector p0 = pp[ 0 ] + t0; - _TVector p1 = qp[ 0 ] + t1; - - vtkSmartPointer< vtkPolyData > cnt = this->m_Contour; - this->m_Contour = vtkSmartPointer< vtkPolyData >::New( ); - this->m_Contour->SetPoints( vtkSmartPointer< vtkPoints >::New( ) ); - this->m_Contour->SetVerts( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetLines( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetPolys( vtkSmartPointer< vtkCellArray >::New( ) ); - this->m_Contour->SetStrips( vtkSmartPointer< vtkCellArray >::New( ) ); - this->GetOutput( "Output" )->SetVTK( this->m_Contour ); - - this->m_Contour->GetPoints( )-> - InsertNextPoint( p0[ 0 ], p0[ 1 ], p0[ 2 ] ); - for( unsigned long i = 0; i < nPoints; ++i ) - { - double p[ 3 ]; - cnt->GetPoints( )->GetPoint( i, p ); - this->m_Contour->GetPoints( )->InsertNextPoint( p ); - - } // rof - this->m_Contour->GetPoints( )-> - InsertNextPoint( p1[ 0 ], p1[ 1 ], p1[ 2 ] ); - this->m_Contour->Modified( ); - } - else - wdg->GetPolyData( this->m_Contour.GetPointer( ) ); - } - else - { - auto iIt = this->m_Interactors.begin( ); - vtkRenderWindowInteractor* iren = NULL; - vtkRenderer* ren = NULL; - _TActor* actor = NULL; - for( ; iIt != this->m_Interactors.end( ); ++iIt ) - { - auto r = ( *iIt )->GetInteractorStyle( )->GetCurrentRenderer( ); - if( r != NULL ) - { - auto props = r->GetViewProps( ); - if( props != NULL ) - { - props->InitTraversal( ); - while( vtkProp* prop = props->GetNextProp( ) ) - { - auto a = dynamic_cast< _TActor* >( prop ); - if( a != NULL ) - if( a->GetImage( ) == image ) - { - iren = *iIt; - actor = a; - ren = r; - - } // fi - - } // elihw - - } // fi - - } // fi - - } // rof - if( actor == NULL || ren == NULL || iren == NULL ) - this->_Error( "Invalid actor and/or renderer." ); - - // Widget configuration - wdg->SetCurrentRenderer( ren ); - wdg->SetDefaultRenderer( ren ); - wdg->SetInputData( image ); - wdg->SetProp3D( actor ); - wdg->SetInteractor( iren ); - double bnds[ 6 ]; - image->GetBounds( bnds ); - wdg->PlaceWidget( - bnds[ 0 ], bnds[ 1 ], - bnds[ 2 ], bnds[ 3 ], - bnds[ 4 ], bnds[ 5 ] - ); - wdg->ProjectToPlaneOn( ); - wdg->SetProjectionNormalToZAxes( ); - wdg->SetProjectionPosition( - ( - actor->GetBounds( )[ 4 ] + - actor->GetBounds( )[ 5 ] - ) / double( 2 ) - ); - wdg->SetHandleSize( 0.005 ); - wdg->SetNumberOfHandles( 3 ); - this->m_Configured = true; - - } // fi -} - -// eof - $RCSfile$ diff --git a/plugins/VTKWidgets/SplineWidget.h b/plugins/VTKWidgets/SplineWidget.h deleted file mode 100644 index b17e08c..0000000 --- a/plugins/VTKWidgets/SplineWidget.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef __cpPluginsVTKWidgets__SplineWidget__h__ -#define __cpPluginsVTKWidgets__SplineWidget__h__ - -#include -#include - -#include - -/* TODO - #include - #include - #include - #include - #include - #include - #include -*/ - -// ------------------------------------------------------------------------- -class vtkPolyData; - -// ------------------------------------------------------------------------- -namespace cpPluginsVTKWidgets -{ - /** - */ - class cpPlugins_VTKWidgets_EXPORT SplineWidget - : public cpPlugins::Pipeline::Widget - { - cpPluginsObject( SplineWidget, cpPlugins::Pipeline::Widget, Widgets ); - - public: - virtual void Clear( ) override; - virtual void SetEnabled( bool v ) override; - virtual bool GetEnabled( ) const override; - - protected: - bool m_Configured; - vtkSmartPointer< vtkPolyData > m_Contour; - - /* TODO: - public: - typedef cpExtensions::Visualization::WindowLevelImageActor TImageActor; - - public: - struct TWidgetData - { - typedef cpExtensions::Interaction::SplineWidget _TWidget; - typedef cpExtensions::Interaction::ImageSlicePointPlacer _TPlacer; - - std::vector< vtkSmartPointer< _TWidget > > Widgets; - std::vector< vtkSmartPointer< _TPlacer > > Placers; - std::vector< vtkSmartPointer< vtkPointHandleRepresentation3D > > Handles; - std::vector< vtkSmartPointer< vtkSeedRepresentation > > Representations; - unsigned int ActualWidgetId; - vtkSmartPointer< vtkCommand > Command; - - TWidgetData( - SplineWidget* seedWidget, - TImageActor* actor, - vtkRenderWindowInteractor* iren - ); - virtual ~TWidgetData( ); - }; - - protected: - void _Configure( ); - - template< class _TImage > - inline void _GD0_Image( _TImage* image ); - - protected: - std::map< vtkProp*, vtkRenderWindowInteractor* > m_Props; - std::vector< TWidgetData* > m_Widgets; - bool m_Configured; - */ - }; - -} // ecapseman - -#endif // __cpPluginsVTKWidgets__SplineWidget__h__ - -// eof - $RCSfile$ diff --git a/plugins/change.csv b/plugins/change.csv deleted file mode 100644 index 999df74..0000000 --- a/plugins/change.csv +++ /dev/null @@ -1 +0,0 @@ -grep -rl cpPlugins_GenericPlugins . | xargs sed -i 's/cpPlugins_GenericPlugins/cpPlugins_GenericPlugins/g' diff --git a/plugins/cpExtensions/DiscontinuityMapImageFilter.cxx b/plugins/cpExtensions/DiscontinuityMapImageFilter.cxx deleted file mode 100644 index 6d64365..0000000 --- a/plugins/cpExtensions/DiscontinuityMapImageFilter.cxx +++ /dev/null @@ -1,49 +0,0 @@ -#include "DiscontinuityMapImageFilter.h" -#include - -#include - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::DiscontinuityMapImageFilter:: -DiscontinuityMapImageFilter( ) - : Superclass( ) -{ - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - this->m_Parameters.ConfigureAsInt( "Radius", 1 ); - this->m_Parameters.ConfigureAsBool( "UseSquareRoot", false ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::DiscontinuityMapImageFilter:: -~DiscontinuityMapImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::DiscontinuityMapImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image pixel type." ); -} - -// ------------------------------------------------------------------------- -template< class _TInputImage > -void cpPluginscpExtensions::DiscontinuityMapImageFilter:: -_GD0( _TInputImage* input ) -{ - typedef cpExtensions::Algorithms::DiscontinuityMapImageFilter< _TInputImage > _TFilter; - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( input ); - filter->SetRadius( this->m_Parameters.GetInt( "Radius" ) ); - filter->SetUseSquareRoot( this->m_Parameters.GetBool( "UseSquareRoot" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/DiscontinuityMapImageFilter.h b/plugins/cpExtensions/DiscontinuityMapImageFilter.h deleted file mode 100644 index 409854a..0000000 --- a/plugins/cpExtensions/DiscontinuityMapImageFilter.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __cpPluginscpExtensions__DiscontinuityMapImageFilter__h__ -#define __cpPluginscpExtensions__DiscontinuityMapImageFilter__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT DiscontinuityMapImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - DiscontinuityMapImageFilter, - cpPlugins::Pipeline::ProcessObject, - cpExtensions - ); - - protected: - template< class _TInputImage > - inline void _GD0( _TInputImage* input ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__DiscontinuityMapImageFilter__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/ImageFunctorFilter.cxx b/plugins/cpExtensions/ImageFunctorFilter.cxx deleted file mode 100644 index bafd384..0000000 --- a/plugins/cpExtensions/ImageFunctorFilter.cxx +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include - -/* TODO - #include -*/ - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::ImageFunctorFilter:: -ImageFunctorFilter( ) - : Superclass( ) -{ - /* TODO - typedef cpPlugins::DataObject _TFunctor; - typedef cpInstances::DataObjects::Image _TImage; - - this->_ConfigureInput< _TImage >( "Input", true, false ); - this->_ConfigureInput< _TFunctor >( "Functor", true, false ); - this->_ConfigureOutput< _TImage >( "Output" ); - */ -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::ImageFunctorFilter:: -~ImageFunctorFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::ImageFunctorFilter:: -_GenerateData( ) -{ - /* TODO - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Image_ScalarPixels_AllDims_1( o, _GD0 ) - cpPlugins_Demangle_Image_ComplexPixels_AllDims_1( o, _GD0 ) - cpPlugins_Demangle_Image_ColorPixels_AllDims_1( o, _GD0 ) - cpPlugins_Demangle_Image_VectorPixels_AllDims_1( o, _GD0 ) - this->_Error( "Invalid input image pixel type." ); - */ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage > -void cpPluginscpExtensions::ImageFunctorFilter:: -_GD0( _TInputImage* input ) -{ - /* TODO - typedef cpExtensions::Visualization::ImageFunctorFilter< _TPath > _TFilter; - auto filter = this->_CreateVTK< _TFilter >( ); - filter->SetInput( path ); - filter->Update( ); - this->GetOutput( "Output" )->SetVTK( filter->GetOutput( ) ); - */ -} - -// ------------------------------------------------------------------------- -template< class _TInputImage, class _TOutputImage > -void cpPluginscpExtensions::ImageFunctorFilter:: -_GD1( _TInputImage* input ) -{ -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/ImageFunctorFilter.h b/plugins/cpExtensions/ImageFunctorFilter.h deleted file mode 100644 index 752d76f..0000000 --- a/plugins/cpExtensions/ImageFunctorFilter.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __cpPluginscpExtensions__ImageFunctorFilter__h__ -#define __cpPluginscpExtensions__ImageFunctorFilter__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT ImageFunctorFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - ImageFunctorFilter, - cpPlugins::Pipeline::ProcessObject, - cpExtensions - ); - - protected: - template< class _TInputImage > - inline void _GD0( _TInputImage* input ); - - template< class _TInputImage, class _TOutputImage > - inline void _GD1( _TInputImage* input ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__ImageFunctorFilter__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathToPolyData.cxx b/plugins/cpExtensions/PolyLineParametricPathToPolyData.cxx deleted file mode 100644 index ff3a77e..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathToPolyData.cxx +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathToPolyData:: -PolyLineParametricPathToPolyData( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::PolyLineParametricPath >( - "Input", true, false - ); - this->_ConfigureOutput< cpInstances::DataObjects::Mesh >( "Output" ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathToPolyData:: -~PolyLineParametricPathToPolyData( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::PolyLineParametricPathToPolyData:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_PolyLineParametricPath_All_1( o, _GD0 ) - this->_Error( "Invalid input path." ); -} - -// ------------------------------------------------------------------------- -template< class _TPath > -void cpPluginscpExtensions::PolyLineParametricPathToPolyData:: -_GD0( _TPath* path ) -{ - typedef cpExtensions::Visualization::PolyLineParametricPathToPolyData< _TPath > _TFilter; - - auto filter = this->_CreateVTK< _TFilter >( ); - filter->SetInput( path ); - filter->Update( ); - this->GetOutput( "Output" )->SetVTK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathToPolyData.h b/plugins/cpExtensions/PolyLineParametricPathToPolyData.h deleted file mode 100644 index f0bf178..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathToPolyData.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __cpPluginscpExtensions__PolyLineParametricPathToPolyData__h__ -#define __cpPluginscpExtensions__PolyLineParametricPathToPolyData__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT PolyLineParametricPathToPolyData - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - PolyLineParametricPathToPolyData, - cpPlugins::Pipeline::ProcessObject, - cpExtensions - ); - - protected: - template< class _TPath > - inline void _GD0( _TPath* path ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__PolyLineParametricPathToPolyData__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.cxx b/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.cxx deleted file mode 100644 index 92a6d7a..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.cxx +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathToSimple3DCurve:: -PolyLineParametricPathToSimple3DCurve( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::PolyLineParametricPath >( - "Input", true, false - ); - this->_ConfigureOutput< cpInstances::DataObjects::Simple3DCurve >( "Output" ); - this->m_Parameters.ConfigureAsUint( "NumberOfSamples", 0 ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathToSimple3DCurve:: -~PolyLineParametricPathToSimple3DCurve( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::PolyLineParametricPathToSimple3DCurve:: -_GenerateData( ) -{ - typedef cpExtensions::DataStructures::PolyLineParametricPath< 3 > _TPath; - typedef cpExtensions::DataStructures::Simple3DCurve< double > _TCurve; - typedef cpExtensions::Algorithms::PolyLineParametricPathToSimple3DCurve< _TPath, _TCurve > _TFilter; - - auto in = this->GetInputData< _TPath >( "Input" ); - if( in == NULL ) - this->_Error( "Invalid input path." ); - - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetInput( in ); - filter->SetNumberOfSamples( this->m_Parameters.GetUint( "NumberOfSamples" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.h b/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.h deleted file mode 100644 index 864acf6..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathToSimple3DCurve.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef __cpPluginscpExtensions__PolyLineParametricPathToSimple3DCurve__h__ -#define __cpPluginscpExtensions__PolyLineParametricPathToSimple3DCurve__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT PolyLineParametricPathToSimple3DCurve - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - PolyLineParametricPathToSimple3DCurve, - cpPlugins::Pipeline::ProcessObject, - cpExtensions - ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__PolyLineParametricPathToSimple3DCurve__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathWriter.cxx b/plugins/cpExtensions/PolyLineParametricPathWriter.cxx deleted file mode 100644 index 400d3eb..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathWriter.cxx +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include - -#include -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginscpExtensions::PolyLineParametricPathWriter:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::SaveFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::SaveFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathWriter:: -PolyLineParametricPathWriter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::PolyLineParametricPath >( "Input", true, false ); - this->_ConfigureInput< cpInstances::DataObjects::Image >( "Image", false, false ); - this->m_Parameters.ConfigureAsSaveFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "PolyLineParametricPath files (*.txt)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::PolyLineParametricPathWriter:: -~PolyLineParametricPathWriter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::PolyLineParametricPathWriter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_PolyLineParametricPath_All_1( o, _GD0 ) - this->_Error( "Invalid input skeleton." ); -} - -// ------------------------------------------------------------------------- -template< class _TPolyLineParametricPath > -void cpPluginscpExtensions::PolyLineParametricPathWriter:: -_GD0( _TPolyLineParametricPath* skeleton ) -{ - auto o = this->GetInputData( "Image" ); - cpPlugins_Demangle_Image_ScalarPixels_2( o, _GD1, _TPolyLineParametricPath::PathDimension, skeleton ) - this->_GD1< itk::Image< unsigned char, _TPolyLineParametricPath::PathDimension >, _TPolyLineParametricPath >( NULL, skeleton ); -} - -// ------------------------------------------------------------------------- -template< class _TImage, class _TPolyLineParametricPath > -void cpPluginscpExtensions::PolyLineParametricPathWriter:: -_GD1( _TImage* image, _TPolyLineParametricPath* skeleton ) -{ - typedef cpExtensions::Algorithms::PolyLineParametricPathWriter< _TPolyLineParametricPath, _TImage > _TWriter; - - auto filter = this->_CreateITK< _TWriter >( ); - filter->SetInput( skeleton ); - filter->SetFileName( this->m_Parameters.GetSaveFileName( "FileName" ) ); - filter->SetImage( image ); - try - { - filter->Update( ); - } - catch( itk::ExceptionObject& err ) - { - this->_Error( err.GetDescription( ) ); - - } // yrt -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/PolyLineParametricPathWriter.h b/plugins/cpExtensions/PolyLineParametricPathWriter.h deleted file mode 100644 index 6ef0046..0000000 --- a/plugins/cpExtensions/PolyLineParametricPathWriter.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef __cpPluginscpExtensions__PolyLineParametricPathWriter__h__ -#define __cpPluginscpExtensions__PolyLineParametricPathWriter__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT PolyLineParametricPathWriter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - PolyLineParametricPathWriter, - cpPlugins::Pipeline::ProcessObject, - IO - ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< class _TPolyLineParametricPath > - inline void _GD0( _TPolyLineParametricPath* skeleton ); - - template< class _TImage, class _TPolyLineParametricPath > - inline void _GD1( _TImage* image, _TPolyLineParametricPath* skeleton ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__PolyLineParametricPathWriter__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonReader.cxx b/plugins/cpExtensions/SkeletonReader.cxx deleted file mode 100644 index 20ac274..0000000 --- a/plugins/cpExtensions/SkeletonReader.cxx +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include - -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginscpExtensions::SkeletonReader:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::OpenFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::OpenFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonReader:: -SkeletonReader( ) - : Superclass( ) -{ - this->_ConfigureOutput< cpInstances::DataObjects::Skeleton >( "Output" ); - this->m_Parameters.ConfigureAsOpenFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "Skeleton files (*.txt)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonReader:: -~SkeletonReader( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::SkeletonReader:: -_GenerateData( ) -{ - std::string success = ""; -#ifdef cpPlugins_CONFIG_PROCESS_DIMENSIONS_1 - success = this->_GD0< 1 >( ); -#endif // cpPlugins_CONFIG_PROCESS_DIMENSIONS_1 -#ifdef cpPlugins_CONFIG_PROCESS_DIMENSIONS_2 - if( success != "" ) success = this->_GD0< 2 >( ); -#endif // cpPlugins_CONFIG_PROCESS_DIMENSIONS_2 -#ifdef cpPlugins_CONFIG_PROCESS_DIMENSIONS_3 - if( success != "" ) success = this->_GD0< 3 >( ); -#endif // cpPlugins_CONFIG_PROCESS_DIMENSIONS_3 -#ifdef cpPlugins_CONFIG_PROCESS_DIMENSIONS_4 - if( success != "" ) success = this->_GD0< 4 >( ); -#endif // cpPlugins_CONFIG_PROCESS_DIMENSIONS_4 - if( success != "" ) - this->_Error( success ); -} - -// ------------------------------------------------------------------------- -template< unsigned int _VDim > -std::string cpPluginscpExtensions::SkeletonReader:: -_GD0( ) -{ - typedef cpExtensions::DataStructures::Skeleton< _VDim > _TSkeleton; - typedef cpExtensions::Algorithms::SkeletonReader< _TSkeleton > _TReader; - - auto filter = this->_CreateITK< _TReader >( ); - filter->SetFileName( this->m_Parameters.GetOpenFileName( "FileName" ) ); - try - { - filter->Update( ); - } - catch( std::exception& err ) - { - return( err.what( ) ); - - } // yrt - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); - return( "" ); -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonReader.h b/plugins/cpExtensions/SkeletonReader.h deleted file mode 100644 index 59852e0..0000000 --- a/plugins/cpExtensions/SkeletonReader.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __cpPluginscpExtensions__SkeletonReader__h__ -#define __cpPluginscpExtensions__SkeletonReader__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT SkeletonReader - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SkeletonReader, - cpPlugins::Pipeline::ProcessObject, - IO - ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< unsigned int _VDim > - inline std::string _GD0( ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__SkeletonReader__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonToImageFilter.cxx b/plugins/cpExtensions/SkeletonToImageFilter.cxx deleted file mode 100644 index f3e83bf..0000000 --- a/plugins/cpExtensions/SkeletonToImageFilter.cxx +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include -#include - -#include -#include - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonToImageFilter:: -SkeletonToImageFilter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Skeleton >( "Skeleton", true, false ); - this->_ConfigureInput< cpInstances::DataObjects::Image >( "TemplateImage", true, false ); - this->_ConfigureOutput< cpInstances::DataObjects::Image >( "Output" ); - this->m_Parameters.ConfigureAsUint( "InsideValue", 1 ); - this->m_Parameters.ConfigureAsUint( "OutsideValue", 0 ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonToImageFilter:: -~SkeletonToImageFilter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::SkeletonToImageFilter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Skeleton" ); - cpPlugins_Demangle_Skeleton_All_1( o, _GD0 ) - this->_Error( "Invalid input skeleton." ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpPluginscpExtensions::SkeletonToImageFilter:: -_GD0( _TSkeleton* skeleton ) -{ - typedef itk::ImageBase< _TSkeleton::Dimension > _TImageBase; - typedef itk::Image< unsigned char, _TSkeleton::Dimension > _TImage; - typedef cpExtensions::Algorithms::SkeletonToImageFilter< _TSkeleton, _TImage > _TFilter; - - auto image = this->GetInputData< _TImageBase >( "TemplateImage" ); - auto filter = this->_CreateITK< _TFilter >( ); - filter->SetTemplateImage( image ); - filter->SetSkeleton( skeleton ); - filter->SetInsideValue( this->m_Parameters.GetUint( "InsideValue" ) ); - filter->SetOutsideValue( this->m_Parameters.GetUint( "OutsideValue" ) ); - filter->Update( ); - this->GetOutput( "Output" )->SetITK( filter->GetOutput( ) ); -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonToImageFilter.h b/plugins/cpExtensions/SkeletonToImageFilter.h deleted file mode 100644 index 99aa824..0000000 --- a/plugins/cpExtensions/SkeletonToImageFilter.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __cpPluginscpExtensions__SkeletonToImageFilter__h__ -#define __cpPluginscpExtensions__SkeletonToImageFilter__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT SkeletonToImageFilter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SkeletonToImageFilter, - cpPlugins::Pipeline::ProcessObject, - cpExtensions - ); - - protected: - template< class _TSkeleton > - inline void _GD0( _TSkeleton* skeleton ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__SkeletonToImageFilter__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonWriter.cxx b/plugins/cpExtensions/SkeletonWriter.cxx deleted file mode 100644 index ab51404..0000000 --- a/plugins/cpExtensions/SkeletonWriter.cxx +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include - -#include -#include -#include - -#ifdef cpPlugins_QT4 -# include -#endif // cpPlugins_QT4 - -// ------------------------------------------------------------------------- -QDialog* cpPluginscpExtensions::SkeletonWriter:: -CreateQDialog( ) -{ -#ifdef cpPlugins_QT4 - cpPlugins::QT::SaveFileDialog* dlg = NULL; - if( QApplication::instance( ) != NULL ) - { - dlg = new cpPlugins::QT::SaveFileDialog( ); - dlg->SetParameters( &( this->m_Parameters ), "FileName" ); - - } // fi - return( dlg ); -#else // cpPlugins_QT4 - return( NULL ); -#endif // cpPlugins_QT4 -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonWriter:: -SkeletonWriter( ) - : Superclass( ) -{ - this->_ConfigureInput< cpInstances::DataObjects::Skeleton >( "Input", true, false ); - this->m_Parameters.ConfigureAsSaveFileName( "FileName", "" ); - this->m_Parameters.SetAcceptedFileExtensions( - "FileName", - "Skeleton files (*.txt)" - ); -} - -// ------------------------------------------------------------------------- -cpPluginscpExtensions::SkeletonWriter:: -~SkeletonWriter( ) -{ -} - -// ------------------------------------------------------------------------- -void cpPluginscpExtensions::SkeletonWriter:: -_GenerateData( ) -{ - auto o = this->GetInputData( "Input" ); - cpPlugins_Demangle_Skeleton_All_1( o, _GD0 ) - this->_Error( "Invalid input skeleton." ); -} - -// ------------------------------------------------------------------------- -template< class _TSkeleton > -void cpPluginscpExtensions::SkeletonWriter:: -_GD0( _TSkeleton* skeleton ) -{ - typedef cpExtensions::Algorithms::SkeletonWriter< _TSkeleton > _TWriter; - - auto filter = this->_CreateITK< _TWriter >( ); - filter->SetInput( skeleton ); - filter->SetFileName( this->m_Parameters.GetSaveFileName( "FileName" ) ); - try - { - filter->Update( ); - } - catch( itk::ExceptionObject& err ) - { - this->_Error( err.GetDescription( ) ); - - } // yrt -} - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/SkeletonWriter.h b/plugins/cpExtensions/SkeletonWriter.h deleted file mode 100644 index f355c87..0000000 --- a/plugins/cpExtensions/SkeletonWriter.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __cpPluginscpExtensions__SkeletonWriter__h__ -#define __cpPluginscpExtensions__SkeletonWriter__h__ - -#include -#include - -namespace cpPluginscpExtensions -{ - /** - */ - class cpPlugins_cpExtensions_EXPORT SkeletonWriter - : public cpPlugins::Pipeline::ProcessObject - { - cpPluginsObject( - SkeletonWriter, - cpPlugins::Pipeline::ProcessObject, - IO - ); - - public: - virtual QDialog* CreateQDialog( ) override; - - protected: - template< class _TSkeleton > - inline void _GD0( _TSkeleton* skeleton ); - }; - -} // ecapseman - -#endif // __cpPluginscpExtensions__SkeletonWriter__h__ - - -// eof - $RCSfile$ diff --git a/plugins/cpExtensions/cpExtensions.i b/plugins/cpExtensions/cpExtensions.i deleted file mode 100644 index f082467..0000000 --- a/plugins/cpExtensions/cpExtensions.i +++ /dev/null @@ -1,20 +0,0 @@ -header #define ITK_MANUAL_INSTANTIATION - -tinclude cpExtensions/Algorithms/DiscontinuityMapImageFilter:h|hxx -tinclude cpExtensions/Algorithms/SkeletonToImageFilter:h|hxx -tinclude cpExtensions/Algorithms/SkeletonReader:h|hxx -tinclude cpExtensions/Algorithms/SkeletonWriter:h|hxx -tinclude cpExtensions/Algorithms/PolyLineParametricPathWriter:h|hxx -cinclude cpExtensions/DataStructures/PolyLineParametricPath.h -cinclude cpExtensions/DataStructures/Skeleton.h - -instances cpExtensions::Algorithms::DiscontinuityMapImageFilter< itk::Image< #scalar_types#, #pdims# > > - -instances cpExtensions::Algorithms::PolyLineParametricPathWriter< cpExtensions::DataStructures::PolyLineParametricPath< #pdims# >, itk::Image< #scalar_types#, #pdims# > > - -instances cpExtensions::Algorithms::SkeletonToImageFilter< cpExtensions::DataStructures::Skeleton< #pdims# >, itk::Image< unsigned char, #pdims# > > - -instances cpExtensions::Algorithms::SkeletonReader< cpExtensions::DataStructures::Skeleton< #pdims# > > -instances cpExtensions::Algorithms::SkeletonWriter< cpExtensions::DataStructures::Skeleton< #pdims# > > - -** eof - $RCSfile$ diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt deleted file mode 100644 index 988fc31..0000000 --- a/tools/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ - -## =================== -## == List of tools == -## =================== - -SET(_pfx cpPlugins_tool_) -SET( - _tools - ExecutePipeline - PrintFileInfo - PrintDirInfo - PrintGuessInfo - RenameImageFile - ) - -## ======================= -## == Compilation rules == -## ======================= - -INCLUDE_DIRECTORIES( - ${PROJECT_SOURCE_DIR}/lib - ${PROJECT_BINARY_DIR}/lib - ) -FOREACH(_t ${_tools}) - ADD_EXECUTABLE(${_pfx}${_t} ${_t}.cxx) - TARGET_LINK_LIBRARIES(${_pfx}${_t} cpPlugins) -ENDFOREACH(_t) - -## eof - $RCSfile$ diff --git a/tools/ExecutePipeline.cxx b/tools/ExecutePipeline.cxx deleted file mode 100644 index 0532fa2..0000000 --- a/tools/ExecutePipeline.cxx +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include -#include -#include - -int main( int argc, char* argv[] ) -{ - if( argc < 2 ) - { - std::cerr - << "Usage: " << argv[ 0 ] << " workspace" - << std::endl; - return( 1 ); - - } // fi - - // Get plugins loader - cpPlugins::Interface::Loader loader; - loader.GuessEnvironment( cpPlugins::OS::FileSystem::CanonicalPath( "." ) ); - - int ret = 0; - try - { - // Prepare workspace - cpPlugins::Interface::Workspace::Pointer workspace = - cpPlugins::Interface::Workspace::New( ); - workspace->Load( argv[ 1 ] ); - - // Execute workspace - workspace->PrintExecutionOn( ); - workspace->Update( ); - } - catch( std::exception& err ) - { - std::cerr << "Error caught: " << err.what( ) << std::endl; - ret = 1; - - } // yrt - - // Close connection to loaded plugins file and finish execution - loader.UnRegisterAll( ); - return( ret ); -} - -// eof - $RCSfile$ diff --git a/tools/PrintDirInfo.cxx b/tools/PrintDirInfo.cxx deleted file mode 100644 index 0c00f79..0000000 --- a/tools/PrintDirInfo.cxx +++ /dev/null @@ -1,56 +0,0 @@ -#include -#include - -int main( int argc, char* argv[] ) -{ - if( argc < 2 ) - { - std::cerr << "Usage: " << argv[ 0 ] << " library" << std::endl; - return( 1 ); - - } // fi - - // Get plugins loader - std::string error_message = ""; - cpPlugins::Interface::Loader loader; - for( int i = 1; i < argc; ++i ) - { - try - { - loader.RegisterFromDirectory( argv[ i ] ); - } - catch( std::exception& err ) - { - error_message += err.what( ) + std::string( "\n" ); - - } // yrt - - } // rof - - if( error_message != "" ) - { - std::cerr - << "***************************************" << std::endl - << "Errors during load: " << std::endl - << error_message << std::endl - << "***************************************" << std::endl; - - } // fi - - // Show loader information - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - // Close connection to loaded plugins file - loader.UnRegisterAll( ); - - // Just a last check - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/tools/PrintFileInfo.cxx b/tools/PrintFileInfo.cxx deleted file mode 100644 index 0eb1109..0000000 --- a/tools/PrintFileInfo.cxx +++ /dev/null @@ -1,56 +0,0 @@ -#include -#include - -int main( int argc, char* argv[] ) -{ - if( argc < 2 ) - { - std::cerr << "Usage: " << argv[ 0 ] << " library" << std::endl; - return( 1 ); - - } // fi - - // Get plugins loader - std::string error_message = ""; - cpPlugins::Interface::Loader loader; - for( int i = 1; i < argc; ++i ) - { - try - { - loader.Register( argv[ i ] ); - } - catch( std::exception& err ) - { - error_message += err.what( ) + std::string( "\n" ); - - } // yrt - - } // rof - - if( error_message != "" ) - { - std::cerr - << "***************************************" << std::endl - << "Errors during load: " << std::endl - << error_message << std::endl - << "***************************************" << std::endl; - - } // fi - - // Show loader information - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - // Close connection to loaded plugins file - loader.UnRegisterAll( ); - - // Just a last check - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/tools/PrintGuessInfo.cxx b/tools/PrintGuessInfo.cxx deleted file mode 100644 index 7b50afd..0000000 --- a/tools/PrintGuessInfo.cxx +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include -#include - -int main( int argc, char* argv[] ) -{ - // Get plugins loader - std::string error_message = ""; - cpPlugins::Interface::Loader loader; - loader.GuessEnvironment( cpPlugins::OS::FileSystem::CanonicalPath( "." ) ); - - // Show loader information - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - // Close connection to loaded plugins file - loader.UnRegisterAll( ); - - // Just a last check - std::cout << "---------------------------" << std::endl; - std::cout << loader << std::endl; - std::cout << "---------------------------" << std::endl; - - return( 0 ); -} - -// eof - $RCSfile$ diff --git a/tools/RenameImageFile.cxx b/tools/RenameImageFile.cxx deleted file mode 100644 index 60297c4..0000000 --- a/tools/RenameImageFile.cxx +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include - -int main( int argc, char* argv[] ) -{ - if( argc < 2 ) - { - std::cerr - << "Usage: " << argv[ 0 ] - << " input_file(s) output_file" << std::endl; - return( 1 ); - - } // fi - - // Get plugins loader - cpPlugins::Interface::Loader loader; - try - { - loader.RegisterFromDirectory( "." ); - } - catch( std::exception& err ) - { - std::cerr << "Error caught: " << err.what( ) << std::endl; - return( 1 ); - - } // yrt - - // Try to get any errors - try - { - // Create filters - auto reader = loader.CreateFilter( "IO", "ImageReader", "reader" ); - auto writer = loader.CreateFilter( "IO", "ImageWriter", "writer" ); - - // Configure parameters - auto reader_params = reader->GetParameters( ); - auto writer_params = writer->GetParameters( ); - for( int i = 1; i < argc - 1; ++i ) - reader_params->AddToOpenFileNameList( "FileNames", argv[ i ] ); - writer_params->SetSaveFileName( "FileName", argv[ argc - 1 ] ); - - // Connect filters - writer->SetInput( "Input", reader->GetOutput( "Output" ) ); - - // Execute - reader->PrintExecutionOn( ); - writer->PrintExecutionOn( ); - writer->Update( ); - } - catch( std::exception& err ) - { - std::cerr << "Error caught: " << err.what( ) << std::endl; - return( 1 ); - - } // yrt - - // Close connection to loaded plugins file - loader.UnRegisterAll( ); - return( 0 ); -} - -// eof - $RCSfile$ -- 2.47.1