diff --git a/Modules/Core/include/mitkChannelDescriptor.h b/Modules/Core/include/mitkChannelDescriptor.h index 0480b64b60..b18ffdf3b3 100644 --- a/Modules/Core/include/mitkChannelDescriptor.h +++ b/Modules/Core/include/mitkChannelDescriptor.h @@ -1,78 +1,76 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCHANNELDESCRIPTOR_H #define MITKCHANNELDESCRIPTOR_H -#include "mitkPixelType.h" +#include #include namespace mitk { /** \brief An object which holds all essential information about a single channel of an Image. The channel descriptor is designed to be used only as a part of the ImageDescriptor. A consequence to this is that the ChannelDescriptor does not hold the geometry information, only the PixelType. The pixel type is the single information that can differ among an image with multiple channels. */ class MITKCORE_EXPORT ChannelDescriptor { public: ChannelDescriptor(mitk::PixelType type, size_t numOfElements, bool allocate = false); ~ChannelDescriptor(); /** \brief Get the type of channel's elements */ PixelType GetPixelType() const { return m_PixelType; } /** \brief Get the size in bytes of the channel */ size_t GetSize() const { return m_Size; } /** \brief Get the pointer to the actual data of the channel \warning Such access to the image's data is not safe and will be replaced \todo new memory management design */ unsigned char *GetData() const { return m_Data; } protected: friend class Image; friend class ImageAccessorBase; void SetData(void *dataPtr) { if (dataPtr == nullptr) { m_Data = (unsigned char *)dataPtr; } } - void AllocateData(); - /** Name of the channel */ std::string m_Name; /** The type of each element of the channel \sa PixelType */ PixelType m_PixelType; /** Size of the channel in bytes */ size_t m_Size; /** Pointer to the data of the channel \warning Not safe \todo Replace in new memory management design */ unsigned char *m_Data; }; } // end namespace mitk #endif // MITKCHANNELDESCRIPTOR_H diff --git a/Modules/Core/include/mitkMemoryUtilities.h b/Modules/Core/include/mitkMemoryUtilities.h index 33e94a49bc..84fdc6c66f 100644 --- a/Modules/Core/include/mitkMemoryUtilities.h +++ b/Modules/Core/include/mitkMemoryUtilities.h @@ -1,91 +1,39 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MEMORY_UTILITIES_H_ #define _MITK_MEMORY_UTILITIES_H_ #include #include namespace mitk { - class MITKCORE_EXPORT MemoryUtilities + namespace MemoryUtilities { - public: /** * Returns the memory usage of the current process in bytes. - * On linux, this refers to the virtual memory allocated by + * On Linux, this refers to the virtual memory allocated by * the process (the VIRT column in top). - * On windows, this refery to the size in bytes of the working + * On Windows, this refers to the size in bytes of the working * set pages (the "Speicherauslastung" column in the task manager). */ - static size_t GetProcessMemoryUsage(); + MITKCORE_EXPORT size_t GetProcessMemoryUsage(); /** * Returns the total size of physical memory in bytes */ - static size_t GetTotalSizeOfPhysicalRam(); - - /** - * Allocates an array of a given number of elements. Each element - * has a size of sizeof(ElementType). The function returns nullptr, if the array - * could not be allocated. - * @param numberOfElements the number of elements of the array - * @param noThrow if set to false, an exception is thrown if memory allocation - * fails. If set to true, a itk::MemoryAllocationError is thrown - * @returns a pointer to the allocated array. If noThrow == true, nullptr is returned - * if memory allocation failed. - */ - template - static ElementType *AllocateElements(size_t numberOfElements, bool noThrow = false) - { - // Encapsulate all image memory allocation here to throw an - // exception when memory allocation fails even when the compiler - // does not do this by default. - ElementType *data = nullptr; - try - { - data = new ElementType[numberOfElements]; - } - catch (...) - { - data = nullptr; - } - if ((data == nullptr) && (noThrow == false)) - { - throw itk::MemoryAllocationError(__FILE__, __LINE__, "Failed to allocate memory.", ITK_LOCATION); - } - return data; - } - - /** - * Deletes an array of elements previously allocated by AllocateElements. - * @param elements the array to delete. Not that nullptr is an accepted value. - */ - template - static void DeleteElements(ElementType *elements) - { - if (elements != nullptr) - { - delete[] elements; - } - } - - protected: -#ifndef _MSC_VER - static int ReadStatmFromProcFS( - int *size, int *res, int *shared, int *text, int *sharedLibs, int *stack, int *dirtyPages); -#endif - }; -} // end of namespace mitk + MITKCORE_EXPORT size_t GetTotalSizeOfPhysicalRam(); + } +} #endif diff --git a/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp b/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp index 49ec3e82ff..9b7199b15b 100644 --- a/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp +++ b/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp @@ -1,56 +1,22 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkChannelDescriptor.h" -#include "mitkMemoryUtilities.h" + +#include mitk::ChannelDescriptor::ChannelDescriptor(mitk::PixelType type, size_t numOfElements, bool /*allocate*/) : m_PixelType(type), m_Size(numOfElements), m_Data(nullptr) { - // MITK_INFO << "Entering ChannelDescriptor constructor."; } mitk::ChannelDescriptor::~ChannelDescriptor() { - // TODO: The following line should be correct but leads to an error. - // Solution might be: Hold PixelType on stack, return copy and implement - // copy constructor as well as assignment operator. - // delete m_PixelType; -} - -/* -void mitk::ChannelDescriptor::Initialize(mitk::PixelType &type, size_t numOfElements, bool allocate) -{ - if( m_PixelType.GetPixelTypeId() != type.GetPixelTypeId() ) - { - MITK_WARN << "Changing pixel type for channel: " << - m_PixelType.GetItkTypeAsString() << " -> " << - type.GetItkTypeAsString(); - } - - m_PixelType = type; - - m_Size = numOfElements * m_PixelType.GetSize(); - - if( allocate ) - { - this->AllocateData(); - } -} -*/ - -void mitk::ChannelDescriptor::AllocateData() -{ - if (m_Data == nullptr) - { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); - } } diff --git a/Modules/Core/src/DataManagement/mitkImageDataItem.cpp b/Modules/Core/src/DataManagement/mitkImageDataItem.cpp index 407ea0a0ee..f52c165603 100644 --- a/Modules/Core/src/DataManagement/mitkImageDataItem.cpp +++ b/Modules/Core/src/DataManagement/mitkImageDataItem.cpp @@ -1,334 +1,333 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkImageDataItem.h" -#include "mitkMemoryUtilities.h" +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include mitk::ImageDataItem::ImageDataItem(const ImageDataItem &aParent, const mitk::ImageDescriptor::Pointer desc, int timestep, unsigned int dimension, void *data, bool manageMemory, size_t offset) : m_Data(static_cast(aParent.m_Data) + offset), m_PixelType(new mitk::PixelType(aParent.GetPixelType())), m_ManageMemory(false), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(offset), m_IsComplete(false), m_Size(0), m_Parent(&aParent), m_Dimension(dimension), m_Timestep(timestep) { // compute size // const unsigned int *dims = desc->GetDimensions(); for (unsigned int i = 0; i < dimension; i++) { m_Dimensions[i] = desc->GetDimensions()[i]; } this->ComputeItemSize(m_Dimensions, dimension); if (data != nullptr && data != m_Data) { memcpy(m_Data, data, m_Size); if (manageMemory) { delete[](unsigned char *) data; } } m_ReferenceCount = 0; } mitk::ImageDataItem::~ImageDataItem() { if (m_VtkImageData != nullptr) { m_VtkImageData->Delete(); } if (m_VtkImageReadAccessor != nullptr) { delete m_VtkImageReadAccessor; } if (m_VtkImageWriteAccessor != nullptr) { delete m_VtkImageWriteAccessor; } if (m_Parent.IsNull()) { if (m_ManageMemory) delete[] m_Data; } delete m_PixelType; } mitk::ImageDataItem::ImageDataItem(const mitk::ImageDescriptor::Pointer desc, int timestep, void *data, bool manageMemory) : m_Data(static_cast(data)), m_PixelType(new mitk::PixelType(desc->GetChannelDescriptor(0).GetPixelType())), m_ManageMemory(manageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(0), m_IsComplete(false), m_Size(0), m_Dimension(desc->GetNumberOfDimensions()), m_Timestep(timestep) { // compute size const unsigned int *dimensions = desc->GetDimensions(); for (unsigned int i = 0; i < m_Dimension; i++) { m_Dimensions[i] = dimensions[i]; } this->ComputeItemSize(m_Dimensions, m_Dimension); if (m_Data == nullptr) { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); + m_Data = new unsigned char[m_Size]; m_ManageMemory = true; } m_ReferenceCount = 0; } mitk::ImageDataItem::ImageDataItem(const mitk::PixelType &type, int timestep, unsigned int dimension, unsigned int *dimensions, void *data, bool manageMemory) : m_Data(static_cast(data)), m_PixelType(new mitk::PixelType(type)), m_ManageMemory(manageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(0), m_IsComplete(false), m_Size(0), m_Parent(nullptr), m_Dimension(dimension), m_Timestep(timestep) { for (unsigned int i = 0; i < m_Dimension; i++) { m_Dimensions[i] = dimensions[i]; } this->ComputeItemSize(dimensions, dimension); if (m_Data == nullptr) { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); + m_Data = new unsigned char[m_Size]; m_ManageMemory = true; } m_ReferenceCount = 0; } mitk::ImageDataItem::ImageDataItem(const ImageDataItem &other) : itk::LightObject(), m_Data(other.m_Data), m_PixelType(new mitk::PixelType(*other.m_PixelType)), m_ManageMemory(other.m_ManageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(other.m_Offset), m_IsComplete(other.m_IsComplete), m_Size(other.m_Size), m_Parent(other.m_Parent), m_Dimension(other.m_Dimension), m_Timestep(other.m_Timestep) { // copy m_Data ?? for (int i = 0; i < MAX_IMAGE_DIMENSIONS; ++i) m_Dimensions[i] = other.m_Dimensions[i]; } itk::LightObject::Pointer mitk::ImageDataItem::InternalClone() const { Self::Pointer newGeometry = new Self(*this); newGeometry->UnRegister(); return newGeometry.GetPointer(); } void mitk::ImageDataItem::ComputeItemSize(const unsigned int *dimensions, unsigned int dimension) { m_Size = m_PixelType->GetSize(); for (unsigned int i = 0; i < dimension; i++) { m_Size *= *(dimensions + i); } } void mitk::ImageDataItem::ConstructVtkImageData(ImageConstPointer iP) const { vtkImageData *inData = vtkImageData::New(); vtkDataArray *scalars = nullptr; const unsigned int *dims = m_Dimensions; const unsigned int dim = m_Dimension; unsigned long size = 0; if (dim == 1) { inData->SetDimensions(dims[0] - 1, 1, 1); size = dims[0]; inData->SetOrigin(((mitk::ScalarType)dims[0]) / 2.0, 0, 0); } else if (dim == 2) { inData->SetDimensions(dims[0], dims[1], 1); size = dims[0] * dims[1]; inData->SetOrigin(((mitk::ScalarType)dims[0]) / 2.0f, ((mitk::ScalarType)dims[1]) / 2.0f, 0); } else if (dim >= 3) { inData->SetDimensions(dims[0], dims[1], dims[2]); size = dims[0] * dims[1] * dims[2]; // Test // inData->SetOrigin( (float) dims[0] / 2.0f, (float) dims[1] / 2.0f, (float) dims[2] / 2.0f ); inData->SetOrigin(0, 0, 0); } else { inData->Delete(); return; } if (m_Timestep >= 0) { SlicedGeometry3D *geom3d; geom3d = iP->GetSlicedGeometry(m_Timestep); const mitk::Vector3D vspacing = geom3d->GetSpacing(); double dspacing[3] = {vspacing[0], vspacing[1], vspacing[2]}; inData->SetSpacing(dspacing); } if (m_PixelType->GetComponentType() == itk::IOComponentEnum::CHAR) { scalars = vtkCharArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::UCHAR) { scalars = vtkUnsignedCharArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::SHORT) { scalars = vtkShortArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::USHORT) { scalars = vtkUnsignedShortArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::INT) { scalars = vtkIntArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::UINT) { scalars = vtkUnsignedIntArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::LONG) { scalars = vtkLongArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::ULONG) { scalars = vtkUnsignedLongArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::FLOAT) { scalars = vtkFloatArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::DOUBLE) { scalars = vtkDoubleArray::New(); } else { inData->Delete(); return; } m_VtkImageData = inData; // set mitk imageDataItem void array to vtk scalar values scalars->SetNumberOfComponents(m_PixelType->GetNumberOfComponents()); scalars->SetVoidArray(m_Data, size * m_PixelType->GetNumberOfComponents(), 1); m_VtkImageData->GetPointData()->SetScalars(scalars); scalars->Delete(); } void mitk::ImageDataItem::Modified() const { if (m_VtkImageData) m_VtkImageData->Modified(); } mitk::ImageVtkReadAccessor *mitk::ImageDataItem::GetVtkImageAccessor(mitk::ImageDataItem::ImageConstPointer iP) const { if (m_VtkImageData == nullptr) { ConstructVtkImageData(iP); } if (m_VtkImageReadAccessor == nullptr) { m_VtkImageReadAccessor = new ImageVtkReadAccessor(iP, this, m_VtkImageData); } return m_VtkImageReadAccessor; } mitk::ImageVtkWriteAccessor *mitk::ImageDataItem::GetVtkImageAccessor(ImagePointer iP) { if (m_VtkImageData == nullptr) { ConstructVtkImageData(iP.GetPointer()); } if (m_VtkImageWriteAccessor == nullptr) { m_VtkImageWriteAccessor = new ImageVtkWriteAccessor(iP, this, m_VtkImageData); } return m_VtkImageWriteAccessor; } diff --git a/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp b/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp index c089328d1f..ef9d70abc2 100755 --- a/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp +++ b/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp @@ -1,115 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkMemoryUtilities.h" +#include -#include #if _MSC_VER #include #include #elif defined(__APPLE__) -#include -#include +#include #include #include #else #include #include +#include #endif -/** - * Returns the memory usage of the current process in bytes. - * On linux, this refers to the virtual memory allocated by - * the process (the VIRT column in top). - * On windows, this refery to the size in bytes of the working - * set pages (the "Speicherauslastung" column in the task manager). - */ size_t mitk::MemoryUtilities::GetProcessMemoryUsage() { -#if _MSC_VER size_t size = 0; + +#if _MSC_VER DWORD pid = GetCurrentProcessId(); PROCESS_MEMORY_COUNTERS pmc; + HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); - if (hProcess == nullptr) - return 0; - if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) + + if (hProcess != nullptr) { - size = pmc.WorkingSetSize; + if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)) != 0) + size = pmc.WorkingSetSize; + + CloseHandle(hProcess); } - CloseHandle(hProcess); - return size; #elif defined(__APPLE__) - struct task_basic_info t_info; - mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; - task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); - size_t size = t_info.virtual_size; - return size; + task_vm_info taskInfo; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + + if (task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast(&taskInfo), &count) == KERN_SUCCESS) + size = taskInfo.resident_size - taskInfo.reusable; // That's what Chromium reports as process memory #else - int size, res, shared, text, sharedLibs, stack, dirtyPages; - if (!ReadStatmFromProcFS(&size, &res, &shared, &text, &sharedLibs, &stack, &dirtyPages)) - return (size_t)size * getpagesize(); - else - return 0; + std::ifstream statm("/proc/self/statm"); + + if (statm.is_open()) + { + size_t resident = 0; + size_t shared = 0; + + statm >> size >> resident >> shared; + + statm.close(); + + if (shared < resident) + size = resident - shared; // That's what the GNOME System Monitor reports as process memory + } #endif - return 0; + + return size; } -/** - * Returns the total size of physical memory in bytes - */ size_t mitk::MemoryUtilities::GetTotalSizeOfPhysicalRam() { #if _MSC_VER MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); - GlobalMemoryStatusEx(&statex); - return (size_t)statex.ullTotalPhys; + + if (GlobalMemoryStatusEx(&statex) != 0) + return statex.ullTotalPhys; #elif defined(__APPLE__) int mib[2]; - int64_t physical_memory; mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; + + int64_t physical_memory; size_t length = sizeof(int64_t); + sysctl(mib, 2, &physical_memory, &length, nullptr, 0); + return physical_memory; #else struct sysinfo info; + if (!sysinfo(&info)) return info.totalram * info.mem_unit; - else - return 0; #endif -} -#ifndef _MSC_VER -#ifndef __APPLE__ -int mitk::MemoryUtilities::ReadStatmFromProcFS( - int *size, int *res, int *shared, int *text, int *sharedLibs, int *stack, int *dirtyPages) -{ - int ret = 0; - FILE *f; - f = fopen("/proc/self/statm", "r"); - if (f) - { - size_t ignored = fscanf(f, "%d %d %d %d %d %d %d", size, res, shared, text, sharedLibs, stack, dirtyPages); - ++ignored; - fclose(f); - } - else - { - ret = -1; - } - return ret; + return 0; } -#endif -#endif diff --git a/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h b/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h index b049ca84b1..9eb9a0514c 100644 --- a/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h +++ b/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h @@ -1,48 +1,49 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#ifndef QMITKMEMORYUSAGEINDICATORVIEW_WIDGET -#define QMITKMEMORYUSAGEINDICATORVIEW_WIDGET +#ifndef QmitkMemoryUsageIndicatorView_h +#define QmitkMemoryUsageIndicatorView_h #include -#include "ui_QmitkMemoryUsageIndicator.h" #include -#include + +#include +#include + +namespace Ui +{ + class QmitkMemoryUsageIndicator; +} /// \ingroup QmitkModule -class MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicatorView : public QWidget, public Ui::QmitkMemoryUsageIndicator +class MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicatorView : public QWidget { Q_OBJECT public: - /// constructor - QmitkMemoryUsageIndicatorView(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr); - - /// destructor + QmitkMemoryUsageIndicatorView(QWidget* parent = nullptr); ~QmitkMemoryUsageIndicatorView() override; -protected slots: +private: void UpdateMemoryUsage(); - -protected: std::string FormatMemorySize(size_t size); std::string FormatPercentage(double val); std::string GetMemoryDescription(size_t processSize, float percentage); - QPixmap m_LEDGreen; - QPixmap m_LEDYellow; - QPixmap m_LEDOrange; - QPixmap m_LEDRed; - char m_PreviousState; + static std::array, 4> s_States; + + Ui::QmitkMemoryUsageIndicator* m_Ui; + size_t m_PreviousState; }; -#endif // QMITKMEMORYUSAGEINDICATORVIEW_WIDGET + +#endif diff --git a/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui b/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui index 8af3c1c083..1c34f9572c 100644 --- a/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui +++ b/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui @@ -1,93 +1,90 @@ MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicator 0 0 124 22 0 0 32000 32000 Form1 Memory usage in % of physical memory 0 - + + 0 + + + 0 + + + 0 + + 0 - + 0 0 000,00 % - - Qt::AutoText - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true - + 20 20 - - 0 - - - QmitkApplicationBase/image0 - true - - false - mitkCommon.h string qpixmap.h diff --git a/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp b/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp index e5f61ab68d..8f58e4fc00 100644 --- a/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp +++ b/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp @@ -1,146 +1,131 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /**************************************************************************** ** ui.h extension file, included from the uic-generated form implementation. ** ** If you want to add, delete, or rename functions or slots, use ** Qt Designer to update this file, preserving your code. ** ** You should not define a constructor or destructor in this file. ** Instead, write your code in functions called init() and destroy(). ** These will automatically be called by the form's constructor and ** destructor. *****************************************************************************/ -#include "QmitkMemoryUsageIndicatorView.h" -#include +#include -#include -#include -#include -#include -#include +#include #include -#include -#include -#include "QmitkMemoryUsageIndicatorImagesGreen.xpm" -#include "QmitkMemoryUsageIndicatorImagesOrange.xpm" -#include "QmitkMemoryUsageIndicatorImagesRed.xpm" -#include "QmitkMemoryUsageIndicatorImagesYellow.xpm" +#include + +#include +#include +#include +#include + +#include -QmitkMemoryUsageIndicatorView::QmitkMemoryUsageIndicatorView(QWidget * /*parent*/, Qt::WindowFlags /*f*/) +std::array, 4> QmitkMemoryUsageIndicatorView::s_States = { + std::make_pair(0.0f, QPixmap(QmitkMemoryUsageIndicatorImagesGreen_xpm)), + std::make_pair(50.0f, QPixmap(QmitkMemoryUsageIndicatorImagesYellow_xpm)), + std::make_pair(65.0f, QPixmap(QmitkMemoryUsageIndicatorImagesOrange_xpm)), + std::make_pair(85.0f, QPixmap(QmitkMemoryUsageIndicatorImagesRed_xpm)) +}; + +QmitkMemoryUsageIndicatorView::QmitkMemoryUsageIndicatorView(QWidget*) + : m_Ui(new Ui::QmitkMemoryUsageIndicator), + m_PreviousState(0) { - this->setupUi(this); + m_Ui->setupUi(this); + m_Ui->led->setPixmap(s_States[0].second); auto timer = new QTimer(this); - QObject::connect(timer, SIGNAL(timeout()), this, SLOT(UpdateMemoryUsage())); + connect(timer, &QTimer::timeout, this, &QmitkMemoryUsageIndicatorView::UpdateMemoryUsage); timer->start(1000); - m_LEDGreen = QPixmap(QmitkMemoryUsageIndicatorImagesGreen_xpm); - m_LEDYellow = QPixmap(QmitkMemoryUsageIndicatorImagesYellow_xpm); - m_LEDOrange = QPixmap(QmitkMemoryUsageIndicatorImagesOrange_xpm); - m_LEDRed = QPixmap(QmitkMemoryUsageIndicatorImagesRed_xpm); - m_LED->setPixmap(m_LEDGreen); - m_PreviousState = 0; } QmitkMemoryUsageIndicatorView::~QmitkMemoryUsageIndicatorView() { } void QmitkMemoryUsageIndicatorView::UpdateMemoryUsage() { size_t processSize = mitk::MemoryUtilities::GetProcessMemoryUsage(); size_t totalSize = mitk::MemoryUtilities::GetTotalSizeOfPhysicalRam(); - float percentage = ((float)processSize / (float)totalSize) * 100.0; - m_Label->setText(GetMemoryDescription(processSize, percentage).c_str()); - if (percentage < 50.0) - { - if (m_PreviousState != 0) - { - m_LED->setPixmap(m_LEDGreen); - m_PreviousState = 0; - m_LED->update(); - } - } - else if (percentage < 65.0) - { - if (m_PreviousState != 1) - { - m_LED->setPixmap(m_LEDYellow); - m_PreviousState = 1; - m_LED->update(); - } - } - else if (percentage < 80.0) - { - if (m_PreviousState != 2) - { - m_LED->setPixmap(m_LEDOrange); - m_PreviousState = 2; - m_LED->update(); - } - } - else + float percentage = static_cast(processSize) / totalSize * 100.0f; + + m_Ui->label->setText(QString::fromStdString(this->GetMemoryDescription(processSize, percentage))); + + for (size_t i = s_States.size() - 1; i >= 0; --i) { - if (m_PreviousState != 3) + if (percentage >= s_States[i].first) { - m_LED->setPixmap(m_LEDRed); - m_PreviousState = 3; - m_LED->update(); + if (m_PreviousState != i) + { + m_Ui->led->setPixmap(s_States[i].second); + m_PreviousState = i; + } + + break; } } } std::string QmitkMemoryUsageIndicatorView::FormatMemorySize(size_t size) { double val = size; - std::string descriptor("B"); - if (val >= 1000.0) + std::string unit; + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "KB"; + unit = "K"; } - if (val >= 1000.0) + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "MB"; + unit = "M"; } - if (val >= 1000.0) + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "GB"; + unit = "G"; } + + unit += "B"; + std::ostringstream str; str.imbue(std::locale::classic()); - str << std::fixed << std::setprecision(2) << val << " " << descriptor; + str << std::fixed << std::setprecision(2) << val << " " << unit; return str.str(); } std::string QmitkMemoryUsageIndicatorView::FormatPercentage(double val) { std::ostringstream str; str.imbue(std::locale::classic()); - str << std::fixed << std::setprecision(2) << val << " " - << "%"; + str << std::fixed << std::setprecision(2) << val << " " << "%"; return str.str(); } std::string QmitkMemoryUsageIndicatorView::GetMemoryDescription(size_t processSize, float percentage) { std::ostringstream str; str.imbue(std::locale::classic()); str << FormatMemorySize(processSize) << " (" << FormatPercentage(percentage) << ")"; return str.str(); }