From b68bbded349a558084839bc30b977ebea1a4d531 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 31 Mar 2016 00:52:11 +0100 Subject: [PATCH 001/127] Add support for little and big endian with an option --- app/ConfigureFormatDialog.cpp | 44 +++++++++++++++++++++++++++----- app/ConfigureFormatDialog.h | 5 +++- app/VideoSubWindow.cpp | 14 +++++----- app/VideoSubWindow.h | 1 + lib/LibAvContextHandle.cpp | 6 ++--- lib/LibAvContextHandle.h | 2 +- lib/PlaYUVerDefs.h | 1 + lib/PlaYUVerFrame.cpp | 27 +++++++++++++++----- lib/PlaYUVerFrame.h | 2 +- lib/PlaYUVerStream.cpp | 15 ++++++----- lib/PlaYUVerStream.h | 5 ++-- tools/PlaYUVerTools.cpp | 14 +++++++++- tools/PlaYUVerToolsCmdParser.cpp | 1 + tools/PlaYUVerToolsCmdParser.h | 2 ++ 14 files changed, 104 insertions(+), 35 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index ab3caf4..89844c1 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -174,7 +174,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 1, 1 ); pixelGridLayout->addWidget( m_comboBoxPixelFormat, 1, 2 ); - QHBoxLayout* bitsPerPelLayout = new QHBoxLayout(); + QLabel* bitsPerPelLabel = new QLabel(); bitsPerPelLabel->setFont( normalFont ); bitsPerPelLabel->setText( "Pixel bit depth" ); @@ -187,6 +187,27 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : pixelGridLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 2, 1 ); pixelGridLayout->addWidget( m_spinBoxBits, 2, 2 ); + /* + * Endianess + */ + QHBoxLayout* endiannessLayout = new QHBoxLayout(); + QLabel* endiannessLabel = new QLabel(); + endiannessLabel->setFont( menusFont ); + endiannessLabel->setText( "Endianness" ); + QComboBox* endiannessComboBox = new QComboBox(); + endiannessComboBox->setFont( normalFont ); + endiannessComboBox->setSizePolicy( sizePolicy ); + endiannessComboBox->clear(); + endiannessComboBox->addItem( QStringLiteral("Big Endian") ); + endiannessComboBox->addItem( QStringLiteral("Little Endian") ); + endiannessComboBox->setCurrentIndex( 0 ); + endiannessLayout->addWidget( endiannessLabel ); + endiannessLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + endiannessLayout->addWidget( endiannessComboBox ); + m_widgetEndianness = new QWidget(); + m_widgetEndianness->setLayout( endiannessLayout ); + m_widgetEndianness->setVisible( true ); + /* * Frame rate format */ @@ -212,13 +233,11 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : dialogButtonOkCancel->setCenterButtons( false ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum ) ); - // MainLayout->addLayout( standardResolutionLayout ); - // MainLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Minimum ) ); MainLayout->addWidget( resolutionGroup ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum ) ); MainLayout->addWidget( pixelGroup ); - MainLayout->addLayout( bitsPerPelLayout ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum ) ); + MainLayout->addWidget( m_widgetEndianness ); MainLayout->addLayout( framerateFormatLayout ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum, QSizePolicy::Expanding ) ); MainLayout->addWidget( dialogButtonOkCancel ); @@ -226,8 +245,9 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : connect( m_comboBoxStandardResolution, SIGNAL( currentIndexChanged(int) ), this, SLOT( slotStandardResolutionSelected(int) ) ); connect( m_spinBoxWidth, SIGNAL( valueChanged(int) ), this, SLOT( slotResolutionChange() ) ); connect( m_spinBoxheight, SIGNAL( valueChanged(int) ), this, SLOT( slotResolutionChange() ) ); - connect( m_comboBoxColorSpace, SIGNAL( currentIndexChanged(int) ), this, SLOT( slotColorSpaceChange(int) ) ); + connect( m_spinBoxBits, SIGNAL( valueChanged(int) ), this, SLOT( slotBitsChange(int) ) ); + connect( dialogButtonOkCancel, SIGNAL( accepted() ), this, SLOT( accept() ) ); connect( dialogButtonOkCancel, SIGNAL( rejected() ), this, SLOT( reject() ) ); @@ -237,7 +257,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : } -Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rFrameRate ) +Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rEndianess, UInt& rFrameRate ) { // Set default values //setWindowTitle( "Configure resolution for " + Filename ); @@ -340,4 +360,16 @@ Void ConfigureFormatDialog::slotColorSpaceChange( Int idx ) m_comboBoxPixelFormat->setCurrentIndex( 0 ); } +Void ConfigureFormatDialog::slotBitsChange( Int idx ) +{ + if( idx > 8 ) + { + m_widgetEndianness->setVisible( true ); + } + else + { + m_widgetEndianness->setVisible( false ); + } +} + } // NAMESPACE diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index fe74524..60ecf56 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -50,12 +50,13 @@ Q_OBJECT public: ConfigureFormatDialog( QWidget *parent = 0 ); - Int runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rFrameRate ); + Int runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rEndianess, UInt& rFrameRate ); private Q_SLOTS: void slotStandardResolutionSelected( int ); void slotResolutionChange(); void slotColorSpaceChange( int ); + void slotBitsChange( int ); private: QStringList standardResolutionNames; @@ -68,6 +69,8 @@ private: QComboBox *m_comboBoxColorSpace; QComboBox *m_comboBoxPixelFormat; QSpinBox *m_spinBoxBits; + QWidget* m_widgetEndianness; + QHBoxLayout* framerateFormatLayout; QSpinBox *m_spinBoxFrameRate; }; diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 7e05ec1..ed23be0 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -51,6 +51,7 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStreamInfoVector& array << d.m_uiHeight << d.m_iPelFormat << d.m_uiBitsPelPixel + << d.m_uiEndianness << d.m_uiFrameRate << d.m_uiFileSize; } @@ -69,6 +70,7 @@ QDataStream& operator>>( QDataStream& in, PlaYUVerStreamInfoVector& array ) in >> d.m_uiHeight; in >> d.m_iPelFormat; in >> d.m_uiBitsPelPixel; + in >> d.m_uiEndianness; in >> d.m_uiFrameRate; in >> d.m_uiFileSize; array.append( d ); @@ -306,7 +308,7 @@ Void VideoSubWindow::refreshSubWindow() Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) { ConfigureFormatDialog formatDialog( this ); - UInt Width = 0, Height = 0, BitsPel = 8, FrameRate = 30; + UInt Width = 0, Height = 0, BitsPel = 8, Endianness = 0, FrameRate = 30; Int InputFormat = PlaYUVerFrame::YUV420p; if( m_pCurrStream ) @@ -319,7 +321,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) if( guessFormat( cFilename, Width, Height, InputFormat, FrameRate ) || bForceDialog ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) { return false; } @@ -327,15 +329,15 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) try { - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, FrameRate ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ); } catch( const char *msg ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) { return false; } - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, FrameRate ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ); } m_sStreamInfo.m_cFilename = cFilename; @@ -365,7 +367,7 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) } if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, streamInfo->m_iPelFormat, - streamInfo->m_uiBitsPelPixel, streamInfo->m_uiFrameRate ) ) + streamInfo->m_uiBitsPelPixel, streamInfo->m_uiEndianness, streamInfo->m_uiFrameRate ) ) { return false; } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index c2f0928..33cbc18 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -52,6 +52,7 @@ typedef struct UInt m_uiHeight; Int m_iPelFormat; UInt m_uiBitsPelPixel; + UInt m_uiEndianness; UInt m_uiFrameRate; UInt64 m_uiFileSize; } PlaYUVerStreamInfo; diff --git a/lib/LibAvContextHandle.cpp b/lib/LibAvContextHandle.cpp index 20c0617..7324a12 100644 --- a/lib/LibAvContextHandle.cpp +++ b/lib/LibAvContextHandle.cpp @@ -112,7 +112,7 @@ Void LibAvContextHandle::closeAvFormat() m_bHasStream = false; } -Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Double& frame_rate, +Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& endianness, UInt& bits_pel, Double& frame_rate, UInt64& num_frames ) { fmt_ctx = NULL; @@ -177,9 +177,9 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } - const char *name = avcodec_get_name( video_dec_ctx->codec_id ); + const char *name = avcodec_get_name( video_dec_ctx->codec_id ); sprintf( m_acCodecName, "%s", name ); - + Double fr = 30; if( video_stream->avg_frame_rate.den && video_stream->avg_frame_rate.num ) fr = av_q2d( video_stream->avg_frame_rate ); diff --git a/lib/LibAvContextHandle.h b/lib/LibAvContextHandle.h index 0f44828..4b4ba50 100644 --- a/lib/LibAvContextHandle.h +++ b/lib/LibAvContextHandle.h @@ -65,7 +65,7 @@ public: m_bHasStream( false ) { } - Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Double& frame_rate, UInt64& num_frames ); + Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, UInt& endianness, Double& frame_rate, UInt64& num_frames ); Void closeAvFormat(); Bool decodeAvFormat(); diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 7f0893d..a37c383 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -119,6 +119,7 @@ enum RGBcomponent COLOR_A, }; + inline std::string lowercase( const std::string& in ) { std::string out; diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index d03248f..b23c6d1 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -174,7 +174,7 @@ Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel m_iNumberChannels = 3; m_uiBitsPel = bitsPixel > 8 ? bitsPixel : 8; m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); - + if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) { throw "Cannot create a PlYUVerFrame of this type"; @@ -385,18 +385,30 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) m_bHasHistogram = false; } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) +Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize, Int endianess ) { if( uiBuffSize != getBytesPerFrame() ) return; Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; - Pel* pTmpPel; + Pel* pPel; UInt bytesPixel = ( m_uiBitsPel - 1 ) / 8 + 1; + UInt shiftInput, shiftOutput; Int ratioH, ratioW, step; UInt i, ch, b; + if( endianess == 1 ) + { + shiftInput = 8; + shiftOutput = 0; + } + else + { + shiftInput = 0; + shiftOutput = 8; + } + ppBuff[0] = Buff; for( i = 1; i < MAX_NUMBER_PLANES; i++ ) { @@ -411,18 +423,18 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; step = m_pcPelFormat->comp[ch].step_minus1 + 1; - pTmpPel = m_pppcInputPel[ch][0]; + pPel = m_pppcInputPel[ch][0]; pTmpBuff = ppBuff[m_pcPelFormat->comp[ch].plane] + ( m_pcPelFormat->comp[ch].offset_plus1 - 1 ); for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) { - *pTmpPel = *pTmpBuff; + *pPel = *pTmpBuff; for( b = 1; b < bytesPixel; b++ ) { pTmpBuff++; - *pTmpPel |= ( *pTmpBuff << ( 8 * b ) ); + *pPel = ( *pPel << shiftOutput ) + ( *pTmpBuff << shiftInput ); } - pTmpPel++; + pPel++; pTmpBuff += step; } } @@ -1186,3 +1198,4 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) } } // NAMESPACE + diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 33ea961..7a6946a 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -211,7 +211,7 @@ public: Void copyFrom( PlaYUVerFrame* ); Void copyFrom( PlaYUVerFrame*, UInt, UInt ); - Void frameFromBuffer( Byte*, UInt64 ); + Void frameFromBuffer( Byte*, UInt64, Int ); Void frameToBuffer( Byte* ); Void fillRGBBuffer(); diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 0aa9ab2..853ef27 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -190,7 +190,7 @@ Void PlaYUVerStream::findHandler() } } -Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput ) { UInt width; UInt height; @@ -212,10 +212,10 @@ Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::st break; } } - return open( filename, width, height, input_format, bitsPel, frame_rate, bInput ); + return open( filename, width, height, input_format, bitsPel, endianness, frame_rate, bInput ); } -Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput ) { if( m_bInit ) { @@ -228,6 +228,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_uiHeight = height; m_iPixelFormat = input_format; m_uiBitsPerPixel = bitsPel; + m_uiEndianness = endianness; m_dFrameRate = frame_rate; m_pchFilename = new Char[m_cFilename.size() + 1]; @@ -247,7 +248,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in #ifdef USE_FFMPEG if( m_iStreamHandler == FFMPEG ) { - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_dFrameRate, m_uiTotalFrameNum ) ) + if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_uiEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) { throw "Cannot open file using FFmpeg libs"; } @@ -370,7 +371,7 @@ Bool PlaYUVerStream::reload() if( m_iStreamHandler == FFMPEG ) { m_cLibAvContext->closeAvFormat(); - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_dFrameRate, m_uiTotalFrameNum ) ) + if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_uiEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) { throw "Cannot open file using FFmpeg libs"; } @@ -578,7 +579,7 @@ Void PlaYUVerStream::readFrame() throw "[PlaYUVerStream] Error reading frame from libav"; return; } - m_pcNextFrame->frameFromBuffer( m_cLibAvContext->m_pchFrameBuffer, m_cLibAvContext->m_uiFrameBufferSize ); + m_pcNextFrame->frameFromBuffer( m_cLibAvContext->m_pchFrameBuffer, m_cLibAvContext->m_uiFrameBufferSize, m_uiEndianness ); } #endif if( m_iStreamHandler == YUV_IO ) @@ -590,7 +591,7 @@ Void PlaYUVerStream::readFrame() throw "[PlaYUVerStream] Cannot read file"; return; } - m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, bytes_read ); + m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, bytes_read, m_uiEndianness ); } m_uiCurrFrameFileIdx++; return; diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index c4d83ae..d0e65b2 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -95,8 +95,8 @@ public: END_OF_SEQ, }; - Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, UInt frame_rate, Bool bInput = true ); - Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt frame_rate, Bool bInput = true ); + Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput = true ); + Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput = true ); Bool reload(); @@ -194,6 +194,7 @@ private: UInt m_uiHeight; Int m_iPixelFormat; UInt m_uiBitsPerPixel; + UInt m_uiEndianness; Double m_dFrameRate; UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index fac4f5e..30a684d 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -76,6 +76,18 @@ Int PlaYUVerTools::openInputs() { uiBitPerPixel = m_cCmdLineHandler.m_uiBitsPerPixel; } + UInt uiEndianness = 0; + if( m_cCmdLineHandler.Opts()["endianness"]->count() ) + { + if( m_cCmdLineHandler.m_strEndianness == "big" ) + { + uiEndianness = 0; + } + if( m_cCmdLineHandler.m_strEndianness == "little" ) + { + uiEndianness = 1; + } + } std::vector inputFileNames = m_cCmdLineHandler.m_apcInputs; @@ -85,7 +97,7 @@ Int PlaYUVerTools::openInputs() pcStream = new PlaYUVerStream; try { - if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, 1 ) ) + if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, uiEndianness, 1 ) ) { m_cCmdLineHandler.log( LOG_ERROR, "Cannot open input stream %s! ", inputFileNames[i].c_str() ); return 2; diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index a8d122c..bd09dfe 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -71,6 +71,7 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) ( "size,s", m_strResolution, "size (WxH)" ) /**/ ( "pel_fmt", m_strPelFmt, "pixel format" ) /**/ ( "bits_pel", m_uiBitsPerPixel, "bits per pixel" ) /**/ + ( "endianness", m_strEndianness, "File endianness (big, little)" ) /**/ ( "frames,f", m_iFrames, "number of frames to parse" ); Opts().addOptions()/**/ diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 93550cf..8a61bb1 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -78,6 +78,8 @@ private: std::string m_strResolution; std::string m_strPelFmt; UInt m_uiBitsPerPixel; + std::string m_strEndianness; + UInt m_uiEndianness; Bool m_bListPelFmts; Int64 m_iFrames; From 22ddfa65aafb2eb77705398d3ef38133b9dfaf18 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 1 Apr 2016 00:44:37 +0100 Subject: [PATCH 002/127] Fix apperance of ConfigureFormatDialog --- app/ConfigureFormatDialog.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 89844c1..4eb157f 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -205,6 +205,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : endiannessLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); endiannessLayout->addWidget( endiannessComboBox ); m_widgetEndianness = new QWidget(); + m_widgetEndianness->setContentsMargins( 0,0,0,0 ); m_widgetEndianness->setLayout( endiannessLayout ); m_widgetEndianness->setVisible( true ); @@ -223,6 +224,10 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : framerateFormatLayout->addWidget( framerateFormatLabel ); framerateFormatLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); framerateFormatLayout->addWidget( m_spinBoxFrameRate ); + QWidget* framerateWidget = new QWidget(); + framerateWidget->setContentsMargins( 0,0,0,0 ); + framerateWidget->setLayout( framerateFormatLayout ); + /* * Confirmation buttons @@ -238,7 +243,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : MainLayout->addWidget( pixelGroup ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum ) ); MainLayout->addWidget( m_widgetEndianness ); - MainLayout->addLayout( framerateFormatLayout ); + MainLayout->addWidget( framerateWidget ); MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum, QSizePolicy::Expanding ) ); MainLayout->addWidget( dialogButtonOkCancel ); @@ -286,6 +291,14 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWi m_comboBoxColorSpace->setCurrentIndex( colorSpace ); m_comboBoxPixelFormat->setCurrentIndex( sampling ); m_spinBoxBits->setValue( rBits ); + if( rBits > 8 ) + { + m_widgetEndianness->setVisible( true ); + } + else + { + m_widgetEndianness->setVisible( false ); + } m_spinBoxFrameRate->setValue( rFrameRate ); for( Int i = 0; i < standardResolutionSizes.size(); i++ ) { From 8b154a2808358e9682ec5da9d40573fc80c616df Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 1 Apr 2016 10:16:28 +0100 Subject: [PATCH 003/127] Fix minor bugs in PlaYUVerStream --- app/VideoSubWindow.cpp | 2 +- lib/PlaYUVerStream.cpp | 4 +++- lib/PlaYUVerStream.h | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index ed23be0..8374048 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -312,7 +312,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) Int InputFormat = PlaYUVerFrame::YUV420p; if( m_pCurrStream ) - m_pCurrStream->getFormat( Width, Height, InputFormat, BitsPel, FrameRate ); + m_pCurrStream->getFormat( Width, Height, InputFormat, BitsPel, Endianness, FrameRate ); if( !m_pCurrStream ) { diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 853ef27..d4a3c49 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -462,7 +462,7 @@ Void PlaYUVerStream::close() m_bInit = false; } -Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rFrameRate ) +Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rEndianness, UInt& rFrameRate ) { if( m_bInit ) { @@ -470,6 +470,7 @@ Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, rHeight = m_uiHeight; rInputFormat = m_iPixelFormat; rBitsPerPel = m_uiBitsPerPixel; + rEndianness = m_uiEndianness; rFrameRate = m_dFrameRate; } else @@ -478,6 +479,7 @@ Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, rHeight = 0; rInputFormat = PlaYUVerFrame::YUV420p; rBitsPerPel = 8; + rEndianness = 0; rFrameRate = 30; } } diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index d0e65b2..27f5d82 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -105,7 +105,7 @@ public: Bool openFile(); Void closeFile(); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rFrameRate ); + Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rEndianness, UInt& rFrameRate ); Void loadAll(); From 6449412206a42e42b7b9bf04e3d57117e2bddb8e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 1 Apr 2016 12:13:20 +0100 Subject: [PATCH 004/127] Change endianness to Int --- app/ConfigureFormatDialog.cpp | 19 ++++++++++--------- app/ConfigureFormatDialog.h | 3 ++- app/VideoSubWindow.cpp | 3 ++- lib/LibAvContextHandle.cpp | 2 +- lib/LibAvContextHandle.h | 2 +- lib/PlaYUVerStream.cpp | 19 ++++++++++--------- lib/PlaYUVerStream.h | 8 ++++---- 7 files changed, 30 insertions(+), 26 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 4eb157f..4df7fe1 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -194,16 +194,15 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : QLabel* endiannessLabel = new QLabel(); endiannessLabel->setFont( menusFont ); endiannessLabel->setText( "Endianness" ); - QComboBox* endiannessComboBox = new QComboBox(); - endiannessComboBox->setFont( normalFont ); - endiannessComboBox->setSizePolicy( sizePolicy ); - endiannessComboBox->clear(); - endiannessComboBox->addItem( QStringLiteral("Big Endian") ); - endiannessComboBox->addItem( QStringLiteral("Little Endian") ); - endiannessComboBox->setCurrentIndex( 0 ); + m_comboBoxEndianness = new QComboBox(); + m_comboBoxEndianness->setFont( normalFont ); + m_comboBoxEndianness->setSizePolicy( sizePolicy ); + m_comboBoxEndianness->clear(); + m_comboBoxEndianness->addItem( QStringLiteral("Big Endian") ); + m_comboBoxEndianness->addItem( QStringLiteral("Little Endian") ); endiannessLayout->addWidget( endiannessLabel ); endiannessLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); - endiannessLayout->addWidget( endiannessComboBox ); + endiannessLayout->addWidget( m_comboBoxEndianness ); m_widgetEndianness = new QWidget(); m_widgetEndianness->setContentsMargins( 0,0,0,0 ); m_widgetEndianness->setLayout( endiannessLayout ); @@ -262,7 +261,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : } -Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rEndianess, UInt& rFrameRate ) +Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ) { // Set default values //setWindowTitle( "Configure resolution for " + Filename ); @@ -291,6 +290,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWi m_comboBoxColorSpace->setCurrentIndex( colorSpace ); m_comboBoxPixelFormat->setCurrentIndex( sampling ); m_spinBoxBits->setValue( rBits ); + m_comboBoxEndianness->setCurrentIndex( rEndianess ); if( rBits > 8 ) { m_widgetEndianness->setVisible( true ); @@ -326,6 +326,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWi } } rBits = m_spinBoxBits->value(); + rEndianess = m_comboBoxEndianness->currentIndex(); rFrameRate = m_spinBoxFrameRate->value(); return QDialog::Accepted; } diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index 60ecf56..660a1d9 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -50,7 +50,7 @@ Q_OBJECT public: ConfigureFormatDialog( QWidget *parent = 0 ); - Int runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, UInt& rEndianess, UInt& rFrameRate ); + Int runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ); private Q_SLOTS: void slotStandardResolutionSelected( int ); @@ -70,6 +70,7 @@ private: QComboBox *m_comboBoxPixelFormat; QSpinBox *m_spinBoxBits; QWidget* m_widgetEndianness; + QComboBox* m_comboBoxEndianness; QHBoxLayout* framerateFormatLayout; QSpinBox *m_spinBoxFrameRate; diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 8374048..50385da 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -308,7 +308,8 @@ Void VideoSubWindow::refreshSubWindow() Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) { ConfigureFormatDialog formatDialog( this ); - UInt Width = 0, Height = 0, BitsPel = 8, Endianness = 0, FrameRate = 30; + UInt Width = 0, Height = 0, BitsPel = 8, FrameRate = 30; + Int Endianness = 0; Int InputFormat = PlaYUVerFrame::YUV420p; if( m_pCurrStream ) diff --git a/lib/LibAvContextHandle.cpp b/lib/LibAvContextHandle.cpp index 7324a12..18f836d 100644 --- a/lib/LibAvContextHandle.cpp +++ b/lib/LibAvContextHandle.cpp @@ -112,7 +112,7 @@ Void LibAvContextHandle::closeAvFormat() m_bHasStream = false; } -Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& endianness, UInt& bits_pel, Double& frame_rate, +Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, UInt64& num_frames ) { fmt_ctx = NULL; diff --git a/lib/LibAvContextHandle.h b/lib/LibAvContextHandle.h index 4b4ba50..57cbc9f 100644 --- a/lib/LibAvContextHandle.h +++ b/lib/LibAvContextHandle.h @@ -65,7 +65,7 @@ public: m_bHasStream( false ) { } - Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, UInt& endianness, Double& frame_rate, UInt64& num_frames ); + Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, UInt64& num_frames ); Void closeAvFormat(); Bool decodeAvFormat(); diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index d4a3c49..dc7c928 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -116,6 +116,7 @@ PlaYUVerStream::PlaYUVerStream() m_iCurrFrameNum = -1; m_iPixelFormat = -1; m_uiBitsPerPixel = 8; + m_iEndianness = -1; m_dFrameRate = 30; m_pStreamBuffer = NULL; m_cFilename = ""; @@ -190,7 +191,7 @@ Void PlaYUVerStream::findHandler() } } -Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { UInt width; UInt height; @@ -215,7 +216,7 @@ Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::st return open( filename, width, height, input_format, bitsPel, endianness, frame_rate, bInput ); } -Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { if( m_bInit ) { @@ -228,7 +229,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_uiHeight = height; m_iPixelFormat = input_format; m_uiBitsPerPixel = bitsPel; - m_uiEndianness = endianness; + m_iEndianness = endianness; m_dFrameRate = frame_rate; m_pchFilename = new Char[m_cFilename.size() + 1]; @@ -248,7 +249,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in #ifdef USE_FFMPEG if( m_iStreamHandler == FFMPEG ) { - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_uiEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) + if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) { throw "Cannot open file using FFmpeg libs"; } @@ -371,7 +372,7 @@ Bool PlaYUVerStream::reload() if( m_iStreamHandler == FFMPEG ) { m_cLibAvContext->closeAvFormat(); - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_uiEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) + if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) { throw "Cannot open file using FFmpeg libs"; } @@ -462,7 +463,7 @@ Void PlaYUVerStream::close() m_bInit = false; } -Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rEndianness, UInt& rFrameRate ) +Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ) { if( m_bInit ) { @@ -470,7 +471,7 @@ Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, rHeight = m_uiHeight; rInputFormat = m_iPixelFormat; rBitsPerPel = m_uiBitsPerPixel; - rEndianness = m_uiEndianness; + rEndianness = m_iEndianness; rFrameRate = m_dFrameRate; } else @@ -581,7 +582,7 @@ Void PlaYUVerStream::readFrame() throw "[PlaYUVerStream] Error reading frame from libav"; return; } - m_pcNextFrame->frameFromBuffer( m_cLibAvContext->m_pchFrameBuffer, m_cLibAvContext->m_uiFrameBufferSize, m_uiEndianness ); + m_pcNextFrame->frameFromBuffer( m_cLibAvContext->m_pchFrameBuffer, m_cLibAvContext->m_uiFrameBufferSize, m_iEndianness ); } #endif if( m_iStreamHandler == YUV_IO ) @@ -593,7 +594,7 @@ Void PlaYUVerStream::readFrame() throw "[PlaYUVerStream] Cannot read file"; return; } - m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, bytes_read, m_uiEndianness ); + m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, bytes_read, m_iEndianness ); } m_uiCurrFrameFileIdx++; return; diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 27f5d82..3861958 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -95,8 +95,8 @@ public: END_OF_SEQ, }; - Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput = true ); - Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, UInt endianness, UInt frame_rate, Bool bInput = true ); + Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); + Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); Bool reload(); @@ -105,7 +105,7 @@ public: Bool openFile(); Void closeFile(); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, UInt& rEndianness, UInt& rFrameRate ); + Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ); Void loadAll(); @@ -194,7 +194,7 @@ private: UInt m_uiHeight; Int m_iPixelFormat; UInt m_uiBitsPerPixel; - UInt m_uiEndianness; + Int m_iEndianness; Double m_dFrameRate; UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; From e81030947a499a56b52e868dd4dcf475fa0d1ce8 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 1 Apr 2016 12:13:54 +0100 Subject: [PATCH 005/127] Change endianness to Int --- lib/LibAvContextHandle.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/LibAvContextHandle.cpp b/lib/LibAvContextHandle.cpp index 18f836d..bd095f4 100644 --- a/lib/LibAvContextHandle.cpp +++ b/lib/LibAvContextHandle.cpp @@ -231,8 +231,13 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& pix_fmt = AV_PIX_FMT_YUV444P; break; case AV_PIX_FMT_GRAY16LE: + bits_pel = 16; + endianness = 1; + pix_fmt = AV_PIX_FMT_GRAY8; + break; case AV_PIX_FMT_GRAY16BE: bits_pel = 16; + endianness = 0; pix_fmt = AV_PIX_FMT_GRAY8; break; } From 5f9533b212e018c0cadc1d1a4eb2537b063a2d72 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 1 Apr 2016 23:13:08 +0100 Subject: [PATCH 006/127] Add PlaYUVerStreamHandlerI class Different classes are used to read and write streams with a common interface --- lib/CMakeLists.txt | 2 +- lib/PlaYUVerFrame.cpp | 2 +- lib/PlaYUVerFramePixelFormats.cpp | 2 +- lib/PlaYUVerStream.cpp | 294 +++++++----------- lib/PlaYUVerStream.h | 26 +- lib/PlaYUVerStreamHandlerIf.h | 85 +++++ ...ntextHandle.cpp => StreamHandlerLibav.cpp} | 235 +++++++------- ...AvContextHandle.h => StreamHandlerLibav.h} | 55 ++-- lib/StreamHandlerRaw.h | 101 ++++++ 9 files changed, 464 insertions(+), 338 deletions(-) create mode 100644 lib/PlaYUVerStreamHandlerIf.h rename lib/{LibAvContextHandle.cpp => StreamHandlerLibav.cpp} (57%) rename lib/{LibAvContextHandle.h => StreamHandlerLibav.h} (69%) create mode 100644 lib/StreamHandlerRaw.h diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 43df34e..f5c8397 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -18,7 +18,7 @@ set(PlaYUVer_Lib_SRCS ) IF( USE_FFMPEG ) - LIST( APPEND PlaYUVer_Lib_SRCS LibAvContextHandle.cpp ) + LIST( APPEND PlaYUVer_Lib_SRCS StreamHandlerLibav.cpp ) ENDIF() IF( USE_OPENCV ) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index b23c6d1..b2620c6 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -30,7 +30,7 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" #ifdef USE_FFMPEG -#include "LibAvContextHandle.h" +#include "StreamHandlerLibav.h" #endif #ifdef USE_OPENCV #include "LibOpenCVHandler.h" diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index c37d74f..95d7b44 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -32,7 +32,7 @@ #include #endif #ifdef USE_FFMPEG -#include "LibAvContextHandle.h" +#include "StreamHandlerLibav.h" #endif #include "PlaYUVerFramePixelFormats.h" diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index dc7c928..36d0b45 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -28,8 +28,11 @@ #include #include "LibMemory.h" #include "PlaYUVerStream.h" +#include "PlaYUVerStreamHandlerIf.h" +#include "StreamHandlerRaw.h" + #ifdef USE_FFMPEG -#include "LibAvContextHandle.h" +#include "StreamHandlerLibav.h" #endif #ifdef USE_OPENCV #include "LibOpenCVHandler.h" @@ -44,7 +47,7 @@ std::vector PlaYUVerStream::supportedReadFormats() REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "gray" ); #ifdef USE_FFMPEG - APPEND_PLAYUVER_SUPPORTED_FMT( LibAvContextHandle, Read ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Read ); #endif //#ifdef USE_OPENCV // APPEND_PLAYUVER_SUPPORTED_FMT( LibOpenCVHandler ); @@ -57,7 +60,7 @@ std::vector PlaYUVerStream::supportedWriteFormats() INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "yuv" ); #ifdef USE_FFMPEG - APPEND_PLAYUVER_SUPPORTED_FMT( LibAvContextHandle, Write ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Write ); #endif END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -67,7 +70,7 @@ std::vector PlaYUVerStream::supportedSaveFormats() INI_REGIST_PLAYUVER_SUPPORTED_FMT; APPEND_PLAYUVER_SUPPORTED_FMT( PlaYUVerStream, Write ); #ifdef USE_FFMPEG - APPEND_PLAYUVER_SUPPORTED_FMT( LibAvContextHandle, Save ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Save ); #endif #ifdef USE_OPENCV APPEND_PLAYUVER_SUPPORTED_FMT( LibOpenCVHandler, Save ); @@ -108,7 +111,7 @@ PlaYUVerStream::PlaYUVerStream() m_bIsOpened = false; m_bLoadAll = false; m_iStreamHandler = INVALID_HANDLER; - m_pFile = NULL; + m_pcStreamHandler = NULL; m_pchFilename = NULL; m_uiWidth = 0; m_uiHeight = 0; @@ -126,18 +129,27 @@ PlaYUVerStream::PlaYUVerStream() m_uiFrameBufferSize = 2; m_uiFrameBufferIndex = 0; m_uiCurrFrameFileIdx = 0; -#ifdef USE_FFMPEG - m_cLibAvContext = new LibAvContextHandle; -#endif +// #ifdef USE_FFMPEG +// m_cLibAvContext = new StreamHandlerLibav; +// #endif } PlaYUVerStream::~PlaYUVerStream() { close(); -#ifdef USE_FFMPEG - if( m_cLibAvContext ) - delete m_cLibAvContext; -#endif +// #ifdef USE_FFMPEG +// if( m_cLibAvContext ) +// delete m_cLibAvContext; +// #endif +} + +std::string PlaYUVerStream::getFormatName() +{ + return !m_pcStreamHandler ? "" : m_pcStreamHandler->getFormatName(); +} +std::string PlaYUVerStream::getCodecName() +{ + return !m_pcStreamHandler ? "" : m_pcStreamHandler->getCodecName(); } Void PlaYUVerStream::findHandler() @@ -156,12 +168,12 @@ Void PlaYUVerStream::findHandler() if( m_bIsInput ) { #ifdef USE_FFMPEG - std::vector supportedFmts = LibAvContextHandle::supportedReadFormats(); + std::vector supportedFmts = StreamHandlerLibav::supportedReadFormats(); for( UInt i = 0; i < supportedFmts.size(); i++ ) { if( supportedFmts[i].formatExt == currExt ) { - m_cFormatName = uppercase( supportedFmts[i].formatExt ); + //m_cFormatName = uppercase( supportedFmts[i].formatExt ); m_iStreamHandler = FFMPEG; return; } @@ -173,12 +185,12 @@ Void PlaYUVerStream::findHandler() else { #ifdef USE_FFMPEG - std::vector supportedFmts = LibAvContextHandle::supportedWriteFormats(); + std::vector supportedFmts = StreamHandlerLibav::supportedWriteFormats(); for( UInt i = 0; i < supportedFmts.size(); i++ ) { if( supportedFmts[i].formatExt == currExt ) { - m_cFormatName = uppercase( supportedFmts[i].formatExt ); +// m_cFormatName = uppercase( supportedFmts[i].formatExt ); m_iStreamHandler = FFMPEG; return; } @@ -246,17 +258,6 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_uiFrameBufferSize = m_bIsInput ? 2 : 1; -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) - { - throw "Cannot open file using FFmpeg libs"; - } - m_cCodedName = m_cLibAvContext->getCodecName(); - } -#endif - #ifdef USE_OPENCV if( m_iStreamHandler == OPENCV_HANDLER ) { @@ -267,9 +268,38 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_uiHeight = m_pcCurrFrame->getHeight(); m_iPixelFormat = m_pcCurrFrame->getPelFormat(); } + m_pcNextFrame = NULL; + m_uiFrameBufferSize = 0; + m_uiFrameBufferIndex = 0; + m_uiTotalFrameNum = 1; } #endif +#ifdef USE_FFMPEG + if( m_iStreamHandler == FFMPEG ) + { + m_pcStreamHandler = new StreamHandlerLibav; + } +#endif + if( m_iStreamHandler == YUV_IO ) + { + m_pcStreamHandler = new PlaYUVerRawHandler; + } + + if( !m_pcStreamHandler ) + { + close(); + throw "[PlaYUVerStream] Invalid handler"; + } + + if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) + { + close(); + throw "[PlaYUVerStream] Cannot open file"; + return m_bInit; + } + m_pcStreamHandler->getFormat( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate ); + if( m_uiWidth <= 0 || m_uiHeight <= 0 || m_iPixelFormat < 0 ) { close(); @@ -277,62 +307,28 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in return m_bInit; } - if( m_iStreamHandler != OPENCV_HANDLER ) + getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); + for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) { - if( m_iStreamHandler == YUV_IO ) + try { - if( !openFile() ) - { - close(); - throw "[PlaYUVerStream] Cannot open file"; - return m_bInit; - } - m_cFormatName = "YUV"; - m_cCodedName = "Raw Video"; + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel ); } - - getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); - for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) + catch( const char *msg ) { - try - { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel ); - } - catch( const char *msg ) - { - close(); - throw "[PlaYUVerStream] Cannot allocated frame buffer"; - return m_bInit; - } - } - m_uiFrameBufferIndex = 0; - m_pcCurrFrame = m_ppcFrameBuffer[m_uiFrameBufferIndex]; - - UInt64 frame_bytes_input = m_pcCurrFrame->getBytesPerFrame(); - - if( m_iStreamHandler == YUV_IO && m_bIsInput ) - { - fseek( m_pFile, 0, SEEK_END ); - UInt64 fileSize = ftell( m_pFile ); -#if 0 - if( fileSize % frame_bytes_input ) - { - Int remaining = fileSize % frame_bytes_input; - close(); - throw "[PlaYUVerStream] Incorrect configuration: failed ( fileSize % frame_bytes_input = " << remaining << " )"; - return m_bInit; - } -#endif - m_uiTotalFrameNum = fileSize / frame_bytes_input; - fseek( m_pFile, 0, SEEK_SET ); + close(); + throw "[PlaYUVerStream] Cannot allocated frame buffer"; + return m_bInit; } } - else + m_uiFrameBufferIndex = 0; + m_pcCurrFrame = m_ppcFrameBuffer[m_uiFrameBufferIndex]; + + m_pcStreamHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); + + if( m_bIsInput ) { - m_pcNextFrame = NULL; - m_uiFrameBufferSize = 0; - m_uiFrameBufferIndex = 0; - m_uiTotalFrameNum = 1; + m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); } if( m_bIsInput && m_uiTotalFrameNum <= 0 ) @@ -368,30 +364,16 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in Bool PlaYUVerStream::reload() { -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - m_cLibAvContext->closeAvFormat(); - if( !m_cLibAvContext->initAvFormat( m_pchFilename, m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate, m_uiTotalFrameNum ) ) + m_pcStreamHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); + + m_pcStreamHandler->closeHandler(); + if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) { - throw "Cannot open file using FFmpeg libs"; + throw "[PlaYUVerStream] Cannot open file using FFmpeg libs"; } - m_cCodedName = m_cLibAvContext->getCodecName(); - } -#endif - if( m_iStreamHandler == YUV_IO ) - { - closeFile(); - if( !openFile() ) - { - return false; - } - UInt64 frameBytesInput = m_pcCurrFrame->getBytesPerFrame(); - fseek( m_pFile, 0, SEEK_END ); - UInt64 fileSize = ftell( m_pFile ); - m_uiTotalFrameNum = fileSize / frameBytesInput; - fseek( m_pFile, 0, SEEK_SET ); - } + m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); + + if( m_uiWidth <= 0 || m_uiHeight <= 0 || m_iPixelFormat < 0 || m_uiTotalFrameNum < 1 ) { return false; @@ -406,40 +388,14 @@ Bool PlaYUVerStream::reload() return true; } -Bool PlaYUVerStream::openFile() -{ -//m_fsIOStream.open( m_cFilename, std::ios::in | std::ios::binary ) - m_pFile = NULL; - m_pFile = fopen( m_pchFilename, m_bIsInput ? "rb" : "wb" ); - if( m_pFile == NULL ) - { - return false; - } - if( m_bIsInput ) - { - fseek( m_pFile, m_iCurrFrameNum >= 0 ? m_iCurrFrameNum : 0, SEEK_SET ); - } - return true; -} - -Void PlaYUVerStream::closeFile() -{ - if( m_pFile ) - fclose( m_pFile ); -} - Void PlaYUVerStream::close() { if( !m_bInit ) return; - if( m_iStreamHandler == YUV_IO ) - closeFile(); + m_pcStreamHandler->closeHandler(); + -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - m_cLibAvContext->closeAvFormat(); -#endif if( m_ppcFrameBuffer ) { @@ -529,25 +485,25 @@ Void PlaYUVerStream::loadAll() Void PlaYUVerStream::getDuration( Int* duration_array ) { - Int hours, mins, secs = 0; -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - secs = m_cLibAvContext->getStreamDuration(); - } - else -#endif - if( m_iStreamHandler == YUV_IO ) - { - secs = m_uiTotalFrameNum / m_dFrameRate; - } - mins = secs / 60; - secs %= 60; - hours = mins / 60; - mins %= 60; - *duration_array++ = hours; - *duration_array++ = mins; - *duration_array++ = secs; +// Int hours, mins, secs = 0; +// #ifdef USE_FFMPEG +// if( m_iStreamHandler == FFMPEG ) +// { +// secs = m_cLibAvContext->getStreamDuration(); +// } +// else +// #endif +// if( m_iStreamHandler == YUV_IO ) +// { +// secs = m_uiTotalFrameNum / m_dFrameRate; +// } +// mins = secs / 60; +// secs %= 60; +// hours = mins / 60; +// mins %= 60; +// *duration_array++ = hours; +// *duration_array++ = mins; +// *duration_array++ = secs; } Void PlaYUVerStream::readFrameFillRGBBuffer() @@ -574,28 +530,16 @@ Void PlaYUVerStream::readFrame() return; } -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - if( !m_cLibAvContext->decodeAvFormat() ) - { - throw "[PlaYUVerStream] Error reading frame from libav"; - return; - } - m_pcNextFrame->frameFromBuffer( m_cLibAvContext->m_pchFrameBuffer, m_cLibAvContext->m_uiFrameBufferSize, m_iEndianness ); - } -#endif - if( m_iStreamHandler == YUV_IO ) - { - UInt64 frame_bytes_input = m_pcNextFrame->getBytesPerFrame(); - UInt64 bytes_read = fread( m_pStreamBuffer, sizeof(Byte), frame_bytes_input, m_pFile ); - if( bytes_read != frame_bytes_input ) + UInt64 uiByterPerFrame = m_pcNextFrame->getBytesPerFrame(); + + + if( !m_pcStreamHandler->read( m_pStreamBuffer ) ) { throw "[PlaYUVerStream] Cannot read file"; return; } - m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, bytes_read, m_iEndianness ); - } + m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, uiByterPerFrame, m_iEndianness ); + m_uiCurrFrameFileIdx++; return; } @@ -609,10 +553,8 @@ Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) { if( m_iStreamHandler == YUV_IO ) { - UInt64 frame_bytes_input = pcFrame->getBytesPerFrame(); pcFrame->frameToBuffer( m_pStreamBuffer ); - UInt64 bytes_read = fwrite( m_pStreamBuffer, sizeof(Byte), frame_bytes_input, m_pFile ); - if( bytes_read != frame_bytes_input ) + if( !m_pcStreamHandler->write( m_pStreamBuffer ) ) { throw "[PlaYUVerStream] Cannot write into the file"; } @@ -755,24 +697,12 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) setNextFrame(); return true; } - if( m_iStreamHandler == OPENCV_HANDLER ) + + if( !m_pcStreamHandler->seek( new_frame_num ) ) { - return true; - } -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - m_cLibAvContext->seekAvFormat( new_frame_num ); - } -#endif - if( m_iStreamHandler == YUV_IO ) - { - if( !m_pFile ) - return false; - UInt64 frame_bytes_input = m_ppcFrameBuffer[0]->getBytesPerFrame(); - UInt64 nbytes_seek = frame_bytes_input * new_frame_num; - fseek( m_pFile, nbytes_seek, SEEK_SET ); + throw "[PlaYUVerStream] Cannot write into the file"; } + m_uiCurrFrameFileIdx = new_frame_num; m_uiFrameBufferIndex = 0; diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 3861958..5fcd2e1 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -35,8 +35,9 @@ namespace plaYUVer { -class LibAvContextHandle; +class StreamHandlerLibav; class LibOpenCVHandler; +class PlaYUVerStreamHandlerIf; typedef struct { @@ -69,6 +70,7 @@ typedef struct formatsList.insert( formatsList.end(), new_fmts.begin(), new_fmts.end() ); \ } + /** * \class PlaYUVerStream * \ingroup PlaYUVerLib PlaYUVerLib_Stream @@ -95,6 +97,9 @@ public: END_OF_SEQ, }; + std::string getFormatName(); + std::string getCodecName(); + Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); @@ -102,9 +107,6 @@ public: Void close(); - Bool openFile(); - Void closeFile(); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ); Void loadAll(); @@ -134,14 +136,6 @@ public: { return m_cFilename; } - std::string getFormatName() - { - return m_cFormatName; - } - std::string getCodecName() - { - return m_cCodedName; - } UInt getFrameNum() { @@ -182,14 +176,12 @@ private: TOTAL_HANDLERR }; Int m_iStreamHandler; - LibAvContextHandle* m_cLibAvContext; + PlaYUVerStreamHandlerIf* m_pcStreamHandler; + StreamHandlerLibav* m_cLibAvContext; std::string m_cFilename; Char* m_pchFilename; - std::string m_cFormatName; - std::string m_cCodedName; - UInt m_uiWidth; UInt m_uiHeight; Int m_iPixelFormat; @@ -199,8 +191,6 @@ private: UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; - FILE* m_pFile; /**< The input file pointer >*/ - std::fstream m_fsIOStream; /**< The input file pointer >*/ Byte* m_pStreamBuffer; UInt m_uiFrameBufferSize; diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h new file mode 100644 index 0000000..02f9f81 --- /dev/null +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -0,0 +1,85 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file PlaYUVerStreamHandlerIf.h + * \brief Abstract class for stream handling + */ + +#ifndef __PLAYUVERSTREAMHANDLERIF_H__ +#define __PLAYUVERSTREAMHANDLERIF_H__ + +#include "PlaYUVerDefs.h" +// #include +// #include +// #include + +namespace plaYUVer +{ + +/** + * \class PlaYUVerStreamHandlerIf + * \ingroup PlaYUVerLib PlaYUVerLib_Stream + * \brief Abstract class for stream handling + */ +class PlaYUVerStreamHandlerIf +{ +public: + PlaYUVerStreamHandlerIf() + { + m_bIsInput = true; + } + ~PlaYUVerStreamHandlerIf() + { + } + virtual Bool openHandler( std::string strFilename, Bool bInput ) = 0; + virtual UInt64 calculateFrameNumber() = 0; + virtual Void closeHandler() = 0; + virtual Bool read( Byte* pchBuffer ) = 0; + virtual Bool write( Byte* pchBuffer ) = 0; + virtual Bool seek( UInt64 iFrameNum ) = 0; + + virtual Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) + { + return; + } + Void setBytesPerFrame( UInt64 uiNBytes ) + { + m_uiNBytesPerFrame = uiNBytes; + } + std::string getFormatName() + { + return m_strFormatName; + } + std::string getCodecName() + { + return m_strCodecName; + } +protected: + Bool m_bIsInput; + UInt64 m_uiNBytesPerFrame; + std::string m_strFormatName; + std::string m_strCodecName; +}; + + +} // NAMESPACE + +#endif // __PLAYUVERSTREAMHANDLERIF_H__ + diff --git a/lib/LibAvContextHandle.cpp b/lib/StreamHandlerLibav.cpp similarity index 57% rename from lib/LibAvContextHandle.cpp rename to lib/StreamHandlerLibav.cpp index bd095f4..95ae08a 100644 --- a/lib/LibAvContextHandle.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -18,13 +18,13 @@ */ /** - * \file LibAvContextHandle.cpp + * \file StreamHandlerLibav.cpp * \ingroup PlaYUVerLib * \brief Interface with libav libs */ #include -#include "LibAvContextHandle.h" +#include "StreamHandlerLibav.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" @@ -32,7 +32,7 @@ namespace plaYUVer { -std::vector LibAvContextHandle::supportedReadFormats() +std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( "Portable Grayscale Map", "pgm" ); @@ -48,26 +48,26 @@ std::vector LibAvContextHandle::supportedReadFormats() END_REGIST_PLAYUVER_SUPPORTED_FMT; } -std::vector LibAvContextHandle::supportedWriteFormats() +std::vector StreamHandlerLibav::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; END_REGIST_PLAYUVER_SUPPORTED_FMT; } -std::vector LibAvContextHandle::supportedSaveFormats() +std::vector StreamHandlerLibav::supportedSaveFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; END_REGIST_PLAYUVER_SUPPORTED_FMT; } -static int open_codec_context( int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type ) +static int open_codec_context( int *stream_idx, AVFormatContext *m_cFmtCtx, enum AVMediaType type ) { int ret; AVStream *st; AVCodecContext *dec_ctx = NULL; AVCodec *dec = NULL; - ret = av_find_best_stream( fmt_ctx, type, -1, -1, NULL, 0 ); + ret = av_find_best_stream( m_cFmtCtx, type, -1, -1, NULL, 0 ); if( ret < 0 ) { return ret; @@ -75,7 +75,7 @@ static int open_codec_context( int *stream_idx, AVFormatContext *fmt_ctx, enum A else { *stream_idx = ret; - st = fmt_ctx->streams[*stream_idx]; + st = m_cFmtCtx->streams[*stream_idx]; /* find decoder for the stream */ dec_ctx = st->codec; @@ -96,34 +96,21 @@ static int open_codec_context( int *stream_idx, AVFormatContext *fmt_ctx, enum A return 0; } -Void LibAvContextHandle::closeAvFormat() +// Bool StreamHandlerLibav::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, +// UInt64& num_frames ) +Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) { - if( m_bHasStream ) - { - if( video_dec_ctx ) - avcodec_close( video_dec_ctx ); + const char* filename = strFilename.c_str(); - if( fmt_ctx ) - avformat_close_input( &fmt_ctx ); - - av_free( frame ); - //av_free( video_dst_data[0] ); - } - m_bHasStream = false; -} - -Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, - UInt64& num_frames ) -{ - fmt_ctx = NULL; - video_dec_ctx = NULL; - video_stream = NULL; + m_cFmtCtx = NULL; + m_cCodecCtx = NULL; + m_cStream = NULL; // video_dst_data[0] = NULL; // video_dst_data[1] = NULL; // video_dst_data[2] = NULL; // video_dst_data[3] = NULL; - video_stream_idx = -1; - frame = NULL; + m_iStreamIdx = -1; + m_cFrame = NULL; m_bHasStream = false; AVDictionary *format_opts = NULL; @@ -131,40 +118,40 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& /* register all formats and codecs */ av_register_all(); - if( width > 0 && height > 0 ) - { - Char aux_string[10]; - sprintf( aux_string, "%dx%d", width, height ); - av_dict_set( &format_opts, "video_size", aux_string, 0 ); - } +// if( width > 0 && height > 0 ) +// { +// Char aux_string[10]; +// sprintf( aux_string, "%dx%d", width, height ); +// av_dict_set( &format_opts, "video_size", aux_string, 0 ); +// } - Int ffmpeg_pel_format = g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; - if( ffmpeg_pel_format >= 0 ) - { - av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( AVPixelFormat( ffmpeg_pel_format ) ), 0 ); - } +// Int ffmpeg_pel_format = g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; +// if( ffmpeg_pel_format >= 0 ) +// { +// av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( AVPixelFormat( ffmpeg_pel_format ) ), 0 ); +// } /* open input file, and allocate format context */ - if( avformat_open_input( &fmt_ctx, filename, NULL, &format_opts ) < 0 ) + if( avformat_open_input( &m_cFmtCtx, filename, NULL, &format_opts ) < 0 ) { //qDebug( ) << " Could not open source file %s !!!" << filename << endl; return false; } /* retrieve stream information */ - if( avformat_find_stream_info( fmt_ctx, NULL ) < 0 ) + if( avformat_find_stream_info( m_cFmtCtx, NULL ) < 0 ) { //qDebug( ) << " Could not find stream information !!!" << endl; return false; } - if( open_codec_context( &video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO ) >= 0 ) + if( open_codec_context( &m_iStreamIdx, m_cFmtCtx, AVMEDIA_TYPE_VIDEO ) >= 0 ) { - video_stream = fmt_ctx->streams[video_stream_idx]; - video_dec_ctx = video_stream->codec; + m_cStream = m_cFmtCtx->streams[m_iStreamIdx]; + m_cCodecCtx = m_cStream->codec; // /* allocate image where the decoded image will be put */ -// ret = av_image_alloc( video_dst_data, video_dst_linesize, video_dec_ctx->width, video_dec_ctx->height, video_dec_ctx->pix_fmt, 1 ); +// ret = av_image_alloc( video_dst_data, video_dst_linesize, m_cCodecCtx->width, m_cCodecCtx->height, m_cCodecCtx->pix_fmt, 1 ); // if( ret < 0 ) // { // //qDebug( ) << " Could not allocate raw video buffer !!!" << endl; @@ -173,48 +160,31 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& // } // video_dst_bufsize = ret; - m_uiFrameBufferSize = av_image_get_buffer_size( video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height, 1 ); + m_uiFrameBufferSize = av_image_get_buffer_size( m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } - const char *name = avcodec_get_name( video_dec_ctx->codec_id ); + const char *name = avcodec_get_name( m_cCodecCtx->codec_id ); sprintf( m_acCodecName, "%s", name ); Double fr = 30; - if( video_stream->avg_frame_rate.den && video_stream->avg_frame_rate.num ) - fr = av_q2d( video_stream->avg_frame_rate ); + if( m_cStream->avg_frame_rate.den && m_cStream->avg_frame_rate.num ) + fr = av_q2d( m_cStream->avg_frame_rate ); #if FF_API_R_FRAME_RATE - else if( video_stream->r_frame_rate.den && video_stream->r_frame_rate.num ) - fr = av_q2d( video_stream->r_frame_rate ); + else if( m_cStream->r_frame_rate.den && m_cStream->r_frame_rate.num ) + fr = av_q2d( m_cStream->r_frame_rate ); #endif - else if( video_stream->time_base.den && video_stream->time_base.num ) - fr = 1 / av_q2d( video_stream->time_base ); - else if( video_stream->codec->time_base.den && video_stream->codec->time_base.num ) - fr = 1 / av_q2d( video_stream->codec->time_base ); + else if( m_cStream->time_base.den && m_cStream->time_base.num ) + fr = 1 / av_q2d( m_cStream->time_base ); + else if( m_cStream->codec->time_base.den && m_cStream->codec->time_base.num ) + fr = 1 / av_q2d( m_cStream->codec->time_base ); - frame_rate = fr; + m_dFrameRate = fr; - /*if( video_stream->nb_frames ) - { - num_frames = video_stream->nb_frames; - } - else*/if( fmt_ctx->duration != AV_NOPTS_VALUE ) - { - Int64 duration = fmt_ctx->duration + 5000; - m_uiSecs = duration / AV_TIME_BASE; - num_frames = m_uiSecs * frame_rate; - m_uiMicroSec = duration % AV_TIME_BASE; - } - else - { - num_frames = 0; - } - num_frames = num_frames == 0 ? 1 : num_frames; - - Int pix_fmt = video_dec_ctx->pix_fmt; + Int pix_fmt = m_cCodecCtx->pix_fmt; // Set bits per pixel to default (8 bits) - bits_pel = 8; + m_uiBitsPerPixel = 8; /** * Auxiliar conversation to re-use similar pixfmt @@ -231,55 +201,52 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& pix_fmt = AV_PIX_FMT_YUV444P; break; case AV_PIX_FMT_GRAY16LE: - bits_pel = 16; - endianness = 1; + m_uiBitsPerPixel = 16; + m_iEndianness = 1; pix_fmt = AV_PIX_FMT_GRAY8; break; case AV_PIX_FMT_GRAY16BE: - bits_pel = 16; - endianness = 0; + m_uiBitsPerPixel = 16; + m_iEndianness = 0; pix_fmt = AV_PIX_FMT_GRAY8; break; } - width = video_dec_ctx->width; - height = video_dec_ctx->height; + m_uiWidth = m_cCodecCtx->width; + m_uiHeight = m_cCodecCtx->height; - pixel_format = PlaYUVerFrame::NO_FMT; + m_iPixelFormat = PlaYUVerFrame::NO_FMT; for( Int i = 0; i < PLAYUVER_NUMBER_FORMATS; i++ ) { if( g_PlaYUVerPixFmtDescriptorsList[i].ffmpegPelFormat == pix_fmt ) { - pixel_format = i; + m_iPixelFormat = i; break; } } - if( pixel_format == PlaYUVerFrame::NO_FMT ) + if( m_iPixelFormat == PlaYUVerFrame::NO_FMT ) { throw "Cannot open file using FFmpeg libs - unsupported pixel format"; - closeAvFormat(); return false; } /* dump input information to stderr */ - av_dump_format( fmt_ctx, 0, filename, 0 ); - if( !video_stream ) + av_dump_format( m_cFmtCtx, 0, filename, 0 ); + if( !m_cStream ) { //qDebug( ) << " Could not find audio or video stream in the input, aborting !!!" << endl; - closeAvFormat(); + closeHandler(); return false; } #if( LIBAVFORMAT_VERSION_MAJOR >= 55 ) - frame = av_frame_alloc(); + m_cFrame = av_frame_alloc(); #else - frame = avcodec_alloc_frame(); + m_cFrame = avcodec_alloc_frame(); #endif - if( !frame ) + if( !m_cFrame ) { - //qDebug( ) << " Could not allocate frame !!!" << endl; - //ret = AVERROR( ENOMEM ); - closeAvFormat(); + closeHandler(); return false; } @@ -293,13 +260,62 @@ Bool LibAvContextHandle::initAvFormat( const char* filename, UInt& width, UInt& return true; } -Bool LibAvContextHandle::decodeVideoPkt() +Void StreamHandlerLibav::closeHandler() +{ + if( m_bHasStream ) + { + if( m_cCodecCtx ) + avcodec_close( m_cCodecCtx ); + + if( m_cFmtCtx ) + avformat_close_input( &m_cFmtCtx ); + + av_free( m_cFrame ); + } + m_bHasStream = false; +} + +Void StreamHandlerLibav::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) +{ + rWidth = m_uiWidth; + rHeight = m_uiHeight; + rInputFormat = m_iPixelFormat; + rBitsPerPel = m_uiBitsPerPixel; + rEndianness = m_iEndianness; + rFrameRate = m_dFrameRate; +} + + +UInt64 StreamHandlerLibav::calculateFrameNumber() +{ + UInt64 num_frames; +// if( m_cStream->nb_frames ) +// { * +// num_frames = m_cStream->nb_frames; +// } +// else + if( m_cFmtCtx->duration != AV_NOPTS_VALUE ) + { + Int64 duration = m_cFmtCtx->duration + 5000; + m_uiSecs = duration / AV_TIME_BASE; + num_frames = m_uiSecs * m_dFrameRate; + m_uiMicroSec = duration % AV_TIME_BASE; + } + else + { + num_frames = 0; + } + num_frames = num_frames == 0 ? 1 : num_frames; + return num_frames; +} + +Bool StreamHandlerLibav::decodeVideoPkt() { Int got_frame = 0; Int decResult; - if( pkt.stream_index == video_stream_idx ) + if( pkt.stream_index == m_iStreamIdx ) { - decResult = avcodec_decode_video2( video_dec_ctx, frame, &got_frame, &pkt ); + decResult = avcodec_decode_video2( m_cCodecCtx, m_cFrame, &got_frame, &pkt ); if( decResult < 0 ) { fprintf( stderr, "Error decoding video frame\n" ); @@ -315,7 +331,7 @@ Bool LibAvContextHandle::decodeVideoPkt() return got_frame > 0 ? true : false; } -Bool LibAvContextHandle::decodeAvFormat() +Bool StreamHandlerLibav::read( Byte* pchBuffer ) { Bool bGotFrame = false; AVPacket orig_pkt = pkt; @@ -323,7 +339,7 @@ Bool LibAvContextHandle::decodeAvFormat() bGotFrame |= decodeVideoPkt(); /* read frames from the file */ - while( !bGotFrame && ( av_read_frame( fmt_ctx, &pkt ) >= 0 ) ) + while( !bGotFrame && ( av_read_frame( m_cFmtCtx, &pkt ) >= 0 ) ) { orig_pkt = pkt; do @@ -348,9 +364,10 @@ Bool LibAvContextHandle::decodeAvFormat() if( bGotFrame ) { - av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, frame->data, frame->linesize, video_dec_ctx->pix_fmt, video_dec_ctx->width, - video_dec_ctx->height, 1 ); - + av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, + m_cCodecCtx->height, 1 ); + av_image_copy_to_buffer( pchBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, + m_cCodecCtx->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); @@ -360,9 +377,15 @@ Bool LibAvContextHandle::decodeAvFormat() return false; } -Void LibAvContextHandle::seekAvFormat( UInt64 frame_num ) +Bool StreamHandlerLibav::write( Byte* pchBuffer ) { - av_seek_frame( fmt_ctx, video_stream_idx, frame_num, AVSEEK_FLAG_FRAME ); + return false; +} + +Bool StreamHandlerLibav::seek( UInt64 iFrameNum ) +{ + av_seek_frame( m_cFmtCtx, m_iStreamIdx, iFrameNum, AVSEEK_FLAG_FRAME ); + return true; } } // NAMESPACE diff --git a/lib/LibAvContextHandle.h b/lib/StreamHandlerLibav.h similarity index 69% rename from lib/LibAvContextHandle.h rename to lib/StreamHandlerLibav.h index 57cbc9f..1b48906 100644 --- a/lib/LibAvContextHandle.h +++ b/lib/StreamHandlerLibav.h @@ -18,7 +18,7 @@ */ /** - * \file LibAvContextHandle.h + * \file StreamHandlerLibav.h * \ingroup PlaYUVerLib * \brief Interface with libav libs */ @@ -49,11 +49,12 @@ extern "C" #include "PlaYUVerDefs.h" #include "PlaYUVerStream.h" +#include "PlaYUVerStreamHandlerIf.h" namespace plaYUVer { -class LibAvContextHandle +class StreamHandlerLibav: public PlaYUVerStreamHandlerIf { public: @@ -61,46 +62,42 @@ public: static std::vector supportedWriteFormats(); static std::vector supportedSaveFormats(); - LibAvContextHandle() : - m_bHasStream( false ) + StreamHandlerLibav() { } - Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, UInt64& num_frames ); - Void closeAvFormat(); - Bool decodeAvFormat(); - Void seekAvFormat( UInt64 frame_num ); + Bool openHandler( std::string strFilename, Bool bInput ); +// Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, UInt64& num_frames ); + Void closeHandler(); + UInt64 calculateFrameNumber(); + Bool seek( UInt64 iFrameNum ); + Bool read( Byte* pchBuffer ); + Bool write( Byte* pchBuffer ); + + Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); - Bool getStatus() - { - return m_bHasStream; - } - Char* getFormatName() - { - return m_acFormatName; - } - Char* getCodecName() - { - return m_acCodecName; - } UInt getStreamDuration() { return m_uiSecs; } -// uint8_t *video_dst_data[4]; -// int video_dst_linesize[4]; -// int video_dst_bufsize; - UChar* m_pchFrameBuffer; UInt64 m_uiFrameBufferSize; private: - AVFormatContext *fmt_ctx; - AVCodecContext *video_dec_ctx; - AVStream *video_stream; - Int video_stream_idx; - AVFrame *frame; + + UInt m_uiWidth; + UInt m_uiHeight; + Int m_iPixelFormat; + UInt m_uiBitsPerPixel; + Int m_iEndianness; + Double m_dFrameRate; + + AVFormatContext* m_cFmtCtx; + AVCodecContext* m_cCodecCtx; + AVStream* m_cStream; + Int m_iStreamIdx; + AVFrame* m_cFrame; AVPacket pkt; Bool m_bHasStream; diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h new file mode 100644 index 0000000..e1d05f4 --- /dev/null +++ b/lib/StreamHandlerRaw.h @@ -0,0 +1,101 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file PlaYUVerRawHandler.h + * \brief Abstract class for stream handling + */ + +#ifndef __PLAYUVERRAWHANDLER_H__ +#define __PLAYUVERRAWHANDLER_H__ + +#include "PlaYUVerDefs.h" +#include "PlaYUVerStreamHandlerIf.h" + +namespace plaYUVer +{ + +/** + * \class PlaYUVerRawHandler + * \ingroup PlaYUVerLib PlaYUVerLib_Stream + * \brief Class to handle raw video format + */ +class PlaYUVerRawHandler: public PlaYUVerStreamHandlerIf +{ +private: + FILE* m_pFile; /**< The input file pointer >*/ +public: + + Bool openHandler( std::string strFilename, Bool bInput ) + { + m_bIsInput = bInput; + m_pFile = NULL; + m_pFile = fopen( strFilename.c_str(), bInput ? "rb" : "wb" ); + if( m_pFile == NULL ) + { + return false; + } + m_strFormatName = "YUV"; + m_strCodecName = "Raw Video"; + return true; + } + Void closeHandler() + { + if( m_pFile ) + fclose( m_pFile ); + } + UInt64 calculateFrameNumber() + { + if( !m_pFile || m_uiNBytesPerFrame == 0 ) + return 0; + fseek( m_pFile, 0, SEEK_END ); + UInt64 fileSize = ftell( m_pFile ); + fseek( m_pFile, 0, SEEK_SET ); + return ( fileSize / m_uiNBytesPerFrame ); + } + Bool seek( UInt64 iFrameNum ) + { + if( m_bIsInput && m_pFile ) + { + fseek( m_pFile, iFrameNum >= 0 ? iFrameNum * m_uiNBytesPerFrame : 0, SEEK_SET ); + return true; + } + return false; + } + Bool read( Byte* pchBuffer ) + { + UInt64 processed_bytes = fread( pchBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + return true; + } + Bool write( Byte* pchBuffer ) + { + UInt64 processed_bytes = fwrite( pchBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + return true; + } +}; + + +} // NAMESPACE + +#endif // __PLAYUVERRAWHANDLER_H__ + From 2ab86e5aeec7ec2d7d7ed629d5b70a1a06d28980 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 2 Apr 2016 01:36:52 +0100 Subject: [PATCH 007/127] Finish three stream handlers: Raw, OpenCv, Libav --- lib/CMakeLists.txt | 2 +- lib/LibOpenCVHandler.cpp | 69 ------- lib/PlaYUVerFrame.cpp | 62 ++++--- lib/PlaYUVerFrame.h | 15 +- lib/PlaYUVerStream.cpp | 175 +++++++----------- lib/PlaYUVerStream.h | 12 +- lib/PlaYUVerStreamHandlerIf.h | 22 ++- lib/StreamHandlerLibav.cpp | 34 ++-- lib/StreamHandlerLibav.h | 10 +- lib/StreamHandlerOpenCV.cpp | 100 ++++++++++ ...bOpenCVHandler.h => StreamHandlerOpenCV.h} | 30 ++- lib/StreamHandlerRaw.h | 15 +- 12 files changed, 289 insertions(+), 257 deletions(-) delete mode 100644 lib/LibOpenCVHandler.cpp create mode 100644 lib/StreamHandlerOpenCV.cpp rename lib/{LibOpenCVHandler.h => StreamHandlerOpenCV.h} (66%) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index f5c8397..92a79c5 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -22,7 +22,7 @@ IF( USE_FFMPEG ) ENDIF() IF( USE_OPENCV ) - LIST( APPEND PlaYUVer_Lib_SRCS LibOpenCVHandler.cpp ) + LIST( APPEND PlaYUVer_Lib_SRCS StreamHandlerOpenCV.cpp ) ENDIF() diff --git a/lib/LibOpenCVHandler.cpp b/lib/LibOpenCVHandler.cpp deleted file mode 100644 index 136cf64..0000000 --- a/lib/LibOpenCVHandler.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) - * Joao Carreira (jfmcarreira@gmail.com) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -/** - * \file LibOpenCVHandler.cpp - * \ingroup PlaYUVerLib - * \brief Interface with opencv lib - */ - -#include -#include "LibOpenCVHandler.h" -#include "PlaYUVerFrame.h" -#include "PlaYUVerFramePixelFormats.h" -#include "LibMemory.h" - -namespace plaYUVer -{ - -std::vector LibOpenCVHandler::supportedReadFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( "Portable Grayscale Map ", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Portable Network Graphics", "png" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Joint Photographic Experts Group", "jpg" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Windows Bitmap", "bmp" ); - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -std::vector LibOpenCVHandler::supportedWriteFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -std::vector LibOpenCVHandler::supportedSaveFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - APPEND_PLAYUVER_SUPPORTED_FMT( LibOpenCVHandler, Read ); - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -PlaYUVerFrame* LibOpenCVHandler::loadFrame( std::string filename ) -{ - return NULL; -} - -Bool LibOpenCVHandler::saveFrame( PlaYUVerFrame* pcFrame, std::string filename ) -{ - cv::Mat* pcCvFrame = pcFrame->getCvMat(); - return cv::imwrite( filename, *pcCvFrame ); -} - -} // NAMESPACE diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index b2620c6..4e54296 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -33,7 +33,7 @@ #include "StreamHandlerLibav.h" #endif #ifdef USE_OPENCV -#include "LibOpenCVHandler.h" +#include "StreamHandlerOpenCV.h" #endif #ifdef USE_PIXFC #include "pixfc-sse.h" @@ -74,14 +74,14 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int color return formatsList; } -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) { - init( width, height, pelFormat, bitsPixel ); + init( width, height, pelFormat, bitsPixel, endianness ); } PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) { - init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel() ); + init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); copyFrom( other ); } @@ -105,7 +105,7 @@ PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt a areaHeight++; } - init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel() ); + init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); copyFrom( other, posX, posY ); } @@ -138,10 +138,10 @@ static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2 total_mem_size += getMem2D( array3D, dim0, dim1 ); - if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof(Pel) ) ) == NULL ) + if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof( Pel ) ) ) == NULL ) printf( "getMem3DImageComponents: array1D" ); - total_mem_size += mem_size * sizeof(Pel); + total_mem_size += mem_size * sizeof( Pel ); // Luma for( i = 1; i < dim1; i++ ) @@ -163,7 +163,7 @@ static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2 return total_mem_size; } -Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel ) +Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) { m_bInit = false; m_pppcInputPel = NULL; @@ -173,6 +173,11 @@ Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel m_iPixelFormat = pel_format; m_iNumberChannels = 3; m_uiBitsPel = bitsPixel > 8 ? bitsPixel : 8; + m_iEndianness = endianness; + if( m_uiBitsPel > 8 && m_iEndianness == -1 ) + { + throw "Invalid endianness type for Bits per Pixel greater than 8"; + } m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) @@ -364,7 +369,7 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame ) return; m_bHasRGBPel = false; m_bHasHistogram = false; - memcpy( *m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof(Pel) ); + memcpy( *m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); } Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) @@ -378,18 +383,23 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) Int ratioW = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; for( UInt i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ); i++ ) { - memcpy( m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( m_uiWidth >> ratioW ) * sizeof(Pel) ); + memcpy( m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( m_uiWidth >> ratioW ) * sizeof( Pel ) ); } } m_bHasRGBPel = false; m_bHasHistogram = false; } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize, Int endianess ) +Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) { if( uiBuffSize != getBytesPerFrame() ) return; + frameFromBuffer( Buff ); +} + +Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) +{ Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; Pel* pPel; @@ -398,7 +408,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize, Int endianes Int ratioH, ratioW, step; UInt i, ch, b; - if( endianess == 1 ) + if( m_iEndianness == 1 ) { shiftInput = 8; shiftOutput = 0; @@ -913,11 +923,11 @@ Void PlaYUVerFrame::openPixfc() #ifdef USE_PIXFC m_pcPixfc = NULL; PixFcPixelFormat input_format = PixFcYUV420P; - PixFcFlag flags = (PixFcFlag)(PixFcFlag_Default + PixFcFlag_NNbResamplingOnly); + PixFcFlag flags = ( PixFcFlag )( PixFcFlag_Default + PixFcFlag_NNbResamplingOnly ); UInt input_row_size = m_uiWidth; - if (create_pixfc(&m_pcPixfc, input_format, PixFcRGB24, m_uiWidth, m_uiHeight, input_row_size, m_uiWidth * 3, flags ) != 0) + if( create_pixfc( &m_pcPixfc, input_format, PixFcRGB24, m_uiWidth, m_uiHeight, input_row_size, m_uiWidth * 3, flags ) != 0 ) { - fprintf(stderr, "Error creating struct pixfc\n"); + fprintf( stderr, "Error creating struct pixfc\n" ); m_pcPixfc = NULL; return; } @@ -928,7 +938,7 @@ Void PlaYUVerFrame::closePixfc() { #ifdef USE_PIXFC if( m_pcPixfc ) - destroy_pixfc(m_pcPixfc); + destroy_pixfc( m_pcPixfc ); #endif } @@ -937,20 +947,20 @@ Void PlaYUVerFrame::FrametoRGB8Pixfc() #ifdef USE_PIXFC switch( m_iPixelFormat ) { - case YUV420p: - m_pcPixfc->convert(m_pcPixfc, m_pppcInputPel, m_pcRGB32); + case YUV420p: + m_pcPixfc->convert( m_pcPixfc, m_pppcInputPel, m_pcRGB32 ); break; - case YUV422p: + case YUV422p: break; - case YUV444p: - case YUYV422: - m_pcPixfc->convert(m_pcPixfc, m_pppcInputPel, m_pcRGB32); + case YUV444p: + case YUYV422: + m_pcPixfc->convert( m_pcPixfc, m_pppcInputPel, m_pcRGB32 ); break; - case GRAY: + case GRAY: break; - case RGB8: + case RGB8: break; - default: + default: // No action. break; } @@ -1020,7 +1030,7 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) if( !m_bInit ) { - init( pcCvFrame->cols, pcCvFrame->rows, m_iPixelFormat, 8 ); + init( pcCvFrame->cols, pcCvFrame->rows, m_iPixelFormat, 8, -1 ); } m_bHasRGBPel = false; diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 7a6946a..b8efb41 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -115,7 +115,7 @@ public: * * @note this function might misbehave if the pixel format enum is not correct */ - PlaYUVerFrame( UInt width, UInt height, Int pelFormat = 0, Int bitsPixel = 8 ); + PlaYUVerFrame( UInt width, UInt height, Int pelFormat = 0, Int bitsPixel = 8, Int endianness = -1 ); /** * Creates and new frame with the configuration of an @@ -158,7 +158,10 @@ public: { return m_uiBitsPel; } - + Int getEndianness() const + { + return m_iEndianness; + } Pel*** getPelBufferYUV() const { return m_pppcInputPel; @@ -207,11 +210,12 @@ public: PlaYUVerPixel getPixelValue( Int xPos, Int yPos ); PlaYUVerPixel getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::ColorSpace eColorSpace ); Void setPixelValue( Int xPos, Int yPos, PlaYUVerPixel pixel ); - + Void copyFrom( PlaYUVerFrame* ); Void copyFrom( PlaYUVerFrame*, UInt, UInt ); - Void frameFromBuffer( Byte*, UInt64, Int ); + Void frameFromBuffer( Byte*, UInt64 ); + Void frameFromBuffer( Byte* ); Void frameToBuffer( Byte* ); Void fillRGBBuffer(); @@ -297,6 +301,7 @@ private: Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) Int m_iNumberChannels; //!< Number of channels UInt m_uiBitsPel; //!< Bits per pixel/channel + Int m_iEndianness; //!< Endiannes of bytes UInt m_uiHalfPelValue; //!< Bits per pixel/channel Pel*** m_pppcInputPel; @@ -328,7 +333,7 @@ private: * @param pel_format pixel format index (always use PixelFormats enum) * */ - Void init( UInt width, UInt height, Int pel_format, Int bitsPixel ); + Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ); Void openPixfc(); Void closePixfc(); diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 36d0b45..92bf173 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -30,12 +30,13 @@ #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" #include "StreamHandlerRaw.h" +#include "StreamHandlerPortable.h" #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" #endif #ifdef USE_OPENCV -#include "LibOpenCVHandler.h" +#include "StreamHandlerOpenCV.h" #endif namespace plaYUVer @@ -44,8 +45,8 @@ namespace plaYUVer std::vector PlaYUVerStream::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "yuv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "gray" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "gray" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Read ); #endif @@ -58,7 +59,7 @@ std::vector PlaYUVerStream::supportedReadFormats() std::vector PlaYUVerStream::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( "Raw Video", "yuv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Write ); #endif @@ -73,7 +74,7 @@ std::vector PlaYUVerStream::supportedSaveFormats() APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Save ); #endif #ifdef USE_OPENCV - APPEND_PLAYUVER_SUPPORTED_FMT( LibOpenCVHandler, Save ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Save ); #endif END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -129,18 +130,11 @@ PlaYUVerStream::PlaYUVerStream() m_uiFrameBufferSize = 2; m_uiFrameBufferIndex = 0; m_uiCurrFrameFileIdx = 0; -// #ifdef USE_FFMPEG -// m_cLibAvContext = new StreamHandlerLibav; -// #endif } PlaYUVerStream::~PlaYUVerStream() { close(); -// #ifdef USE_FFMPEG -// if( m_cLibAvContext ) -// delete m_cLibAvContext; -// #endif } std::string PlaYUVerStream::getFormatName() @@ -152,57 +146,6 @@ std::string PlaYUVerStream::getCodecName() return !m_pcStreamHandler ? "" : m_pcStreamHandler->getCodecName(); } -Void PlaYUVerStream::findHandler() -{ - m_iStreamHandler = INVALID_HANDLER; - -// if( m_uiBitsPerPixel != 8 ) -// { -// m_iStreamHandler = YUV_IO; -// return; -// } - - std::string currExt = m_cFilename.substr( m_cFilename.find_last_of( "." ) + 1 ); - currExt = lowercase( currExt ); - - if( m_bIsInput ) - { -#ifdef USE_FFMPEG - std::vector supportedFmts = StreamHandlerLibav::supportedReadFormats(); - for( UInt i = 0; i < supportedFmts.size(); i++ ) - { - if( supportedFmts[i].formatExt == currExt ) - { - //m_cFormatName = uppercase( supportedFmts[i].formatExt ); - m_iStreamHandler = FFMPEG; - return; - } - } -#endif - if( m_iStreamHandler == INVALID_HANDLER ) - m_iStreamHandler = YUV_IO; - } - else - { -#ifdef USE_FFMPEG - std::vector supportedFmts = StreamHandlerLibav::supportedWriteFormats(); - for( UInt i = 0; i < supportedFmts.size(); i++ ) - { - if( supportedFmts[i].formatExt == currExt ) - { -// m_cFormatName = uppercase( supportedFmts[i].formatExt ); - m_iStreamHandler = FFMPEG; - return; - } - } -#endif - if( currExt == "yuv" ) - { - m_iStreamHandler = YUV_IO; - } - } -} - Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { UInt width; @@ -248,43 +191,55 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in std::copy( m_cFilename.begin(), m_cFilename.end(), m_pchFilename ); m_pchFilename[m_cFilename.size()] = '\0'; // don't forget the terminating 0 - findHandler(); - if( m_iStreamHandler == INVALID_HANDLER ) + + m_iStreamHandler = INVALID_HANDLER; + std::string currExt = m_cFilename.substr( m_cFilename.find_last_of( "." ) + 1 ); + currExt = lowercase( currExt ); + + std::vector supportedFmts; + if( m_bIsInput ) { - close(); - throw "Invalid file format"; - return m_bInit; + supportedFmts = supportedReadFormats(); } - - m_uiFrameBufferSize = m_bIsInput ? 2 : 1; - -#ifdef USE_OPENCV - if( m_iStreamHandler == OPENCV_HANDLER ) + else { - m_pcCurrFrame = LibOpenCVHandler::loadFrame( m_cFilename ); - if( m_pcCurrFrame ) + supportedFmts = supportedWriteFormats(); + } + for( UInt i = 0; i < supportedFmts.size(); i++ ) + { + if( supportedFmts[i].formatExt == currExt ) { - m_uiWidth = m_pcCurrFrame->getWidth(); - m_uiHeight = m_pcCurrFrame->getHeight(); - m_iPixelFormat = m_pcCurrFrame->getPelFormat(); + m_pfctCreateHandler = supportedFmts[i].formatFct; + break; } - m_pcNextFrame = NULL; - m_uiFrameBufferSize = 0; - m_uiFrameBufferIndex = 0; - m_uiTotalFrameNum = 1; } -#endif -#ifdef USE_FFMPEG - if( m_iStreamHandler == FFMPEG ) - { - m_pcStreamHandler = new StreamHandlerLibav; - } -#endif - if( m_iStreamHandler == YUV_IO ) - { - m_pcStreamHandler = new PlaYUVerRawHandler; - } +// if( m_iStreamHandler == INVALID_HANDLER ) +// { +// close(); +// throw "Invalid file format"; +// return m_bInit; +// } + + +// #ifdef USE_OPENCV +// if( m_iStreamHandler == OPENCV_HANDLER ) +// { +// m_pcCurrFrame = LibOpenCVHandler::loadFrame( m_cFilename ); +// if( m_pcCurrFrame ) +// { +// m_uiWidth = m_pcCurrFrame->getWidth(); +// m_uiHeight = m_pcCurrFrame->getHeight(); +// m_iPixelFormat = m_pcCurrFrame->getPelFormat(); +// } +// m_pcNextFrame = NULL; +// m_uiFrameBufferSize = 0; +// m_uiFrameBufferIndex = 0; +// m_uiTotalFrameNum = 1; +// } +// #endif + + m_pcStreamHandler = m_pfctCreateHandler(); if( !m_pcStreamHandler ) { @@ -307,12 +262,14 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in return m_bInit; } + m_uiFrameBufferSize = m_bIsInput ? 2 : 1; + getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness ); } catch( const char *msg ) { @@ -338,7 +295,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in return m_bInit; } - if( !getMem1D( &m_pStreamBuffer, m_pcCurrFrame->getBytesPerFrame() ) ) + if( !m_pcStreamHandler->configureBuffer( m_pcCurrFrame ) ) { close(); throw "[PlaYUVerStream] Cannot allocated memory"; @@ -530,15 +487,12 @@ Void PlaYUVerStream::readFrame() return; } - UInt64 uiByterPerFrame = m_pcNextFrame->getBytesPerFrame(); - - - if( !m_pcStreamHandler->read( m_pStreamBuffer ) ) + if( !m_pcStreamHandler->read( m_pcNextFrame ) ) { throw "[PlaYUVerStream] Cannot read file"; return; } - m_pcNextFrame->frameFromBuffer( m_pStreamBuffer, uiByterPerFrame, m_iEndianness ); + m_uiCurrFrameFileIdx++; return; @@ -551,13 +505,9 @@ Void PlaYUVerStream::writeFrame() Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) { - if( m_iStreamHandler == YUV_IO ) + if( !m_pcStreamHandler->write( pcFrame ) ) { - pcFrame->frameToBuffer( m_pStreamBuffer ); - if( !m_pcStreamHandler->write( m_pStreamBuffer ) ) - { - throw "[PlaYUVerStream] Cannot write into the file"; - } + throw "[PlaYUVerStream] Cannot write into the file"; } return; } @@ -572,7 +522,6 @@ Bool PlaYUVerStream::saveFrame( const std::string& filename, PlaYUVerFrame *save Int iFileFormat = INVALID_HANDLER; std::string fmtExt; -//std::string currExt = QFileInfo( qtString ).suffix().toStdString(); std::string currExt = filename.substr( filename.find_last_of( "." ) + 1 ); std::vector supportedFmts = PlaYUVerStream::supportedSaveFormats(); @@ -607,12 +556,12 @@ Bool PlaYUVerStream::saveFrame( const std::string& filename, PlaYUVerFrame *save return qimg.save( qtString ); } #endif -#ifdef USE_OPENCV - else - { - return LibOpenCVHandler::saveFrame( saveFrame, filename ); - } -#endif +// #ifdef USE_OPENCV +// else +// { +// return LibOpenCVHandler::saveFrame( saveFrame, filename ); +// } +// #endif } return false; } diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 5fcd2e1..cac1e19 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -35,7 +35,6 @@ namespace plaYUVer { -class StreamHandlerLibav; class LibOpenCVHandler; class PlaYUVerStreamHandlerIf; @@ -46,10 +45,14 @@ typedef struct UInt uiHeight; } PlaYUVerStdResolution; + +typedef PlaYUVerStreamHandlerIf* (*CreateStreamHandlerFn)( void ); + typedef struct { std::string formatName; std::string formatExt; + CreateStreamHandlerFn formatFct; } PlaYUVerSupportedFormat; #define INI_REGIST_PLAYUVER_SUPPORTED_FMT \ @@ -59,9 +62,10 @@ typedef struct #define END_REGIST_PLAYUVER_SUPPORTED_FMT \ return formatsList; -#define REGIST_PLAYUVER_SUPPORTED_FMT( name, ext ) \ + #define REGIST_PLAYUVER_SUPPORTED_FMT( handler, name, ext ) \ formatElem.formatName = name; \ formatElem.formatExt = lowercase( ext ); \ + formatElem.formatFct = handler; \ formatsList.push_back( formatElem ); #define APPEND_PLAYUVER_SUPPORTED_FMT( class_name, fct ) \ @@ -176,8 +180,8 @@ private: TOTAL_HANDLERR }; Int m_iStreamHandler; + CreateStreamHandlerFn m_pfctCreateHandler; PlaYUVerStreamHandlerIf* m_pcStreamHandler; - StreamHandlerLibav* m_cLibAvContext; std::string m_cFilename; Char* m_pchFilename; @@ -200,8 +204,6 @@ private: UInt m_uiFrameBufferIndex; UInt64 m_uiCurrFrameFileIdx; - Void findHandler(); - }; } // NAMESPACE diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 02f9f81..ff399a7 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -26,13 +26,16 @@ #define __PLAYUVERSTREAMHANDLERIF_H__ #include "PlaYUVerDefs.h" -// #include -// #include -// #include +#include "LibMemory.h" namespace plaYUVer { +#define REGISTER_STREAM_HANDLER(X) \ + public: \ + static PlaYUVerStreamHandlerIf* Create() { return new X(); } \ + void Delete() { delete this; } + /** * \class PlaYUVerStreamHandlerIf * \ingroup PlaYUVerLib PlaYUVerLib_Stream @@ -45,16 +48,21 @@ public: { m_bIsInput = true; } - ~PlaYUVerStreamHandlerIf() + virtual ~PlaYUVerStreamHandlerIf() { } virtual Bool openHandler( std::string strFilename, Bool bInput ) = 0; virtual UInt64 calculateFrameNumber() = 0; virtual Void closeHandler() = 0; - virtual Bool read( Byte* pchBuffer ) = 0; - virtual Bool write( Byte* pchBuffer ) = 0; + virtual Bool read( PlaYUVerFrame* pcFrame ) = 0; + virtual Bool write( PlaYUVerFrame* pcFrame ) = 0; virtual Bool seek( UInt64 iFrameNum ) = 0; + virtual Bool configureBuffer( PlaYUVerFrame* pcFrame ) + { + return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); + } + virtual Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) { return; @@ -71,8 +79,10 @@ public: { return m_strCodecName; } + protected: Bool m_bIsInput; + Byte* m_pStreamBuffer; UInt64 m_uiNBytesPerFrame; std::string m_strFormatName; std::string m_strCodecName; diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 95ae08a..7d52311 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -35,16 +35,16 @@ namespace plaYUVer std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( "Portable Grayscale Map", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Portable Network Graphics", "png" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Joint Photographic Experts Group", "jpg" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Windows Bitmap", "bmp" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Audio video interleaved", "avi" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Windows media video", "wmv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "MPEG4", "mp4" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "Matroska Multimedia Container", "mkv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "H.264 streams", "h264" ); - REGIST_PLAYUVER_SUPPORTED_FMT( "HEVC streams", "hevc" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Grayscale Map", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -96,8 +96,6 @@ static int open_codec_context( int *stream_idx, AVFormatContext *m_cFmtCtx, enum return 0; } -// Bool StreamHandlerLibav::initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, -// UInt64& num_frames ) Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) { const char* filename = strFilename.c_str(); @@ -331,7 +329,7 @@ Bool StreamHandlerLibav::decodeVideoPkt() return got_frame > 0 ? true : false; } -Bool StreamHandlerLibav::read( Byte* pchBuffer ) +Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) { Bool bGotFrame = false; AVPacket orig_pkt = pkt; @@ -364,20 +362,22 @@ Bool StreamHandlerLibav::read( Byte* pchBuffer ) if( bGotFrame ) { - av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, - m_cCodecCtx->height, 1 ); - av_image_copy_to_buffer( pchBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, +// av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, +// m_cCodecCtx->height, 1 ); + av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); + pcFrame->frameFromBuffer( m_pStreamBuffer ); + return true; } return false; } -Bool StreamHandlerLibav::write( Byte* pchBuffer ) +Bool StreamHandlerLibav::write( PlaYUVerFrame* pcFrame ) { return false; } diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 1b48906..4c0de4f 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -56,6 +56,8 @@ namespace plaYUVer class StreamHandlerLibav: public PlaYUVerStreamHandlerIf { + REGISTER_STREAM_HANDLER( StreamHandlerLibav ) + public: static std::vector supportedReadFormats(); @@ -65,14 +67,16 @@ public: StreamHandlerLibav() { } + ~StreamHandlerLibav() + { + } Bool openHandler( std::string strFilename, Bool bInput ); -// Bool initAvFormat( const char* filename, UInt& width, UInt& height, Int& pixel_format, UInt& bits_pel, Int& endianness, Double& frame_rate, UInt64& num_frames ); Void closeHandler(); UInt64 calculateFrameNumber(); Bool seek( UInt64 iFrameNum ); - Bool read( Byte* pchBuffer ); - Bool write( Byte* pchBuffer ); + Bool read( PlaYUVerFrame* pcFrame ); + Bool write( PlaYUVerFrame* pcFrame ); Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp new file mode 100644 index 0000000..f793fe5 --- /dev/null +++ b/lib/StreamHandlerOpenCV.cpp @@ -0,0 +1,100 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file StreamHandlerOpenCV.cpp + * \ingroup PlaYUVerLib + * \brief Interface with opencv lib + */ + +#include +#include "StreamHandlerOpenCV.h" +#include "PlaYUVerFrame.h" +#include "PlaYUVerFramePixelFormats.h" +#include "LibMemory.h" + +namespace plaYUVer +{ + +std::vector StreamHandlerOpenCV::supportedReadFormats() +{ + INI_REGIST_PLAYUVER_SUPPORTED_FMT; + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Grayscale Map ", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); + END_REGIST_PLAYUVER_SUPPORTED_FMT; +} + +std::vector StreamHandlerOpenCV::supportedWriteFormats() +{ + INI_REGIST_PLAYUVER_SUPPORTED_FMT; + END_REGIST_PLAYUVER_SUPPORTED_FMT; +} + +std::vector StreamHandlerOpenCV::supportedSaveFormats() +{ + INI_REGIST_PLAYUVER_SUPPORTED_FMT; +// APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); + END_REGIST_PLAYUVER_SUPPORTED_FMT; +} + +Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) +{ + m_cFilename = m_cFilename; + return true; +} + +Void StreamHandlerOpenCV::closeHandler() +{ + +} + +Void StreamHandlerOpenCV::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) +{ +// rWidth = m_uiWidth; +// rHeight = m_uiHeight; +// rInputFormat = m_iPixelFormat; +// rBitsPerPel = m_uiBitsPerPixel; +// rEndianness = m_iEndianness; + rFrameRate = 1; +} + +UInt64 StreamHandlerOpenCV::calculateFrameNumber() +{ + return 1; +} + +Bool StreamHandlerOpenCV::seek( UInt64 iFrameNum ) +{ + return true; +} + +Bool StreamHandlerOpenCV::read( PlaYUVerFrame* pcFrame ) +{ + return false; +} + +Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) +{ + cv::Mat* pcCvFrame = pcFrame->getCvMat(); + return cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); +} + +} // NAMESPACE diff --git a/lib/LibOpenCVHandler.h b/lib/StreamHandlerOpenCV.h similarity index 66% rename from lib/LibOpenCVHandler.h rename to lib/StreamHandlerOpenCV.h index 7a71eb9..cd14dfc 100644 --- a/lib/LibOpenCVHandler.h +++ b/lib/StreamHandlerOpenCV.h @@ -18,13 +18,13 @@ */ /** - * \file LibOpenCVHandler.h + * \file StreamHandlerOpenCV.h * \ingroup PlaYUVerLib * \brief Interface with opencv lib */ -#ifndef __LIBOPENCVHANDLER_H__ -#define __LIBOPENCVHANDLER_H__ +#ifndef __STREAMHANDLEROPENCV_H__ +#define __STREAMHANDLEROPENCV_H__ #include #include @@ -32,29 +32,43 @@ #include #include "PlaYUVerDefs.h" #include "PlaYUVerStream.h" +#include "PlaYUVerStreamHandlerIf.h" namespace plaYUVer { class PlaYUVerFrame; -class LibOpenCVHandler +class StreamHandlerOpenCV: public PlaYUVerStreamHandlerIf { + REGISTER_STREAM_HANDLER( StreamHandlerOpenCV ) + public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); static std::vector supportedSaveFormats(); - LibOpenCVHandler() + StreamHandlerOpenCV() + { + } + ~StreamHandlerOpenCV() { } - static PlaYUVerFrame* loadFrame( std::string filename ); - static Bool saveFrame( PlaYUVerFrame* pcFrame, std::string filename ); + Bool openHandler( std::string strFilename, Bool bInput ); + Void closeHandler(); + UInt64 calculateFrameNumber(); + Bool seek( UInt64 iFrameNum ); + Bool read( PlaYUVerFrame* pcFrame ); + Bool write( PlaYUVerFrame* pcFrame ); + Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); + +private: + std::string m_cFilename; }; } // NAMESPACE -#endif // __LIBOPENCVHANDLER_H__ +#endif // __STREAMHANDLEROPENCV_H__ diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index e1d05f4..f4615b4 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -38,9 +38,14 @@ namespace plaYUVer */ class PlaYUVerRawHandler: public PlaYUVerStreamHandlerIf { + REGISTER_STREAM_HANDLER( PlaYUVerRawHandler ) + private: FILE* m_pFile; /**< The input file pointer >*/ + public: + PlaYUVerRawHandler() {} + ~PlaYUVerRawHandler() {} Bool openHandler( std::string strFilename, Bool bInput ) { @@ -78,16 +83,18 @@ public: } return false; } - Bool read( Byte* pchBuffer ) + Bool read( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fread( pchBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; + pcFrame->frameFromBuffer( m_pStreamBuffer ); return true; } - Bool write( Byte* pchBuffer ) + Bool write( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fwrite( pchBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + pcFrame->frameToBuffer( m_pStreamBuffer ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; return true; From 1fdf750d6ad5bede73d7b92bd1d8dab261e69d5b Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 2 Apr 2016 01:42:09 +0100 Subject: [PATCH 008/127] Save endianness type --- app/VideoSubWindow.cpp | 7 ++++--- app/VideoSubWindow.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 50385da..c861320 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -51,7 +51,7 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStreamInfoVector& array << d.m_uiHeight << d.m_iPelFormat << d.m_uiBitsPelPixel - << d.m_uiEndianness + << d.m_iEndianness << d.m_uiFrameRate << d.m_uiFileSize; } @@ -70,7 +70,7 @@ QDataStream& operator>>( QDataStream& in, PlaYUVerStreamInfoVector& array ) in >> d.m_uiHeight; in >> d.m_iPelFormat; in >> d.m_uiBitsPelPixel; - in >> d.m_uiEndianness; + in >> d.m_iEndianness; in >> d.m_uiFrameRate; in >> d.m_uiFileSize; array.append( d ); @@ -346,6 +346,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) m_sStreamInfo.m_uiHeight = Height; m_sStreamInfo.m_iPelFormat = InputFormat; m_sStreamInfo.m_uiBitsPelPixel = BitsPel; + m_sStreamInfo.m_iEndianness = Endianness; m_sStreamInfo.m_uiFrameRate = FrameRate; m_sStreamInfo.m_uiFileSize = QFileInfo( cFilename ).size(); @@ -368,7 +369,7 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) } if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, streamInfo->m_iPelFormat, - streamInfo->m_uiBitsPelPixel, streamInfo->m_uiEndianness, streamInfo->m_uiFrameRate ) ) + streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate ) ) { return false; } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index 33cbc18..b397429 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -52,7 +52,7 @@ typedef struct UInt m_uiHeight; Int m_iPelFormat; UInt m_uiBitsPelPixel; - UInt m_uiEndianness; + UInt m_iEndianness; UInt m_uiFrameRate; UInt64 m_uiFileSize; } PlaYUVerStreamInfo; From b71ca0580cb02fd84c72c7282eb38add767287b1 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 2 Apr 2016 02:42:20 +0100 Subject: [PATCH 009/127] Uniformisation of write and save --- app/PlaYUVerApp.cpp | 2 +- lib/PlaYUVerStream.cpp | 166 +++++++++++------------------------- lib/PlaYUVerStream.h | 22 +---- lib/StreamHandlerLibav.cpp | 12 ++- lib/StreamHandlerLibav.h | 1 - lib/StreamHandlerOpenCV.cpp | 18 ++-- lib/StreamHandlerOpenCV.h | 1 - 7 files changed, 70 insertions(+), 152 deletions(-) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 0d40fab..7207dc6 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -305,7 +305,7 @@ Void PlaYUVerApp::save() QString supported = tr( "Supported Files (" ); QStringList formatsList; - std::vector supportedFmts = PlaYUVerStream::supportedSaveFormats(); + std::vector supportedFmts = PlaYUVerStream::supportedWriteFormats(); for( UInt i = 0; i < supportedFmts.size(); i++ ) { QString currFmt; diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 92bf173..47cc857 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -62,19 +62,9 @@ std::vector PlaYUVerStream::supportedWriteFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Write ); -#endif - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -std::vector PlaYUVerStream::supportedSaveFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - APPEND_PLAYUVER_SUPPORTED_FMT( PlaYUVerStream, Write ); -#ifdef USE_FFMPEG - APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Save ); #endif #ifdef USE_OPENCV - APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Save ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Write ); #endif END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -105,15 +95,38 @@ std::vector PlaYUVerStream::stdResolutionSizes() return stdResList; } + +CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( std::string strFilename, bool bRead ) +{ + std::string currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 ); + currExt = lowercase( currExt ); + + std::vector supportedFmts; + if( bRead ) + { + supportedFmts = PlaYUVerStream::supportedReadFormats(); + } + else + { + supportedFmts = PlaYUVerStream::supportedWriteFormats(); + } + for( UInt i = 0; i < supportedFmts.size(); i++ ) + { + if( supportedFmts[i].formatExt == currExt ) + { + return supportedFmts[i].formatFct; + } + } + return NULL; +} + PlaYUVerStream::PlaYUVerStream() { m_bInit = false; - m_bIsInput = true; - m_bIsOpened = false; - m_bLoadAll = false; - m_iStreamHandler = INVALID_HANDLER; + m_pfctCreateHandler = NULL; m_pcStreamHandler = NULL; - m_pchFilename = NULL; + m_bIsInput = true; + m_bLoadAll = false; m_uiWidth = 0; m_uiHeight = 0; m_uiTotalFrameNum = 0; @@ -122,7 +135,6 @@ PlaYUVerStream::PlaYUVerStream() m_uiBitsPerPixel = 8; m_iEndianness = -1; m_dFrameRate = 30; - m_pStreamBuffer = NULL; m_cFilename = ""; m_pcCurrFrame = NULL; m_pcNextFrame = NULL; @@ -187,40 +199,6 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_iEndianness = endianness; m_dFrameRate = frame_rate; - m_pchFilename = new Char[m_cFilename.size() + 1]; - std::copy( m_cFilename.begin(), m_cFilename.end(), m_pchFilename ); - m_pchFilename[m_cFilename.size()] = '\0'; // don't forget the terminating 0 - - - m_iStreamHandler = INVALID_HANDLER; - std::string currExt = m_cFilename.substr( m_cFilename.find_last_of( "." ) + 1 ); - currExt = lowercase( currExt ); - - std::vector supportedFmts; - if( m_bIsInput ) - { - supportedFmts = supportedReadFormats(); - } - else - { - supportedFmts = supportedWriteFormats(); - } - for( UInt i = 0; i < supportedFmts.size(); i++ ) - { - if( supportedFmts[i].formatExt == currExt ) - { - m_pfctCreateHandler = supportedFmts[i].formatFct; - break; - } - } - -// if( m_iStreamHandler == INVALID_HANDLER ) -// { -// close(); -// throw "Invalid file format"; -// return m_bInit; -// } - // #ifdef USE_OPENCV // if( m_iStreamHandler == OPENCV_HANDLER ) @@ -239,6 +217,13 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in // } // #endif + m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); + if( !m_pfctCreateHandler ) + { + close(); + throw "[PlaYUVerStream] Invalid handler"; + } + m_pcStreamHandler = m_pfctCreateHandler(); if( !m_pcStreamHandler ) @@ -323,12 +308,12 @@ Bool PlaYUVerStream::reload() { m_pcStreamHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); - m_pcStreamHandler->closeHandler(); - if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) - { - throw "[PlaYUVerStream] Cannot open file using FFmpeg libs"; - } - m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); + m_pcStreamHandler->closeHandler(); + if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) + { + throw "[PlaYUVerStream] Cannot open file using FFmpeg libs"; + } + m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); if( m_uiWidth <= 0 || m_uiHeight <= 0 || m_iPixelFormat < 0 || m_uiTotalFrameNum < 1 ) @@ -350,7 +335,7 @@ Void PlaYUVerStream::close() if( !m_bInit ) return; - m_pcStreamHandler->closeHandler(); + m_pcStreamHandler->closeHandler(); @@ -366,12 +351,6 @@ Void PlaYUVerStream::close() m_ppcFrameBuffer = NULL; } - if( m_pStreamBuffer ) - freeMem1D( m_pStreamBuffer ); - - if( m_pchFilename ) - delete[] m_pchFilename; - m_bLoadAll = false; m_bInit = false; } @@ -482,18 +461,12 @@ Void PlaYUVerStream::readFrame() return; } - if( m_iStreamHandler == OPENCV_HANDLER ) + if( !m_pcStreamHandler->read( m_pcNextFrame ) ) { + throw "[PlaYUVerStream] Cannot read file"; return; } - if( !m_pcStreamHandler->read( m_pcNextFrame ) ) - { - throw "[PlaYUVerStream] Cannot read file"; - return; - } - - m_uiCurrFrameFileIdx++; return; } @@ -519,51 +492,14 @@ Bool PlaYUVerStream::saveFrame( const std::string& filename ) Bool PlaYUVerStream::saveFrame( const std::string& filename, PlaYUVerFrame *saveFrame ) { - Int iFileFormat = INVALID_HANDLER; - std::string fmtExt; - - std::string currExt = filename.substr( filename.find_last_of( "." ) + 1 ); - - std::vector supportedFmts = PlaYUVerStream::supportedSaveFormats(); - for( UInt i = 0; i < supportedFmts.size(); i++ ) + PlaYUVerStream auxSaveStream; + if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), saveFrame->getEndianness(), 1, false ) ) { - if( supportedFmts[i].formatExt == currExt ) - { - iFileFormat = i; - fmtExt = supportedFmts[i].formatExt[i]; - break; - } + return false; } - - if( iFileFormat != INVALID_HANDLER ) - { - if( fmtExt == "yuv" ) - { - PlaYUVerStream auxFrameStream; - if( !auxFrameStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), 1, false ) ) - { - return false; - } - auxFrameStream.writeFrame( saveFrame ); - auxFrameStream.close(); - return true; - } -#if 0 - else - { - saveFrame->fillRGBBuffer(); - QImage qimg = QImage( saveFrame->getRGBBuffer(), saveFrame->getWidth(), saveFrame->getHeight(), QImage::Format_RGB32 ); - return qimg.save( qtString ); - } -#endif -// #ifdef USE_OPENCV -// else -// { -// return LibOpenCVHandler::saveFrame( saveFrame, filename ); -// } -// #endif - } - return false; + auxSaveStream.writeFrame( saveFrame ); + auxSaveStream.close(); + return true; } Bool PlaYUVerStream::setNextFrame() diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index cac1e19..23984b5 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -85,7 +85,8 @@ public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - static std::vector supportedSaveFormats(); + + static CreateStreamHandlerFn findStreamHandler( std::string strFilename, bool bRead ); static std::vector stdResolutionSizes(); @@ -166,26 +167,11 @@ public: private: Bool m_bInit; - Bool m_bIsInput; - Bool m_bIsOpened; - - Bool m_bLoadAll; - - enum PlaYUVerStreamHandlers - { - INVALID_HANDLER = -1, - YUV_IO, - OPENCV_HANDLER, - FFMPEG, - TOTAL_HANDLERR - }; - Int m_iStreamHandler; CreateStreamHandlerFn m_pfctCreateHandler; PlaYUVerStreamHandlerIf* m_pcStreamHandler; + Bool m_bIsInput; std::string m_cFilename; - Char* m_pchFilename; - UInt m_uiWidth; UInt m_uiHeight; Int m_iPixelFormat; @@ -195,7 +181,7 @@ private: UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; - Byte* m_pStreamBuffer; + Bool m_bLoadAll; UInt m_uiFrameBufferSize; PlaYUVerFrame **m_ppcFrameBuffer; diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 7d52311..4d3037c 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -54,12 +54,6 @@ std::vector StreamHandlerLibav::supportedWriteFormats() END_REGIST_PLAYUVER_SUPPORTED_FMT; } -std::vector StreamHandlerLibav::supportedSaveFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - static int open_codec_context( int *stream_idx, AVFormatContext *m_cFmtCtx, enum AVMediaType type ) { int ret; @@ -162,8 +156,10 @@ Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } + m_strFormatName = uppercase (strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); const char *name = avcodec_get_name( m_cCodecCtx->codec_id ); - sprintf( m_acCodecName, "%s", name ); +// sprintf( m_acCodecName, "%s", name ); + m_strCodecName = name; Double fr = 30; if( m_cStream->avg_frame_rate.den && m_cStream->avg_frame_rate.num ) @@ -207,6 +203,8 @@ Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) m_uiBitsPerPixel = 16; m_iEndianness = 0; pix_fmt = AV_PIX_FMT_GRAY8; + case AV_PIX_FMT_PAL8: + pix_fmt = AV_PIX_FMT_GRAY8; break; } diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 4c0de4f..8af8fa2 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -62,7 +62,6 @@ public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - static std::vector supportedSaveFormats(); StreamHandlerLibav() { diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index f793fe5..9cc4c76 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -45,19 +45,13 @@ std::vector StreamHandlerOpenCV::supportedReadFormats() std::vector StreamHandlerOpenCV::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -std::vector StreamHandlerOpenCV::supportedSaveFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; -// APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) { - m_cFilename = m_cFilename; + m_cFilename = strFilename; return true; } @@ -93,8 +87,14 @@ Bool StreamHandlerOpenCV::read( PlaYUVerFrame* pcFrame ) Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) { + Bool bRet = false; cv::Mat* pcCvFrame = pcFrame->getCvMat(); - return cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); + if( pcCvFrame ) + { + bRet = cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); + delete pcCvFrame; + } + return bRet; } } // NAMESPACE diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index cd14dfc..edf203f 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -47,7 +47,6 @@ public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - static std::vector supportedSaveFormats(); StreamHandlerOpenCV() { From e9feb12367b30e12332fbb3a8403426d8c0cc6d6 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 2 Apr 2016 02:59:09 +0100 Subject: [PATCH 010/127] Add StreamHandlerPortableMap and change some files organisation --- lib/StreamHandlerPortableMap.cpp | 103 +++++++++++++++++++++++++++++++ lib/StreamHandlerPortableMap.h | 70 +++++++++++++++++++++ lib/StreamHandlerRaw.cpp | 99 +++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+) create mode 100644 lib/StreamHandlerPortableMap.cpp create mode 100644 lib/StreamHandlerPortableMap.h create mode 100644 lib/StreamHandlerRaw.cpp diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp new file mode 100644 index 0000000..699637a --- /dev/null +++ b/lib/StreamHandlerPortableMap.cpp @@ -0,0 +1,103 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file StreamHandlerPortableMap.cpp + * \ingroup PlaYUVerLib + * \brief Interface with opencv lib + */ + +#include +#include "StreamHandlerPortableMap.h" +#include "PlaYUVerFrame.h" +#include "PlaYUVerFramePixelFormats.h" +#include "LibMemory.h" + +namespace plaYUVer +{ + +std::vector StreamHandlerPortableMap::supportedReadFormats() +{ + INI_REGIST_PLAYUVER_SUPPORTED_FMT; + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable Grayscale Map ", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable Pix Map ", "ppm" ); + END_REGIST_PLAYUVER_SUPPORTED_FMT; +} + +std::vector StreamHandlerPortableMap::supportedWriteFormats() +{ + INI_REGIST_PLAYUVER_SUPPORTED_FMT; +// APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerPortableMap, Read ); + END_REGIST_PLAYUVER_SUPPORTED_FMT; +} + +Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput ) +{ + m_cFilename = strFilename; + return true; +} + +Void StreamHandlerPortableMap::closeHandler() +{ + +} + +Bool StreamHandlerPortableMap::configureBuffer( PlaYUVerFrame* pcFrame ) +{ + return true; +} + +Void StreamHandlerPortableMap::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) +{ +// rWidth = m_uiWidth; +// rHeight = m_uiHeight; +// rInputFormat = m_iPixelFormat; +// rBitsPerPel = m_uiBitsPerPixel; +// rEndianness = m_iEndianness; + rFrameRate = 1; +} + +UInt64 StreamHandlerPortableMap::calculateFrameNumber() +{ + return 1; +} + +Bool StreamHandlerPortableMap::seek( UInt64 iFrameNum ) +{ + return true; +} + +Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) +{ + return false; +} + +Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) +{ + Bool bRet = false; + cv::Mat* pcCvFrame = pcFrame->getCvMat(); + if( pcCvFrame ) + { + bRet = cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); + delete pcCvFrame; + } + return bRet; +} + +} // NAMESPACE diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h new file mode 100644 index 0000000..44a64ba --- /dev/null +++ b/lib/StreamHandlerPortableMap.h @@ -0,0 +1,70 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file StreamHandlerPortableMap.h + * \ingroup PlaYUVerLib + * \brief Interface with opencv lib + */ + +#ifndef __STREAMHANDLERPORTABLEMAP_H__ +#define __STREAMHANDLERPORTABLEMAP_H__ + +#include +#include +#include +#include +#include "PlaYUVerDefs.h" +#include "PlaYUVerStream.h" +#include "PlaYUVerStreamHandlerIf.h" + +namespace plaYUVer +{ + +class PlaYUVerFrame; + +class StreamHandlerPortableMap: public PlaYUVerStreamHandlerIf +{ + REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) + +public: + + static std::vector supportedReadFormats(); + static std::vector supportedWriteFormats(); + + StreamHandlerPortableMap() {} + ~StreamHandlerPortableMap() {} + + Bool openHandler( std::string strFilename, Bool bInput ); + Void closeHandler(); + Bool configureBuffer( PlaYUVerFrame* pcFrame ); + UInt64 calculateFrameNumber(); + Bool seek( UInt64 iFrameNum ); + Bool read( PlaYUVerFrame* pcFrame ); + Bool write( PlaYUVerFrame* pcFrame ); + + Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); + +private: + std::string m_cFilename; +}; + +} // NAMESPACE + +#endif // __STREAMHANDLERPORTABLEMAP_H__ diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp new file mode 100644 index 0000000..a669108 --- /dev/null +++ b/lib/StreamHandlerRaw.cpp @@ -0,0 +1,99 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file StreamHandlerRaw.cpp + * \ingroup PlaYUVerLib + * \brief Interface for raw (yuv) streams + */ + +#include +#include "StreamHandlerRaw.h" +#include "PlaYUVerFrame.h" +#include "PlaYUVerFramePixelFormats.h" +#include "LibMemory.h" + +namespace plaYUVer +{ + +Bool PlaYUVerRawHandler::openHandler( std::string strFilename, Bool bInput ) +{ + m_bIsInput = bInput; + m_pFile = NULL; + m_pFile = fopen( strFilename.c_str(), bInput ? "rb" : "wb" ); + if( m_pFile == NULL ) + { + return false; + } + m_strFormatName = "YUV"; + m_strCodecName = "Raw Video"; + return true; +} + +Void PlaYUVerRawHandler::closeHandler() +{ + if( m_pFile ) + fclose( m_pFile ); +} + +Bool PlaYUVerRawHandler::configureBuffer( PlaYUVerFrame* pcFrame ) +{ + return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); +} + + +UInt64 PlaYUVerRawHandler::calculateFrameNumber() +{ + if( !m_pFile || m_uiNBytesPerFrame == 0 ) + return 0; + fseek( m_pFile, 0, SEEK_END ); + UInt64 fileSize = ftell( m_pFile ); + fseek( m_pFile, 0, SEEK_SET ); + return ( fileSize / m_uiNBytesPerFrame ); +} + +Bool PlaYUVerRawHandler::seek( UInt64 iFrameNum ) +{ + if( m_bIsInput && m_pFile ) + { + fseek( m_pFile, iFrameNum >= 0 ? iFrameNum * m_uiNBytesPerFrame : 0, SEEK_SET ); + return true; + } + return false; +} + +Bool PlaYUVerRawHandler::read( PlaYUVerFrame* pcFrame ) +{ + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + pcFrame->frameFromBuffer( m_pStreamBuffer ); + return true; +} + +Bool PlaYUVerRawHandler::write( PlaYUVerFrame* pcFrame ) +{ + pcFrame->frameToBuffer( m_pStreamBuffer ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + return true; +} + +} // NAMESPACE From 51834ae5a7373be6e44378c903fae18a13b843e4 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 2 Apr 2016 04:04:19 +0100 Subject: [PATCH 011/127] Add support for portable maps from 1 to 6 --- lib/CMakeLists.txt | 2 + lib/PlaYUVerStream.cpp | 23 ++----- lib/PlaYUVerStreamHandlerIf.h | 13 ++-- lib/StreamHandlerLibav.cpp | 13 +++- lib/StreamHandlerLibav.h | 1 + lib/StreamHandlerOpenCV.cpp | 7 +++ lib/StreamHandlerOpenCV.h | 1 + lib/StreamHandlerPortableMap.cpp | 105 ++++++++++++++++++++----------- lib/StreamHandlerPortableMap.h | 12 ++-- lib/StreamHandlerRaw.h | 69 ++++---------------- 10 files changed, 120 insertions(+), 126 deletions(-) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 92a79c5..ec3f4aa 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -12,6 +12,8 @@ set(PlaYUVer_Lib_SRCS # PlaYUVerFrameStats.cpp # Stream PlaYUVerStream.cpp + StreamHandlerRaw.cpp + StreamHandlerPortableMap.cpp # Command Parser PlaYUVerCmdParser.cpp PlaYUVerProgramOptions.cpp diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 47cc857..f1210b0 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -30,7 +30,7 @@ #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" #include "StreamHandlerRaw.h" -#include "StreamHandlerPortable.h" +#include "StreamHandlerPortableMap.h" #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" @@ -47,6 +47,9 @@ std::vector PlaYUVerStream::supportedReadFormats() INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "gray" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Read ); #endif @@ -199,24 +202,6 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_iEndianness = endianness; m_dFrameRate = frame_rate; - -// #ifdef USE_OPENCV -// if( m_iStreamHandler == OPENCV_HANDLER ) -// { -// m_pcCurrFrame = LibOpenCVHandler::loadFrame( m_cFilename ); -// if( m_pcCurrFrame ) -// { -// m_uiWidth = m_pcCurrFrame->getWidth(); -// m_uiHeight = m_pcCurrFrame->getHeight(); -// m_iPixelFormat = m_pcCurrFrame->getPelFormat(); -// } -// m_pcNextFrame = NULL; -// m_uiFrameBufferSize = 0; -// m_uiFrameBufferIndex = 0; -// m_uiTotalFrameNum = 1; -// } -// #endif - m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); if( !m_pfctCreateHandler ) { diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index ff399a7..4619aaa 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -26,7 +26,7 @@ #define __PLAYUVERSTREAMHANDLERIF_H__ #include "PlaYUVerDefs.h" -#include "LibMemory.h" +#include "PlaYUVerFrame.h" namespace plaYUVer { @@ -51,17 +51,14 @@ public: virtual ~PlaYUVerStreamHandlerIf() { } + virtual Bool openHandler( std::string strFilename, Bool bInput ) = 0; - virtual UInt64 calculateFrameNumber() = 0; virtual Void closeHandler() = 0; + virtual Bool configureBuffer( PlaYUVerFrame* pcFrame ) = 0; + virtual UInt64 calculateFrameNumber() = 0; + virtual Bool seek( UInt64 iFrameNum ) = 0; virtual Bool read( PlaYUVerFrame* pcFrame ) = 0; virtual Bool write( PlaYUVerFrame* pcFrame ) = 0; - virtual Bool seek( UInt64 iFrameNum ) = 0; - - virtual Bool configureBuffer( PlaYUVerFrame* pcFrame ) - { - return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); - } virtual Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) { diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 4d3037c..ae9568b 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -203,9 +203,6 @@ Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) m_uiBitsPerPixel = 16; m_iEndianness = 0; pix_fmt = AV_PIX_FMT_GRAY8; - case AV_PIX_FMT_PAL8: - pix_fmt = AV_PIX_FMT_GRAY8; - break; } m_uiWidth = m_cCodecCtx->width; @@ -269,8 +266,18 @@ Void StreamHandlerLibav::closeHandler() av_free( m_cFrame ); } m_bHasStream = false; + + if( m_pStreamBuffer ) + freeMem1D( m_pStreamBuffer ); + } +Bool StreamHandlerLibav::configureBuffer( PlaYUVerFrame* pcFrame ) +{ + return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); +} + + Void StreamHandlerLibav::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) { rWidth = m_uiWidth; diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 8af8fa2..5b3344e 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -72,6 +72,7 @@ public: Bool openHandler( std::string strFilename, Bool bInput ); Void closeHandler(); + Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); Bool seek( UInt64 iFrameNum ); Bool read( PlaYUVerFrame* pcFrame ); diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 9cc4c76..38679ab 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -60,6 +60,12 @@ Void StreamHandlerOpenCV::closeHandler() } +Bool StreamHandlerOpenCV::configureBuffer( PlaYUVerFrame* pcFrame ) +{ + return true; +} + + Void StreamHandlerOpenCV::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) { // rWidth = m_uiWidth; @@ -70,6 +76,7 @@ Void StreamHandlerOpenCV::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFor rFrameRate = 1; } + UInt64 StreamHandlerOpenCV::calculateFrameNumber() { return 1; diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index edf203f..b63ba15 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -57,6 +57,7 @@ public: Bool openHandler( std::string strFilename, Bool bInput ); Void closeHandler(); + Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); Bool seek( UInt64 iFrameNum ); Bool read( PlaYUVerFrame* pcFrame ); diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index 699637a..e72b07a 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -32,47 +32,81 @@ namespace plaYUVer { -std::vector StreamHandlerPortableMap::supportedReadFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable Grayscale Map ", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable Pix Map ", "ppm" ); - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - -std::vector StreamHandlerPortableMap::supportedWriteFormats() -{ - INI_REGIST_PLAYUVER_SUPPORTED_FMT; -// APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerPortableMap, Read ); - END_REGIST_PLAYUVER_SUPPORTED_FMT; -} - Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput ) { - m_cFilename = strFilename; + m_bIsInput = bInput; + m_pFile = NULL; + m_pFile = fopen( strFilename.c_str(), bInput ? "rb" : "wb" ); + if( m_pFile == NULL ) + { + return false; + } + m_strFormatName = "PGM"; + m_strCodecName = "Raw Video"; + if( m_bIsInput ) + { + char line[101]; + do + { + fgets( line, 100, m_pFile ); + } + while( line[0] == '#' ); + sscanf( line,"P%d", &m_iMagicNumber ); + + do + { + fgets( line, 100, m_pFile ); + } + while( line[0] == '#' ); + sscanf( line,"%d %d", &m_iWidth, &m_iHeight ); + + if( m_iMagicNumber == 1 || m_iMagicNumber == 4 ) + { + m_uiBitsPerPixel = 1; + m_iMaxValue = 1; + m_iPixelFormat = PlaYUVerFrame::GRAY; + } + else + { + do + { + fgets( line, 100, m_pFile ); + } + while( line[0] == '#' ); + sscanf( line,"%d", &m_iMaxValue ); + + m_uiBitsPerPixel = log( m_iMaxValue + 1 )/log( 2 ); + m_iPixelFormat = m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; + } + } return true; } Void StreamHandlerPortableMap::closeHandler() { + if( m_pFile ) + fclose( m_pFile ); -} - -Bool StreamHandlerPortableMap::configureBuffer( PlaYUVerFrame* pcFrame ) -{ - return true; + if( m_pStreamBuffer ) + freeMem1D( m_pStreamBuffer ); } Void StreamHandlerPortableMap::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) { -// rWidth = m_uiWidth; -// rHeight = m_uiHeight; -// rInputFormat = m_iPixelFormat; -// rBitsPerPel = m_uiBitsPerPixel; -// rEndianness = m_iEndianness; + rWidth = m_iWidth; + rHeight = m_iHeight; + rInputFormat = m_iPixelFormat; + rBitsPerPel = m_uiBitsPerPixel; + rEndianness = 0; rFrameRate = 1; } +Bool StreamHandlerPortableMap::configureBuffer( PlaYUVerFrame* pcFrame ) +{ + return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); +} + + UInt64 StreamHandlerPortableMap::calculateFrameNumber() { return 1; @@ -85,19 +119,20 @@ Bool StreamHandlerPortableMap::seek( UInt64 iFrameNum ) Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) { - return false; + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + pcFrame->frameFromBuffer( m_pStreamBuffer ); + return true; } Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) { - Bool bRet = false; - cv::Mat* pcCvFrame = pcFrame->getCvMat(); - if( pcCvFrame ) - { - bRet = cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); - delete pcCvFrame; - } - return bRet; + pcFrame->frameToBuffer( m_pStreamBuffer ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + if( processed_bytes != m_uiNBytesPerFrame ) + return false; + return true; } } // NAMESPACE diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 44a64ba..4256b35 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -44,10 +44,6 @@ class StreamHandlerPortableMap: public PlaYUVerStreamHandlerIf REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) public: - - static std::vector supportedReadFormats(); - static std::vector supportedWriteFormats(); - StreamHandlerPortableMap() {} ~StreamHandlerPortableMap() {} @@ -62,7 +58,13 @@ public: Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); private: - std::string m_cFilename; + FILE* m_pFile; /**< The input file pointer >*/ + Int m_iMagicNumber; + Int m_iMaxValue; + Int m_iWidth; + Int m_iHeight; + Int m_iPixelFormat; + UInt m_uiBitsPerPixel; }; } // NAMESPACE diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index f4615b4..27bd0b9 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -18,12 +18,12 @@ */ /** - * \file PlaYUVerRawHandler.h + * \file StreamHandlerRaw.h * \brief Abstract class for stream handling */ -#ifndef __PLAYUVERRAWHANDLER_H__ -#define __PLAYUVERRAWHANDLER_H__ +#ifndef __STREAMHANDLERRAW_H__ +#define __STREAMHANDLERRAW_H__ #include "PlaYUVerDefs.h" #include "PlaYUVerStreamHandlerIf.h" @@ -47,62 +47,19 @@ public: PlaYUVerRawHandler() {} ~PlaYUVerRawHandler() {} - Bool openHandler( std::string strFilename, Bool bInput ) - { - m_bIsInput = bInput; - m_pFile = NULL; - m_pFile = fopen( strFilename.c_str(), bInput ? "rb" : "wb" ); - if( m_pFile == NULL ) - { - return false; - } - m_strFormatName = "YUV"; - m_strCodecName = "Raw Video"; - return true; - } - Void closeHandler() - { - if( m_pFile ) - fclose( m_pFile ); - } - UInt64 calculateFrameNumber() - { - if( !m_pFile || m_uiNBytesPerFrame == 0 ) - return 0; - fseek( m_pFile, 0, SEEK_END ); - UInt64 fileSize = ftell( m_pFile ); - fseek( m_pFile, 0, SEEK_SET ); - return ( fileSize / m_uiNBytesPerFrame ); - } - Bool seek( UInt64 iFrameNum ) - { - if( m_bIsInput && m_pFile ) - { - fseek( m_pFile, iFrameNum >= 0 ? iFrameNum * m_uiNBytesPerFrame : 0, SEEK_SET ); - return true; - } - return false; - } - Bool read( PlaYUVerFrame* pcFrame ) - { - UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); - if( processed_bytes != m_uiNBytesPerFrame ) - return false; - pcFrame->frameFromBuffer( m_pStreamBuffer ); - return true; - } - Bool write( PlaYUVerFrame* pcFrame ) - { - pcFrame->frameToBuffer( m_pStreamBuffer ); - UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); - if( processed_bytes != m_uiNBytesPerFrame ) - return false; - return true; - } + Bool openHandler( std::string strFilename, Bool bInput ); + Void closeHandler(); + Bool configureBuffer( PlaYUVerFrame* pcFrame ); + UInt64 calculateFrameNumber(); + Bool seek( UInt64 iFrameNum ); + Bool read( PlaYUVerFrame* pcFrame ); + Bool write( PlaYUVerFrame* pcFrame ); + + }; } // NAMESPACE -#endif // __PLAYUVERRAWHANDLER_H__ +#endif // __STREAMHANDLERRAW_H__ From 55ae2a0e7fb4921ff0a109097ebfafbe6d4f795f Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 3 Apr 2016 23:33:38 +0100 Subject: [PATCH 012/127] Change some variable to PlaYUVerStreamHandlerIf and make it friend of PlaYUVerStream --- lib/PlaYUVerStream.cpp | 124 +++++++++++++++++-------------- lib/PlaYUVerStream.h | 40 ++-------- lib/PlaYUVerStreamHandlerIf.h | 20 ++++- lib/StreamHandlerLibav.cpp | 11 --- lib/StreamHandlerLibav.h | 11 --- lib/StreamHandlerOpenCV.cpp | 13 +--- lib/StreamHandlerOpenCV.h | 4 - lib/StreamHandlerPortableMap.cpp | 60 ++++++++------- lib/StreamHandlerPortableMap.h | 6 -- 9 files changed, 126 insertions(+), 163 deletions(-) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index f1210b0..a29e2e0 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -47,9 +47,9 @@ std::vector PlaYUVerStream::supportedReadFormats() INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "gray" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Read ); #endif @@ -127,17 +127,11 @@ PlaYUVerStream::PlaYUVerStream() { m_bInit = false; m_pfctCreateHandler = NULL; - m_pcStreamHandler = NULL; + m_pcHandler = NULL; m_bIsInput = true; m_bLoadAll = false; - m_uiWidth = 0; - m_uiHeight = 0; m_uiTotalFrameNum = 0; m_iCurrFrameNum = -1; - m_iPixelFormat = -1; - m_uiBitsPerPixel = 8; - m_iEndianness = -1; - m_dFrameRate = 30; m_cFilename = ""; m_pcCurrFrame = NULL; m_pcNextFrame = NULL; @@ -154,11 +148,11 @@ PlaYUVerStream::~PlaYUVerStream() std::string PlaYUVerStream::getFormatName() { - return !m_pcStreamHandler ? "" : m_pcStreamHandler->getFormatName(); + return !m_pcHandler ? "" : m_pcHandler->getFormatName(); } std::string PlaYUVerStream::getCodecName() { - return !m_pcStreamHandler ? "" : m_pcStreamHandler->getCodecName(); + return !m_pcHandler ? "" : m_pcHandler->getCodecName(); } Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) @@ -194,13 +188,6 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in } m_bInit = false; m_bIsInput = bInput; - m_cFilename = filename; - m_uiWidth = width; - m_uiHeight = height; - m_iPixelFormat = input_format; - m_uiBitsPerPixel = bitsPel; - m_iEndianness = endianness; - m_dFrameRate = frame_rate; m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); if( !m_pfctCreateHandler ) @@ -209,23 +196,34 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in throw "[PlaYUVerStream] Invalid handler"; } - m_pcStreamHandler = m_pfctCreateHandler(); + m_pcHandler = m_pfctCreateHandler(); - if( !m_pcStreamHandler ) + if( !m_pcHandler ) { close(); throw "[PlaYUVerStream] Invalid handler"; } - if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) + m_cFilename = filename; + + m_pcHandler->m_cFilename = filename; + m_pcHandler->m_uiWidth = width; + m_pcHandler->m_uiHeight = height; + m_pcHandler->m_iPixelFormat = input_format; + m_pcHandler->m_uiBitsPerPixel = bitsPel; + m_pcHandler->m_iEndianness = endianness; + m_pcHandler->m_dFrameRate = frame_rate; + + + if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { close(); throw "[PlaYUVerStream] Cannot open file"; return m_bInit; } - m_pcStreamHandler->getFormat( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness, m_dFrameRate ); - if( m_uiWidth <= 0 || m_uiHeight <= 0 || m_iPixelFormat < 0 ) + + if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 ) { close(); throw "[PlaYUVerStream] Incorrect configuration"; @@ -239,7 +237,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel, m_iEndianness ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel, m_pcHandler->m_iEndianness ); } catch( const char *msg ) { @@ -251,11 +249,11 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_uiFrameBufferIndex = 0; m_pcCurrFrame = m_ppcFrameBuffer[m_uiFrameBufferIndex]; - m_pcStreamHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); + m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); if( m_bIsInput ) { - m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); + m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); } if( m_bIsInput && m_uiTotalFrameNum <= 0 ) @@ -265,21 +263,13 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in return m_bInit; } - if( !m_pcStreamHandler->configureBuffer( m_pcCurrFrame ) ) + if( !m_pcHandler->configureBuffer( m_pcCurrFrame ) ) { close(); throw "[PlaYUVerStream] Cannot allocated memory"; return m_bInit; } - if( m_pcCurrFrame ) - { - m_uiWidth = m_pcCurrFrame->getWidth(); - m_uiHeight = m_pcCurrFrame->getHeight(); - m_iPixelFormat = m_pcCurrFrame->getPelFormat(); - m_uiBitsPerPixel = m_pcCurrFrame->getBitsPel(); - } - m_iCurrFrameNum = -1; m_bInit = true; @@ -291,17 +281,16 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in Bool PlaYUVerStream::reload() { - m_pcStreamHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); - - m_pcStreamHandler->closeHandler(); - if( !m_pcStreamHandler->openHandler( m_cFilename, m_bIsInput ) ) + m_pcHandler->closeHandler(); + if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { throw "[PlaYUVerStream] Cannot open file using FFmpeg libs"; } - m_uiTotalFrameNum = m_pcStreamHandler->calculateFrameNumber(); + m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); + m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); - - if( m_uiWidth <= 0 || m_uiHeight <= 0 || m_iPixelFormat < 0 || m_uiTotalFrameNum < 1 ) + if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 + || m_pcHandler->m_iPixelFormat < 0 || m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) { return false; } @@ -320,7 +309,7 @@ Void PlaYUVerStream::close() if( !m_bInit ) return; - m_pcStreamHandler->closeHandler(); + m_pcHandler->closeHandler(); @@ -340,16 +329,43 @@ Void PlaYUVerStream::close() m_bInit = false; } +std::string PlaYUVerStream::getFileName() +{ + return m_cFilename; +} + +UInt PlaYUVerStream::getFrameNum() +{ + return m_uiTotalFrameNum; +} +UInt PlaYUVerStream::getWidth() const +{ + return m_pcHandler->m_uiWidth; +} +UInt PlaYUVerStream::getHeight() const +{ + return m_pcHandler->m_uiHeight; +} +Double PlaYUVerStream::getFrameRate() +{ + return m_pcHandler->m_dFrameRate; +} + +Int PlaYUVerStream::getCurrFrameNum() +{ + return m_iCurrFrameNum; +} + Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ) { if( m_bInit ) { - rWidth = m_uiWidth; - rHeight = m_uiHeight; - rInputFormat = m_iPixelFormat; - rBitsPerPel = m_uiBitsPerPixel; - rEndianness = m_iEndianness; - rFrameRate = m_dFrameRate; + rWidth = m_pcHandler->m_uiWidth; + rHeight = m_pcHandler->m_uiHeight; + rInputFormat = m_pcHandler->m_iPixelFormat; + rBitsPerPel = m_pcHandler->m_uiBitsPerPixel; + rEndianness = m_pcHandler->m_iEndianness; + rFrameRate = m_pcHandler->m_dFrameRate; } else { @@ -382,7 +398,7 @@ Void PlaYUVerStream::loadAll() getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); if( !m_ppcFrameBuffer[i] ) { close(); @@ -446,7 +462,7 @@ Void PlaYUVerStream::readFrame() return; } - if( !m_pcStreamHandler->read( m_pcNextFrame ) ) + if( !m_pcHandler->read( m_pcNextFrame ) ) { throw "[PlaYUVerStream] Cannot read file"; return; @@ -463,7 +479,7 @@ Void PlaYUVerStream::writeFrame() Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) { - if( !m_pcStreamHandler->write( pcFrame ) ) + if( !m_pcHandler->write( pcFrame ) ) { throw "[PlaYUVerStream] Cannot write into the file"; } @@ -568,7 +584,7 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) return true; } - if( !m_pcStreamHandler->seek( new_frame_num ) ) + if( !m_pcHandler->seek( new_frame_num ) ) { throw "[PlaYUVerStream] Cannot write into the file"; } diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 23984b5..95a2dbb 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -107,11 +107,15 @@ public: Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); - Bool reload(); - Void close(); + std::string getFileName(); + UInt getFrameNum(); + UInt getWidth() const; + UInt getHeight() const; + Int getCurrFrameNum(); + Double getFrameRate(); Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ); Void loadAll(); @@ -137,47 +141,17 @@ public: return m_bInit; } - std::string getFileName() - { - return m_cFilename; - } - UInt getFrameNum() - { - return m_uiTotalFrameNum; - } - UInt getWidth() const - { - return m_uiWidth; - } - UInt getHeight() const - { - return m_uiHeight; - } - Int getCurrFrameNum() - { - return m_iCurrFrameNum; - } - Double getFrameRate() - { - return m_dFrameRate; - } Void getDuration( Int* duration_array ); private: Bool m_bInit; CreateStreamHandlerFn m_pfctCreateHandler; - PlaYUVerStreamHandlerIf* m_pcStreamHandler; + PlaYUVerStreamHandlerIf* m_pcHandler; Bool m_bIsInput; std::string m_cFilename; - UInt m_uiWidth; - UInt m_uiHeight; - Int m_iPixelFormat; - UInt m_uiBitsPerPixel; - Int m_iEndianness; - Double m_dFrameRate; UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 4619aaa..f49509c 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -26,6 +26,7 @@ #define __PLAYUVERSTREAMHANDLERIF_H__ #include "PlaYUVerDefs.h" +#include "PlaYUVerStream.h" #include "PlaYUVerFrame.h" namespace plaYUVer @@ -43,10 +44,17 @@ namespace plaYUVer */ class PlaYUVerStreamHandlerIf { + friend class PlaYUVerStream; public: PlaYUVerStreamHandlerIf() { m_bIsInput = true; + m_uiWidth = 0; + m_uiHeight = 0; + m_iPixelFormat = -1; + m_uiBitsPerPixel = 8; + m_iEndianness = -1; + m_dFrameRate = 30; } virtual ~PlaYUVerStreamHandlerIf() { @@ -60,10 +68,6 @@ public: virtual Bool read( PlaYUVerFrame* pcFrame ) = 0; virtual Bool write( PlaYUVerFrame* pcFrame ) = 0; - virtual Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) - { - return; - } Void setBytesPerFrame( UInt64 uiNBytes ) { m_uiNBytesPerFrame = uiNBytes; @@ -79,6 +83,14 @@ public: protected: Bool m_bIsInput; + std::string m_cFilename; + UInt m_uiWidth; + UInt m_uiHeight; + Int m_iPixelFormat; + UInt m_uiBitsPerPixel; + Int m_iEndianness; + Double m_dFrameRate; + Byte* m_pStreamBuffer; UInt64 m_uiNBytesPerFrame; std::string m_strFormatName; diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index ae9568b..87d29b1 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -278,17 +278,6 @@ Bool StreamHandlerLibav::configureBuffer( PlaYUVerFrame* pcFrame ) } -Void StreamHandlerLibav::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) -{ - rWidth = m_uiWidth; - rHeight = m_uiHeight; - rInputFormat = m_iPixelFormat; - rBitsPerPel = m_uiBitsPerPixel; - rEndianness = m_iEndianness; - rFrameRate = m_dFrameRate; -} - - UInt64 StreamHandlerLibav::calculateFrameNumber() { UInt64 num_frames; diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 5b3344e..90c3d9e 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -78,8 +78,6 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); - UInt getStreamDuration() { return m_uiSecs; @@ -90,13 +88,6 @@ public: private: - UInt m_uiWidth; - UInt m_uiHeight; - Int m_iPixelFormat; - UInt m_uiBitsPerPixel; - Int m_iEndianness; - Double m_dFrameRate; - AVFormatContext* m_cFmtCtx; AVCodecContext* m_cCodecCtx; AVStream* m_cStream; @@ -106,8 +97,6 @@ private: Bool m_bHasStream; - Char m_acFormatName[20]; - Char m_acCodecName[20]; UInt64 m_uiSecs; UInt64 m_uiMicroSec; diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 38679ab..73969e8 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -52,6 +52,7 @@ std::vector StreamHandlerOpenCV::supportedWriteFormats( Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) { m_cFilename = strFilename; + m_dFrameRate = 1; return true; } @@ -65,18 +66,6 @@ Bool StreamHandlerOpenCV::configureBuffer( PlaYUVerFrame* pcFrame ) return true; } - -Void StreamHandlerOpenCV::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) -{ -// rWidth = m_uiWidth; -// rHeight = m_uiHeight; -// rInputFormat = m_iPixelFormat; -// rBitsPerPel = m_uiBitsPerPixel; -// rEndianness = m_iEndianness; - rFrameRate = 1; -} - - UInt64 StreamHandlerOpenCV::calculateFrameNumber() { return 1; diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index b63ba15..affe797 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -63,10 +63,6 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); - -private: - std::string m_cFilename; }; } // NAMESPACE diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index e72b07a..c7f04dd 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -46,19 +46,10 @@ Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput if( m_bIsInput ) { char line[101]; - do - { - fgets( line, 100, m_pFile ); - } - while( line[0] == '#' ); + while( fgets( line, 100, m_pFile ) && line[0] == '#' ); sscanf( line,"P%d", &m_iMagicNumber ); - - do - { - fgets( line, 100, m_pFile ); - } - while( line[0] == '#' ); - sscanf( line,"%d %d", &m_iWidth, &m_iHeight ); + while( fgets( line, 100, m_pFile ) && line[0] == '#' ); + sscanf( line,"%u %u", &m_uiWidth, &m_uiHeight ); if( m_iMagicNumber == 1 || m_iMagicNumber == 4 ) { @@ -68,17 +59,34 @@ Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput } else { - do - { - fgets( line, 100, m_pFile ); - } - while( line[0] == '#' ); + while( fgets( line, 100, m_pFile ) && line[0] == '#' ); sscanf( line,"%d", &m_iMaxValue ); - m_uiBitsPerPixel = log( m_iMaxValue + 1 )/log( 2 ); m_iPixelFormat = m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; } } + else + { + m_iMaxValue = ( 1 << m_uiBitsPerPixel ) - 1; + if( m_uiBitsPerPixel == 1 ) + { + m_iMagicNumber = 4; + } + else if( m_iPixelFormat == PlaYUVerFrame::GRAY ) + { + m_iMagicNumber = 5; + } + else if( m_iPixelFormat == PlaYUVerFrame::RGB24 ) + { + m_iMagicNumber = 6; + } + else + { + return false; + } + } + m_iEndianness = 0; + m_dFrameRate = 1; return true; } @@ -91,16 +99,6 @@ Void StreamHandlerPortableMap::closeHandler() freeMem1D( m_pStreamBuffer ); } -Void StreamHandlerPortableMap::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ) -{ - rWidth = m_iWidth; - rHeight = m_iHeight; - rInputFormat = m_iPixelFormat; - rBitsPerPel = m_uiBitsPerPixel; - rEndianness = 0; - rFrameRate = 1; -} - Bool StreamHandlerPortableMap::configureBuffer( PlaYUVerFrame* pcFrame ) { return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); @@ -128,6 +126,12 @@ Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) { + fseek( m_pFile, 0, SEEK_SET ); + fprintf( m_pFile, "P%d\n%d %d\n", m_iMagicNumber, m_uiWidth, m_uiHeight ); + if( m_iMagicNumber > 4 ) + { + fprintf( m_pFile, "%d\n", m_iMaxValue ); + } pcFrame->frameToBuffer( m_pStreamBuffer ); UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 4256b35..a64018b 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -55,16 +55,10 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, Double& rFrameRate ); - private: FILE* m_pFile; /**< The input file pointer >*/ Int m_iMagicNumber; Int m_iMaxValue; - Int m_iWidth; - Int m_iHeight; - Int m_iPixelFormat; - UInt m_uiBitsPerPixel; }; } // NAMESPACE From 4053b47297e32bf50f54e8ea5f46648bc5755cc8 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 4 Apr 2016 00:44:25 +0100 Subject: [PATCH 013/127] Fix big endian and little endian read and write buffer --- lib/PlaYUVerFrame.cpp | 47 +++++++++++++++++++++++++----------------- lib/PlaYUVerStream.cpp | 3 +++ 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 4e54296..a861c46 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -404,19 +404,18 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) Byte* pTmpBuff; Pel* pPel; UInt bytesPixel = ( m_uiBitsPel - 1 ) / 8 + 1; - UInt shiftInput, shiftOutput; Int ratioH, ratioW, step; - UInt i, ch, b; + UInt i, ch; + Int startByte = 0; + Int endByte = bytesPixel; + Int incByte = 1; + Int b; - if( m_iEndianness == 1 ) + if( m_iEndianness == 0 ) { - shiftInput = 8; - shiftOutput = 0; - } - else - { - shiftInput = 0; - shiftOutput = 8; + startByte = bytesPixel - 1; + endByte = -1; + incByte = -1; } ppBuff[0] = Buff; @@ -431,18 +430,18 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) { ratioW = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - step = m_pcPelFormat->comp[ch].step_minus1 + 1; + step = m_pcPelFormat->comp[ch].step_minus1; pPel = m_pppcInputPel[ch][0]; pTmpBuff = ppBuff[m_pcPelFormat->comp[ch].plane] + ( m_pcPelFormat->comp[ch].offset_plus1 - 1 ); for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) { - *pPel = *pTmpBuff; - for( b = 1; b < bytesPixel; b++ ) + *pPel = 0; + for( b = startByte; b != endByte; b += incByte ) { + *pPel += *pTmpBuff << ( b * 8 ); pTmpBuff++; - *pPel = ( *pPel << shiftOutput ) + ( *pTmpBuff << shiftInput ); } pPel++; pTmpBuff += step; @@ -459,7 +458,18 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) Byte* pTmpBuff; Pel* pTmpPel; Int ratioH, ratioW, step; - UInt i, ch, b; + UInt i, ch; + Int startByte = 0; + Int endByte = bytesPixel; + Int incByte = 1; + Int b; + + if( m_iEndianness == 0 ) + { + startByte = bytesPixel - 1; + endByte = -1; + incByte = -1; + } ppBuff[0] = output_buffer; for( Int i = 1; i < MAX_NUMBER_PLANES; i++ ) @@ -473,18 +483,17 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) { ratioW = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - step = m_pcPelFormat->comp[ch].step_minus1 + 1; + step = m_pcPelFormat->comp[ch].step_minus1; pTmpPel = m_pppcInputPel[ch][0]; pTmpBuff = ppBuff[m_pcPelFormat->comp[ch].plane]; for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) { - *pTmpBuff = ( *pTmpPel & 0x00FF ); - for( b = 1; b < bytesPixel; b++ ) + for( b = startByte; b != endByte; b += incByte ) { + *pTmpBuff = *pTmpPel >> ( 8 * b ); pTmpBuff++; - *pTmpBuff = ( *pTmpPel >> ( 8 * b ) ) & 0x00FF; } pTmpPel++; pTmpBuff += step; diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index a29e2e0..ea76ad5 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -63,6 +63,9 @@ std::vector PlaYUVerStream::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Write ); #endif From 1abbaf20927e3410eb12f8d29b3836e587fb785d Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 4 Apr 2016 17:37:21 +0100 Subject: [PATCH 014/127] Check number of inputs for quality --- tools/PlaYUVerTools.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 30a684d..71847b9 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -184,11 +184,11 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) if( m_cCmdLineHandler.Opts()["quality"]->count() ) { std::string qualityMetric = m_cCmdLineHandler.m_strQualityMetric; -// if( m_apcInputStreams.size() != 2 ) -// { -// m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of inputs! " ); -// return 2; -// } + if( m_apcInputStreams.size() < 2 ) + { + m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of inputs! " ); + return 2; + } for( UInt i = 0; i < PlaYUVerFrame::supportedQualityMetricsList().size(); i++ ) { if( lowercase( PlaYUVerFrame::supportedQualityMetricsList()[i] ) == lowercase( qualityMetric ) ) From 41e81dc2662e5843c89ffc5316522d22bce00ea3 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 4 Apr 2016 17:41:50 +0100 Subject: [PATCH 015/127] Fix quality log --- tools/PlaYUVerTools.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 71847b9..6339727 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -382,6 +382,7 @@ Int PlaYUVerTools::QualityOperation() { m_cCmdLineHandler.log( LOG_INFO, " %5.3f", adAverageQuality[s][c] ); } + m_cCmdLineHandler.log( LOG_RESULT, " " ); } m_cCmdLineHandler.log( LOG_INFO, "\n" ); return 0; From 51767e48f15680ab8a445e3e7adb5aed250019dd Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 4 Apr 2016 18:28:56 +0100 Subject: [PATCH 016/127] Format output of quality --- tools/PlaYUVerTools.cpp | 46 +++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 6339727..e6ca68f 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -334,12 +334,45 @@ Int PlaYUVerTools::SaveOperation() Int PlaYUVerTools::QualityOperation() { + const char *pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); PlaYUVerFrame* apcCurrFrame[MAX_NUMBER_INPUTS]; Bool abEOF[MAX_NUMBER_INPUTS]; Double adAverageQuality[MAX_NUMBER_INPUTS - 1][MAX_NUMBER_COMPONENTS]; Double dQuality; - m_cCmdLineHandler.log( LOG_INFO, " Measuring Quality using %s ... \n", PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str() ); + std::string metric_fmt = " "; + switch( m_uiQualityMetric ) + { + case PlaYUVerFrame::PSNR_METRIC: + //"PSNR_0_0" + metric_fmt += " %6.3f "; + break; + case PlaYUVerFrame::SSIM_METRIC: + //"SSIM_0_0" + metric_fmt += " %6.4f "; + break; + case PlaYUVerFrame::MSE_METRIC: + //"MSE_0_0" + metric_fmt += "%7.2f"; + break; + default: + metric_fmt += " %6.3f "; + } + metric_fmt += " "; + + m_cCmdLineHandler.log( LOG_INFO, " Measuring Quality using %s ... \n", pchQualityMetricName ); + m_cCmdLineHandler.log( LOG_INFO, "# Frame ", pchQualityMetricName ); + + for( UInt s = 1; s < m_apcInputStreams.size(); s++ ) + { + for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) + { + m_cCmdLineHandler.log( LOG_INFO, "%s_%d_%d ", pchQualityMetricName, s, c ); + } + m_cCmdLineHandler.log( LOG_INFO, " " ); + } + + m_cCmdLineHandler.log( LOG_INFO, "\n" ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) { @@ -351,7 +384,7 @@ Int PlaYUVerTools::QualityOperation() } for( UInt frame = 0; frame < m_uiNumberOfFrames; frame++ ) { - m_cCmdLineHandler.log( LOG_INFO, " %3d", frame ); + m_cCmdLineHandler.log( LOG_INFO, " %3d ", frame ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) apcCurrFrame[s] = m_apcInputStreams[s]->getCurrFrame(); @@ -362,8 +395,9 @@ Int PlaYUVerTools::QualityOperation() { dQuality = apcCurrFrame[s]->getQuality( m_uiQualityMetric, apcCurrFrame[0], c ); adAverageQuality[s - 1][c] = ( adAverageQuality[s - 1][c] * Double( frame ) + dQuality ) / Double( frame + 1 ); - m_cCmdLineHandler.log( LOG_RESULT, " %5.3f", dQuality ); + m_cCmdLineHandler.log( LOG_RESULT, metric_fmt.c_str(), dQuality ); } + m_cCmdLineHandler.log( LOG_RESULT, " " ); } m_cCmdLineHandler.log( LOG_RESULT, "\n" ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) @@ -375,14 +409,14 @@ Int PlaYUVerTools::QualityOperation() } } } - m_cCmdLineHandler.log( LOG_INFO, "\n Mean Values: \n " ); + m_cCmdLineHandler.log( LOG_INFO, "\n Mean Values: \n " ); for( UInt s = 0; s < m_apcInputStreams.size() - 1; s++ ) { for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) { - m_cCmdLineHandler.log( LOG_INFO, " %5.3f", adAverageQuality[s][c] ); + m_cCmdLineHandler.log( LOG_INFO, metric_fmt.c_str(), adAverageQuality[s][c] ); } - m_cCmdLineHandler.log( LOG_RESULT, " " ); + m_cCmdLineHandler.log( LOG_RESULT, " " ); } m_cCmdLineHandler.log( LOG_INFO, "\n" ); return 0; From 960ff3f1cf488cb7acde4e8f9adfd5aac37d3429 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 4 Apr 2016 23:58:36 +0100 Subject: [PATCH 017/127] Fix output --- tools/PlaYUVerTools.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index e6ca68f..a5844ce 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -361,7 +361,7 @@ Int PlaYUVerTools::QualityOperation() metric_fmt += " "; m_cCmdLineHandler.log( LOG_INFO, " Measuring Quality using %s ... \n", pchQualityMetricName ); - m_cCmdLineHandler.log( LOG_INFO, "# Frame ", pchQualityMetricName ); + m_cCmdLineHandler.log( LOG_INFO, "# Frame ", pchQualityMetricName ); for( UInt s = 1; s < m_apcInputStreams.size(); s++ ) { @@ -384,7 +384,7 @@ Int PlaYUVerTools::QualityOperation() } for( UInt frame = 0; frame < m_uiNumberOfFrames; frame++ ) { - m_cCmdLineHandler.log( LOG_INFO, " %3d ", frame ); + m_cCmdLineHandler.log( LOG_INFO, " %3d ", frame ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) apcCurrFrame[s] = m_apcInputStreams[s]->getCurrFrame(); @@ -409,7 +409,7 @@ Int PlaYUVerTools::QualityOperation() } } } - m_cCmdLineHandler.log( LOG_INFO, "\n Mean Values: \n " ); + m_cCmdLineHandler.log( LOG_INFO, "\n Mean Values: \n " ); for( UInt s = 0; s < m_apcInputStreams.size() - 1; s++ ) { for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) From 903af894c02d0a6c743b10132b72b0aa900a543a Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 6 Apr 2016 18:43:04 +0100 Subject: [PATCH 018/127] Remove opencv from pgm handler --- lib/StreamHandlerPortableMap.h | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index a64018b..5780e7b 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -29,7 +29,6 @@ #include #include #include -#include #include "PlaYUVerDefs.h" #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" From 0afae69f94ac67e3bcf03734c98764206a9168f8 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 6 Apr 2016 18:45:58 +0100 Subject: [PATCH 019/127] Fix missing include --- lib/StreamHandlerPortableMap.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index c7f04dd..9784b96 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -24,6 +24,7 @@ */ #include +#include #include "StreamHandlerPortableMap.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" From eff93de754017a3fa9c718b986ddfd1f813fb12c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 6 Apr 2016 22:43:34 +0100 Subject: [PATCH 020/127] Add WeightedPSNR module --- app/PlaYUVerAppModuleIf.cpp | 16 +++-- app/PlaYUVerAppModuleIf.h | 2 +- lib/CMakeLists.txt | 2 +- modules/CMakeLists.txt | 1 + modules/PlaYUVerModuleFactory.cpp | 1 + modules/WeightedPSNR.cpp | 116 ++++++++++++++++++++++++++++++ modules/WeightedPSNR.h | 56 +++++++++++++++ 7 files changed, 186 insertions(+), 8 deletions(-) create mode 100644 modules/WeightedPSNR.cpp create mode 100644 modules/WeightedPSNR.h diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index e71b17d..c4d15d8 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -58,14 +58,18 @@ Void PlaYUVerAppModuleIf::update() Bool PlaYUVerAppModuleIf::apply( Bool isPlaying, Bool disableThreads ) { Bool bRet = false; + QApplication::setOverrideCursor( Qt::WaitCursor ); - if( m_pcDisplaySubWindow ) + if( m_pcModule->m_iModuleType == FRAME_PROCESSING_MODULE ) { - m_pcDisplaySubWindow->setFillWindow( true ); - } - else - { - m_pcSubWindow[0]->setFillWindow( true ); + if( m_pcDisplaySubWindow ) + { + m_pcDisplaySubWindow->setFillWindow( true ); + } + else + { + m_pcSubWindow[0]->setFillWindow( true ); + } } if( !( isPlaying && ( m_pcModule->m_uiModuleRequirements & MODULE_REQUIRES_SKIP_WHILE_PLAY ) ) ) { diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index 3bfb424..817055b 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -40,7 +40,7 @@ class QAction; namespace plaYUVer { -#define PLAYUVER_THREADED_MODULES +//#define PLAYUVER_THREADED_MODULES class VideoSubWindow; diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index ec3f4aa..2f4ebc9 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -9,7 +9,7 @@ set(PlaYUVer_Lib_SRCS PlaYUVerFrame.cpp PlaYUVerPixel.cpp PlaYUVerFramePixelFormats.cpp - # PlaYUVerFrameStats.cpp + # PlaYUVerFrameStats.cpp # Stream PlaYUVerStream.cpp StreamHandlerRaw.cpp diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index db5a07e..c45cca9 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -43,6 +43,7 @@ ADD_MODULE( SetChromaHalfScale "SetChromaHalfScale" ) ADD_MODULE( EightBitsSampling "EightBitsSampling" ) ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) +ADD_MODULE( WeightedPSNR "WeightedPSNR" ) IF( USE_OPENCV ) ADD_MODULE( DisparityStereoBM "DisparityStereoBM" ) ADD_MODULE( DisparityStereoSGBM "DisparityStereoSGBM" ) diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index 961295b..957aa10 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -48,6 +48,7 @@ PlaYUVerModuleFactory::PlaYUVerModuleFactory() Register( "FrameShift", &FrameShift::Create ); Register( "EightBitsSampling", &EightBitsSampling::Create ); Register( "LumaAverage", &LumaAverage::Create ); + Register( "WeightedPSNR", &WeightedPSNR::Create ); #ifdef USE_OPENCV //Register( "DisparityStereoVar", &DisparityStereoVar::Create ); Register( "DisparityStereoBM", &DisparityStereoBM::Create ); diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp new file mode 100644 index 0000000..85130ce --- /dev/null +++ b/modules/WeightedPSNR.cpp @@ -0,0 +1,116 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file WeightedPSNR.cpp + * \brief Weighted PSNR quality module + */ + +#include "WeightedPSNR.h" +#include +#include + +namespace plaYUVer +{ + +WeightedPSNR::WeightedPSNR() +{ + /* Module Definition */ + m_iModuleAPI = MODULE_API_2; + m_iModuleType = FRAME_MEASUREMENT_MODULE; + m_pchModuleCategory = "Quality"; + m_pchModuleName = "WeightedPSNR"; + m_pchModuleTooltip = "Measure the weighted PSNR between two images"; + m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; + m_uiNumberOfFrames = MODULE_REQUIRES_THREE_FRAMES; + + m_cModuleOptions.addOptions()/**/ + ( "Component", m_uiComponent, "Select the component to compute quality [0]" ); + + m_uiComponent = 0; + +} + +Bool WeightedPSNR::create( std::vector apcFrameList ) +{ + _BASIC_MODULE_API_2_CHECK_ + + for( UInt i = 1; i < apcFrameList.size(); i++ ) + { + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + return false; + } + return true; +} + +Double measureWMSE( Int component, PlaYUVerFrame* Org, PlaYUVerFrame* Rec, PlaYUVerFrame* Mask ) +{ + Pel* pMaskPelYUV = Mask->getPelBufferYUV()[0][0]; + Pel* pRecPelYUV = Rec->getPelBufferYUV()[component][0]; + Pel* pOrgPelYUV = Org->getPelBufferYUV()[component][0]; + + Double aux_pel_1, aux_pel_2, aux_pel_mask; + Int diff = 0; + Double ssd = 0; + UInt count = 0; + + UInt numberOfPixels = 0; + if( component == LUMA ) + { + numberOfPixels = Org->getHeight() * Org->getWidth(); + } + else + { + numberOfPixels = Rec->getChromaLength(); + } + + for( UInt i = 0; i < numberOfPixels; i++ ) + { + aux_pel_mask = *pMaskPelYUV++; + aux_pel_1 = *pRecPelYUV++; + aux_pel_2 = *pOrgPelYUV++; + diff = aux_pel_1 - aux_pel_2; + ssd += ( aux_pel_mask * diff * diff ); + count += aux_pel_mask; + } + if( ssd == 0.0 ) + { + return 0.0; + } + return ssd / Double( count ); +} + + +Double WeightedPSNR::measure( std::vector apcFrameList ) +{ + Double dPSNR = 100; + Double dMaxValue = ( 1 << apcFrameList[1]->getBitsPel() ) - 1; + Double dMSE = measureWMSE( m_uiComponent, apcFrameList[1], apcFrameList[2], apcFrameList[0] ); + if( dMSE != 0 ) + dPSNR = 10 * log10( ( dMaxValue * dMaxValue ) / dMSE ); + return dPSNR; +} + +Void WeightedPSNR::destroy() +{ + +} + +} // NAMESPACE + diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h new file mode 100644 index 0000000..0ca0f06 --- /dev/null +++ b/modules/WeightedPSNR.h @@ -0,0 +1,56 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file WeightedPSNR.h + * \brief Frame Difference module + */ + +#ifndef __WEIGHTEDPSNR_H__ +#define __WEIGHTEDPSNR_H__ + +#include "lib/PlaYUVerModuleIf.h" + +#include + +namespace plaYUVer +{ + +class WeightedPSNR: public PlaYUVerModuleIf +{ +REGISTER_CLASS_FACTORY( WeightedPSNR ) + +private: + UInt m_uiComponent; + +public: + WeightedPSNR(); + virtual ~WeightedPSNR() + { + } + Bool create( std::vector apcFrameList ); + Double measure( std::vector apcFrameList ); + Void destroy(); + +}; + +} // NAMESPACE + +#endif // __WEIGHTEDPSNR_H__ + From d151b11c8cbfa07768f206147f78fae02372d490 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 7 Apr 2016 00:08:11 +0100 Subject: [PATCH 021/127] Add support for multiple configurations in playuverTools --- lib/PlaYUVerCmdParser.cpp | 5 -- lib/PlaYUVerProgramOptions.cpp | 7 ++- lib/PlaYUVerProgramOptions.h | 46 ++++++++++++-- tools/PlaYUVerTools.cpp | 101 ++++++++++++++++--------------- tools/PlaYUVerToolsCmdParser.cpp | 11 ++-- tools/PlaYUVerToolsCmdParser.h | 18 +++--- 6 files changed, 113 insertions(+), 75 deletions(-) diff --git a/lib/PlaYUVerCmdParser.cpp b/lib/PlaYUVerCmdParser.cpp index b93e8f7..41759fe 100644 --- a/lib/PlaYUVerCmdParser.cpp +++ b/lib/PlaYUVerCmdParser.cpp @@ -66,11 +66,6 @@ Bool PlaYUVerCmdParser::parse() // m_cParserOptions.setDefaults(); m_aUnhandledArgs = m_cParserOptions.scanArgv( m_iArgc, ( const Char** )m_ppArgv ); - // for( std::list::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++ ) - // { - // fprintf( stderr, "Unhandled argument ignored: `%s'\n", *it ); - // } - if( checkListingOpts() ) { return false; diff --git a/lib/PlaYUVerProgramOptions.cpp b/lib/PlaYUVerProgramOptions.cpp index 00c4730..a7ee257 100644 --- a/lib/PlaYUVerProgramOptions.cpp +++ b/lib/PlaYUVerProgramOptions.cpp @@ -1,7 +1,7 @@ /* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are - * granted under this license. + * granted under this license. * * Copyright (c) 2010-2014, ITU/ISO/IEC * All rights reserved. @@ -94,6 +94,11 @@ OptionBase* Options::getOption( const std::string& optName ) return NULL; } +Bool Options::hasOpt( const std::string& optName ) +{ + return getOption( optName )->count() > 0 ? true : false; +} + void Options::addOption( OptionBase *opt ) { Option* names = new Option(); diff --git a/lib/PlaYUVerProgramOptions.h b/lib/PlaYUVerProgramOptions.h index b3e1721..b1ce0b9 100644 --- a/lib/PlaYUVerProgramOptions.h +++ b/lib/PlaYUVerProgramOptions.h @@ -1,7 +1,7 @@ /* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are - * granted under this license. + * granted under this license. * * Copyright (c) 2010-2014, ITU/ISO/IEC * All rights reserved. @@ -171,8 +171,43 @@ inline void StandardOpt::parse( const std::string& arg ) arg_count++; } -/* string parsing is specialized -- copy the whole string, not just the - * first word */ +template<> +inline void StandardOpt< std::vector >::parse( const std::string& arg ) +{ + UInt aux_opt_storage; + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> aux_opt_storage; + opt_storage.push_back( aux_opt_storage ); + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } + arg_count++; +} + +template<> +inline void StandardOpt< std::vector >::parse( const std::string& arg ) +{ + Int aux_opt_storage; + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> aux_opt_storage; + opt_storage.push_back( aux_opt_storage ); + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } + arg_count++; +} + +/* string parsing is specialized */ template<> inline void StandardOpt::parse( const std::string& arg ) { @@ -180,8 +215,7 @@ inline void StandardOpt::parse( const std::string& arg ) arg_count++; } -/* string parsing is specialized -- copy the whole string, not just the - * first word */ +/* string vector parsing is specialized */ template<> inline void StandardOpt >::parse( const std::string& arg ) { @@ -259,6 +293,8 @@ public: return opt_list; } + Bool hasOpt( const std::string& optName ); + void addOption( OptionBase *opt ); private: diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index a5844ce..e485e6a 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -54,46 +54,49 @@ PlaYUVerTools::~PlaYUVerTools() } } +#define GET_PARAM( X , i ) X[X.size() > i ? i : X.size() - 1] + + Int PlaYUVerTools::openInputs() { /** * Create input streams */ - if( m_cCmdLineHandler.Opts()["input"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "input" ) ) { - std::string resolutionString( "" ); - if( m_cCmdLineHandler.Opts()["size"]->count() ) - { - resolutionString = m_cCmdLineHandler.m_strResolution; - } - std::string fmtString( "yuv420p" ); - if( m_cCmdLineHandler.Opts()["pel_fmt"]->count() ) - { - fmtString = m_cCmdLineHandler.m_strPelFmt; - } - UInt uiBitPerPixel = 8; - if( m_cCmdLineHandler.Opts()["bits_pel"]->count() ) - { - uiBitPerPixel = m_cCmdLineHandler.m_uiBitsPerPixel; - } - UInt uiEndianness = 0; - if( m_cCmdLineHandler.Opts()["endianness"]->count() ) - { - if( m_cCmdLineHandler.m_strEndianness == "big" ) - { - uiEndianness = 0; - } - if( m_cCmdLineHandler.m_strEndianness == "little" ) - { - uiEndianness = 1; - } - } - std::vector inputFileNames = m_cCmdLineHandler.m_apcInputs; + std::string resolutionString( "" ); + std::string fmtString( "yuv420p" ); + UInt uiBitPerPixel = 8; + UInt uiEndianness = 0; + PlaYUVerStream* pcStream; for( UInt i = 0; i < inputFileNames.size() && i < MAX_NUMBER_INPUTS; i++ ) { + if( m_cCmdLineHandler.Opts().hasOpt( "size" ) ) + { + resolutionString = GET_PARAM( m_cCmdLineHandler.m_strResolution, 0 ); + } + if( m_cCmdLineHandler.Opts().hasOpt( "pel_fmt" ) ) + { + fmtString = GET_PARAM( m_cCmdLineHandler.m_strPelFmt, i ); + } + if( m_cCmdLineHandler.Opts().hasOpt( "bits_pel" ) ) + { + uiBitPerPixel = GET_PARAM( m_cCmdLineHandler.m_uiBitsPerPixel, i ); + } + if( m_cCmdLineHandler.Opts().hasOpt( "endianness" ) ) + { + if( GET_PARAM( m_cCmdLineHandler.m_strEndianness, i ) == "big" ) + { + uiEndianness = 0; + } + if( GET_PARAM( m_cCmdLineHandler.m_strEndianness, i ) == "little" ) + { + uiEndianness = 1; + } + } pcStream = new PlaYUVerStream; try { @@ -113,7 +116,7 @@ Int PlaYUVerTools::openInputs() } m_uiNumberOfFrames = MAX_UINT; - if( m_cCmdLineHandler.Opts()["frames"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "frames" ) ) { m_uiNumberOfFrames = m_cCmdLineHandler.m_iFrames; } @@ -144,7 +147,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) return 2; } - if( m_cCmdLineHandler.Opts()["save"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "save" ) ) { if( m_apcInputStreams.size() == 0 ) { @@ -165,7 +168,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) m_cCmdLineHandler.log( LOG_ERROR, "Invalid frame number! Use --frame option " ); return 2; } - if( m_cCmdLineHandler.Opts()["output"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "output" ) ) m_pcOutputFileNames.push_back( m_cCmdLineHandler.m_strOutput ); if( m_pcOutputFileNames.size() != m_apcInputStreams.size() ) { @@ -181,7 +184,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) /** * Check Quality operation */ - if( m_cCmdLineHandler.Opts()["quality"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "quality" ) ) { std::string qualityMetric = m_cCmdLineHandler.m_strQualityMetric; if( m_apcInputStreams.size() < 2 ) @@ -209,7 +212,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) /** * Check Module operation */ - if( m_cCmdLineHandler.Opts()["module"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "module" ) ) { std::string moduleName = m_cCmdLineHandler.m_strModule; @@ -263,7 +266,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) { // Check outputs std::vector outputFileNames; - if( m_cCmdLineHandler.Opts()["output"]->count() ) + if( m_cCmdLineHandler.Opts().hasOpt( "output" ) ) outputFileNames.push_back( m_cCmdLineHandler.m_strOutput ); if( outputFileNames.size() == 1 ) @@ -343,20 +346,20 @@ Int PlaYUVerTools::QualityOperation() std::string metric_fmt = " "; switch( m_uiQualityMetric ) { - case PlaYUVerFrame::PSNR_METRIC: - //"PSNR_0_0" - metric_fmt += " %6.3f "; - break; - case PlaYUVerFrame::SSIM_METRIC: - //"SSIM_0_0" - metric_fmt += " %6.4f "; - break; - case PlaYUVerFrame::MSE_METRIC: - //"MSE_0_0" - metric_fmt += "%7.2f"; - break; - default: - metric_fmt += " %6.3f "; + case PlaYUVerFrame::PSNR_METRIC: + //"PSNR_0_0" + metric_fmt += " %6.3f "; + break; + case PlaYUVerFrame::SSIM_METRIC: + //"SSIM_0_0" + metric_fmt += " %6.4f "; + break; + case PlaYUVerFrame::MSE_METRIC: + //"MSE_0_0" + metric_fmt += "%7.2f"; + break; + default: + metric_fmt += " %6.3f "; } metric_fmt += " "; diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index bd09dfe..c9a9225 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -37,7 +37,6 @@ PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() { m_uiLogLevel = 0; m_bQuiet = false; - m_strPelFmt = std::string( "YUV420p" ); m_iFrames = -1; } @@ -69,7 +68,7 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) //( "input,i", m_strInput, "input file" ) /**/ ( "output,o", m_strOutput, "output file" ) /**/ ( "size,s", m_strResolution, "size (WxH)" ) /**/ - ( "pel_fmt", m_strPelFmt, "pixel format" ) /**/ + ( "pel_fmt,p", m_strPelFmt, "pixel format" ) /**/ ( "bits_pel", m_uiBitsPerPixel, "bits per pixel" ) /**/ ( "endianness", m_strEndianness, "File endianness (big, little)" ) /**/ ( "frames,f", m_iFrames, "number of frames to parse" ); @@ -90,19 +89,19 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) m_uiLogLevel = LOG_RESULT; } - if( Opts()["module"]->count() && Opts()["help"]->count() ) + if( Opts().hasOpt("module") && Opts().hasOpt("help") ) { listModuleHelp(); iRet = 1; } - else if( Opts()["help"]->count() ) + else if( Opts().hasOpt("help") ) { printf( "Usage: %s modules/quality/save [options] -input=input_file [--output=output_file]\n", argv[0] ); Opts().doHelp( std::cout ); iRet = 1; } - if( Opts()["module_list"]->count() || Opts()["module_list_full"]->count() ) + if( Opts().hasOpt("module_list") || Opts().hasOpt("module_list_full") ) { listModules(); iRet = 1; @@ -114,7 +113,7 @@ Void PlaYUVerToolsCmdParser::listModules() { Bool bDetailed = false; - if( Opts()["module_list_full"]->count() ) + if( Opts().hasOpt("module_list_full") ) bDetailed = true; PlaYUVerModuleIf* pcCurrModuleIf; diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 8a61bb1..92bb8c2 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -72,22 +72,22 @@ private: Bool m_bShowHelp; Bool m_bShowVersion; Bool m_bQuiet; + std::vector m_apcInputs; - std::string m_strInput; + std::vector m_strResolution; + std::vector m_strPelFmt; + std::vector m_uiBitsPerPixel; + std::vector m_strEndianness; std::string m_strOutput; - std::string m_strResolution; - std::string m_strPelFmt; - UInt m_uiBitsPerPixel; - std::string m_strEndianness; - UInt m_uiEndianness; - Bool m_bListPelFmts; Int64 m_iFrames; - Bool m_bListQuality; std::string m_strQualityMetric; - Bool m_bListModules; std::string m_strModule; + Bool m_bListPelFmts; + Bool m_bListQuality; + Bool m_bListModules; + Void listModules(); Void listModuleHelp(); From 070712e5c517ce31f2e394fbc6d586712b3be54c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 7 Apr 2016 00:28:54 +0100 Subject: [PATCH 022/127] Fix checking for WeightedPSNR --- modules/WeightedPSNR.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 85130ce..d5849c7 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -51,9 +51,18 @@ Bool WeightedPSNR::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ + for( UInt i = 0; i < apcFrameList.size(); i++ ) + { + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_RESOLUTION ) ) + return false; + } + if( apcFrameList[0]->getNumberChannels() != 1 ) + { + return false; + } for( UInt i = 1; i < apcFrameList.size(); i++ ) { - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[1], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_BITS ) ) return false; } return true; From 6e1455fa5294d887ec32a7c8ff120b827de66684 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 9 Apr 2016 16:11:30 +0100 Subject: [PATCH 023/127] Fix module update funtion for the cases when a dock is presented instead of a window --- app/PlaYUVerAppModuleIf.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index c4d15d8..348cd1d 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -53,6 +53,10 @@ Void PlaYUVerAppModuleIf::update() { m_pcDisplaySubWindow->refreshFrame(); } + else + { + apply(); + } } Bool PlaYUVerAppModuleIf::apply( Bool isPlaying, Bool disableThreads ) From 3a3c0128205482b7ef6de47cc479596fc9cd811f Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 10 Apr 2016 21:05:34 +0100 Subject: [PATCH 024/127] Fix the wrong statistics value in the frame information dock --- app/FramePropertiesDock.cpp | 6 ++--- app/HistogramWidget.cpp | 44 +++++++++++++++++++------------------ app/HistogramWidget.h | 4 ++-- lib/PlaYUVerFrame.cpp | 16 +++++++------- lib/PlaYUVerFrame.h | 2 +- 5 files changed, 37 insertions(+), 35 deletions(-) diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index f4dde99..d9ee2f3 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -427,10 +427,9 @@ Void FramePropertiesDock::updateStatistiques() Int min = minInterv->value(); Int max = maxInterv->value(); Int channel = histogramWidget->m_channelType; - //Int channel = channelCB->currentIndex(); if( channel == HistogramWidget::ColorChannelsHistogram ) - channel = colorsCB->currentIndex() + 1; + channel = colorsCB->currentIndex(); PlaYUVerFrame* frame; @@ -528,7 +527,8 @@ Void FramePropertiesDock::slotChannelChanged( Int channel ) colorsCB->setEnabled( true ); break; default: // Luminance. - histogramWidget->m_channelType = HistogramWidget::LumaHistogram; + //histogramWidget->m_channelType = HistogramWidget::LumaHistogram; + histogramWidget->m_channelType = HistogramWidget::FirstChannelHistogram; colorsCB->setEnabled( false ); break; } diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index cd398f0..3f6be8b 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -24,7 +24,7 @@ */ //TODO: -// - Optimizar paintEvent. Parece haver codigo redundante !! +// - Optimizar paintEvent. Parece haver codigo redundante !! #include "config.h" #include #include @@ -63,6 +63,8 @@ public: // eventData->histogram = m_histogram; // QCoreApplication::postEvent( m_parent, eventData ); + eventData->starting = true; + m_pcFrame->calcHistogram(); eventData->starting = false; @@ -167,7 +169,7 @@ public: }; //////////////////////////////////////////////////////////////////////////////// -// Constructors +// Constructors //////////////////////////////////////////////////////////////////////////////// //Constructor without image data @@ -178,7 +180,8 @@ HistogramWidget::HistogramWidget( Int width, Int height, QWidget *parent ) : d = new HistogramWidgetPrivate; - m_channelType = LumaHistogram; +// m_channelType = LumaHistogram; + m_channelType = FirstChannelHistogram; m_scaleType = LogScaleHistogram; m_colorType = FirstChannelColor; m_renderingType = FullImageHistogram; @@ -202,7 +205,7 @@ HistogramWidget::HistogramWidget( Int width, Int height, QWidget *parent ) : } //////////////////////////////////////////////////////////////////////////////// -// Destructor +// Destructor //////////////////////////////////////////////////////////////////////////////// HistogramWidget::~HistogramWidget() { @@ -220,7 +223,7 @@ HistogramWidget::~HistogramWidget() delete d; } //////////////////////////////////////////////////////////////////////////////// -// Setup Functions +// Setup Functions //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::setOptions( HistogramOptions options ) @@ -249,7 +252,7 @@ Void HistogramWidget::reset() } //////////////////////////////////////////////////////////////////////////////// -// Custom Event Handler +// Custom Event Handler //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::customEvent( QEvent *event ) @@ -341,7 +344,7 @@ Void HistogramWidget::customEvent( QEvent *event ) //delete ed; } //////////////////////////////////////////////////////////////////////////////// -// Data Loading Functions +// Data Loading Functions //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::setDataLoading() @@ -390,13 +393,12 @@ Void HistogramWidget::stopHistogramComputation() } //////////////////////////////////////////////////////////////////////////////// -// Update Data Methods +// Update Data Methods //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::updateData( PlaYUVerFrame *pcFrame, PlaYUVerFrame *pcFrameSelection ) { d->imageBits = pcFrame->getBitsPel(); - //d->imageColorSpace = image.getPelFormat(); d->imageColorSpace = pcFrame->getColorSpace(); d->imageChannels = pcFrame->getNumberChannels(); @@ -429,7 +431,7 @@ Void HistogramWidget::slotBlinkTimerDone() } //////////////////////////////////////////////////////////////////////////////// -// Paint Event +// Paint Event //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::paintEvent( QPaintEvent * ) @@ -534,9 +536,9 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) case HistogramWidget::ColorChannelsHistogram: // All color channels. max = qMax( qMax( frame->getMaximum( LUMA ), frame->getMaximum( CHROMA_U ) ), frame->getMaximum( CHROMA_V ) ); break; - case HistogramWidget::LumaHistogram: // Luminance. - max = frame->getMaximum( LUMA ); - break; +// case HistogramWidget::LumaHistogram: // Luminance. +// max = frame->getMaximum( LUMA ); +// break; } switch( m_scaleType ) @@ -596,11 +598,11 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) case HistogramWidget::ColorChannelsHistogram: // All color. vr = frame->getHistogramValue( LUMA, i ); vg = frame->getHistogramValue( CHROMA_U, i ); - vb = frame->getHistogramValue( CHROMA_U, i++ ); - break; - case HistogramWidget::LumaHistogram: // Luminance. - v = frame->getHistogramValue( LUMA, i++ ); + vb = frame->getHistogramValue( CHROMA_V, i++ ); break; +// case HistogramWidget::LumaHistogram: // Luminance. +// v = frame->getHistogramValue( LUMA, i++ ); +// break; } @@ -900,9 +902,9 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) guidePos = d->colorGuide.blue(); break; - case HistogramWidget::LumaHistogram: - guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() ), d->colorGuide.blue() ); - break; +// case HistogramWidget::LumaHistogram: +// guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() ), d->colorGuide.blue() ); +// break; default: // Alpha. guidePos = -1; @@ -985,7 +987,7 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) } //////////////////////////////////////////////////////////////////////////////// -// Mouse Events +// Mouse Events //////////////////////////////////////////////////////////////////////////////// Void HistogramWidget::mousePressEvent( QMouseEvent * e ) diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index dee1452..16da264 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -49,9 +49,9 @@ public: enum HistogramChannel { /** Luminance */ - LumaHistogram = 0, + //LumaHistogram = 0, /** Channels */ - FirstChannelHistogram, + FirstChannelHistogram = 0, SecondChannelHistogram, ThirdChannelHistogram, /** Alpha channel */ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index a861c46..8d81865 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -681,11 +681,11 @@ Int PlaYUVerFrame::getRealHistoChannel( Int channel ) } else { - if( channel == LUMA ) - { - histoChannel = 3; - } - else +// if( channel == LUMA ) +// { +// histoChannel = 3; +// } +// else { histoChannel = channel; } @@ -724,12 +724,12 @@ Int PlaYUVerFrame::getRealHistoChannel( Int channel ) return histoChannel; } -Double PlaYUVerFrame::getCount( Int channel, UInt start, UInt end ) +UInt PlaYUVerFrame::getCount( Int channel, UInt start, UInt end ) { UInt i; Int histoChannel; Int indexStart; - Double count = 0.0; + UInt count = 0; if( !m_bHasHistogram || start < 0 || end > m_uiHistoSegments - 1 || start > end ) { @@ -740,7 +740,7 @@ Double PlaYUVerFrame::getCount( Int channel, UInt start, UInt end ) if( histoChannel == -1 ) { - return 0.0; + return 0; } indexStart = histoChannel * m_uiHistoSegments; diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index b8efb41..98e5ff6 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -229,7 +229,7 @@ public: */ Void calcHistogram(); - Double getCount( Int channel, UInt start, UInt end ); + UInt getCount( Int channel, UInt start, UInt end ); Double getMean( Int channel, UInt start, UInt end ); Int getMedian( Int channel, UInt start, UInt end ); Double getStdDev( Int channel, UInt start, UInt end ); From faa4c30c981770a7e9015183fa297811862097ee Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 11 Apr 2016 01:16:07 +0100 Subject: [PATCH 025/127] Use YUV as default handler --- lib/PlaYUVerStream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index ea76ad5..ce7a3f7 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -123,7 +123,7 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( std::string strFilename return supportedFmts[i].formatFct; } } - return NULL; + return &PlaYUVerRawHandler::Create; } PlaYUVerStream::PlaYUVerStream() From ac999efa00ae53b0bafad887ac0dc2ed1d04da11 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 11 Apr 2016 01:19:23 +0100 Subject: [PATCH 026/127] Fix when an stream handler cannot be created --- lib/PlaYUVerStream.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index ce7a3f7..e3ffb8b 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -195,7 +195,6 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); if( !m_pfctCreateHandler ) { - close(); throw "[PlaYUVerStream] Invalid handler"; } @@ -203,8 +202,7 @@ Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int in if( !m_pcHandler ) { - close(); - throw "[PlaYUVerStream] Invalid handler"; + throw "[PlaYUVerStream] Cannot create handler"; } m_cFilename = filename; From 842aa6ea2e6174e24bf625f47e233bef92a24060 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 12 Apr 2016 02:00:09 +0100 Subject: [PATCH 027/127] Fix SeekStreamDialog sizee --- app/SeekStreamDialog.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index f6e6eac..f342ca9 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -44,10 +44,8 @@ SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *paren setWindowTitle( "Seek Video" ); QFont labelFont; - labelFont.setStretch( 110 ); QLabel* pcLabel = new QLabel; pcLabel->setText( QString( "Go to frame (0 - %1)" ).arg( pcCurrStream->getFrameNum() - 1 ) ); - pcLabel->setFont( labelFont ); m_spinFrameNum = new QSpinBox; m_spinFrameNum->setMinimumSize( 70, 5 ); @@ -61,13 +59,14 @@ SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *paren dialogButtonOkCancel->setStandardButtons( QDialogButtonBox::Cancel | QDialogButtonBox::Ok ); dialogButtonOkCancel->setCenterButtons( false ); - QGridLayout* mainLayout = new QGridLayout; - mainLayout->addWidget( pcLabel, 0, 0 ); - mainLayout->addWidget( m_spinFrameNum, 0, 1 ); - mainLayout->addWidget( dialogButtonOkCancel, 1, 0, 1, 2, Qt::AlignRight ); - setLayout( mainLayout ); - - setFixedSize( 220, mainLayout->sizeHint().height() ); + QVBoxLayout* verticalLayout = new QVBoxLayout; + QHBoxLayout* horizontalLayout = new QHBoxLayout; + horizontalLayout->addWidget( pcLabel ); + horizontalLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + horizontalLayout->addWidget( m_spinFrameNum ); + verticalLayout->addLayout( horizontalLayout ); + verticalLayout->addWidget( dialogButtonOkCancel, Qt::AlignRight ); + setLayout( verticalLayout ); connect( dialogButtonOkCancel, SIGNAL( accepted() ), this, SLOT( accept() ) ); connect( dialogButtonOkCancel, SIGNAL( rejected() ), this, SLOT( reject() ) ); @@ -75,6 +74,7 @@ SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *paren Int SeekStreamDialog::runDialog() { + m_spinFrameNum->selectAll(); if( exec() == QDialog::Rejected ) { return -1; From a6eb69ba2ce36d8d25d7bae0b74ace4d94b505c9 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 20 Apr 2016 16:05:20 +0100 Subject: [PATCH 028/127] Fix USE_STATIC variable on WIN32 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 29a13c4..e69f1dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,7 +104,7 @@ ADD_FEATURE_INFO(WErrors USE_WERROR "Warnings as errors" ) IF( WIN32 ) - SET( USE_STATIC OFF ) + SET( USE_STATIC ON ) INCLUDE( cmake/Win32.cmake ) ENDIF() From 11504d2f0f71c636bbd5b3c1a4c8a04852b5d601 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 22 Apr 2016 23:01:23 +0100 Subject: [PATCH 029/127] Clean up old code --- cmake/Win32.cmake | 7 ------ config.h.in | 7 +----- lib/CMakeLists.txt | 10 -------- lib/PlaYUVerFrame.cpp | 55 ------------------------------------------- lib/PlaYUVerFrame.h | 5 +--- 5 files changed, 2 insertions(+), 82 deletions(-) diff --git a/cmake/Win32.cmake b/cmake/Win32.cmake index bd37a98..833bbce 100644 --- a/cmake/Win32.cmake +++ b/cmake/Win32.cmake @@ -9,8 +9,6 @@ foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} ) set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} "." ) endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES ) -set(CMAKE_STATIC_LIBRARY_PREFIX "lib") - SET(MSVC_DLL_DIR "MSVC_DLL_DIR" CACHE PATH "Where to find MSVC dlls") INSTALL(FILES ${MSVC_DLL_DIR}/msvcr120.dll DESTINATION bin ) INSTALL(FILES ${MSVC_DLL_DIR}/msvcp120.dll DESTINATION bin ) @@ -41,9 +39,7 @@ IF( USE_OPENCV ) IF( WIN32 ) SET(OpenCV_DLL_DIR "${OpenCV_DIR}/bin" CACHE PATH "Where to find OpenCV dlls") INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_core${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_contrib${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_highgui${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_contrib${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_imgproc${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_calib3d${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_features2d${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) @@ -55,9 +51,6 @@ IF( USE_OPENCV ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_stitching${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_photo${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_objdetect${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_nonfree${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_legacy${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_gpu${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) ENDIF() LIST(APPEND CPACK_DEBIAN_PACKAGE_DEPENDS ",") LIST(APPEND CPACK_DEBIAN_PACKAGE_DEPENDS "libopencv-dev (>= 2.4.8)") diff --git a/config.h.in b/config.h.in index 7203346..20642c7 100644 --- a/config.h.in +++ b/config.h.in @@ -54,11 +54,9 @@ /* Dynamic Modules Loading */ #cmakedefine USE_DYNLOAD +/* Use modules in a different thread */ #cmakedefine PLAYUVER_THREADED_MODULES -/* Boost support */ -#cmakedefine USE_BOOST - /* OpenCV */ #cmakedefine USE_OPENCV @@ -68,8 +66,5 @@ /* Fervor update lib */ #cmakedefine USE_FERVOR -/* PIXFC-SSE lib */ -#cmakedefine USE_PIXFC - #endif // __CONFIG_PLAYUVER_H__ diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 2f4ebc9..2d569ae 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -36,16 +36,6 @@ set(PlaYUVer_Lib_HEADERS PlaYUVerModuleIf.h ) -# OPTION( USE_PIXFC "Add PIXFC support" OFF ) -# IF( USE_PIXFC ) -# IF(EXISTS "${EXTERNAL_SRC}/pixfc-sse/build/src/libpixfc-sse.a") -# INCLUDE_DIRECTORIES( ${EXTERNAL_SRC}/pixfc-sse/include ) -# LIST(APPEND LINKER_LIBS ${EXTERNAL_SRC}/pixfc-sse/build/src/libpixfc-sse.a ) -# LIST(APPEND LINKER_LIBS rt) -# ELSE() -# SET( USE_PIXFC OFF ) -# ENDIF() -# ENDIF() CONFIGURE_FILE( PlaYUVerConfig.cmake.in PlaYUVerConfig.cmake @ONLY) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 8d81865..c1478bb 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -35,9 +35,6 @@ #ifdef USE_OPENCV #include "StreamHandlerOpenCV.h" #endif -#ifdef USE_PIXFC -#include "pixfc-sse.h" -#endif namespace plaYUVer { @@ -125,8 +122,6 @@ PlaYUVerFrame::~PlaYUVerFrame() if( m_pcARGB32 ) freeMem1D( m_pcARGB32 ); m_pcARGB32 = NULL; - - closePixfc(); } static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) @@ -927,56 +922,6 @@ Double PlaYUVerFrame::getMaximum( Int channel ) ************************************************************** */ -Void PlaYUVerFrame::openPixfc() -{ -#ifdef USE_PIXFC - m_pcPixfc = NULL; - PixFcPixelFormat input_format = PixFcYUV420P; - PixFcFlag flags = ( PixFcFlag )( PixFcFlag_Default + PixFcFlag_NNbResamplingOnly ); - UInt input_row_size = m_uiWidth; - if( create_pixfc( &m_pcPixfc, input_format, PixFcRGB24, m_uiWidth, m_uiHeight, input_row_size, m_uiWidth * 3, flags ) != 0 ) - { - fprintf( stderr, "Error creating struct pixfc\n" ); - m_pcPixfc = NULL; - return; - } -#endif -} - -Void PlaYUVerFrame::closePixfc() -{ -#ifdef USE_PIXFC - if( m_pcPixfc ) - destroy_pixfc( m_pcPixfc ); -#endif -} - -Void PlaYUVerFrame::FrametoRGB8Pixfc() -{ -#ifdef USE_PIXFC - switch( m_iPixelFormat ) - { - case YUV420p: - m_pcPixfc->convert( m_pcPixfc, m_pppcInputPel, m_pcRGB32 ); - break; - case YUV422p: - break; - case YUV444p: - case YUYV422: - m_pcPixfc->convert( m_pcPixfc, m_pppcInputPel, m_pcRGB32 ); - break; - case GRAY: - break; - case RGB8: - break; - default: - // No action. - break; - } - m_bHasRGBPel = true; -#endif -} - cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) { #ifdef USE_OPENCV diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 98e5ff6..317ae1f 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -33,7 +33,7 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerPixel.h" -class PixFcSSE; + namespace cv { class Mat; @@ -335,9 +335,6 @@ private: */ Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ); - Void openPixfc(); - Void closePixfc(); - PixFcSSE* m_pcPixfc; Void FrametoRGB8Pixfc(); }; From 99128a658f7bf7609550462a0e4bbd8838e1ade3 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 22 Apr 2016 23:20:24 +0100 Subject: [PATCH 030/127] Merge master and improve version to 0.10.0 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e69f1dc..f4d0427 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ SET( PROJECT_NAME "playuver" ) PROJECT( ${PROJECT_NAME} ) SET( PLAYUVER_VERSION_MAJOR "0" ) -SET( PLAYUVER_VERSION_MINOR "9" ) +SET( PLAYUVER_VERSION_MINOR "10" ) SET( PLAYUVER_VERSION_PATCH "0" ) SET( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLAYUVER_VERSION_PATCH}") From 1e2bd11e9df0020f38433100d8b13ce679e29461 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 22 Apr 2016 23:36:57 +0100 Subject: [PATCH 031/127] Make some vars global to all scopes --- CMakeLists.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f4d0427..13a3162 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,14 +8,13 @@ cmake_minimum_required( VERSION 2.8.9 ) # Project Definition ###################################################################################### -SET( PROJECT_NAME "playuver" ) +set( PROJECT_NAME "playuver" CACHE INTERNAL "" FORCE ) PROJECT( ${PROJECT_NAME} ) SET( PLAYUVER_VERSION_MAJOR "0" ) SET( PLAYUVER_VERSION_MINOR "10" ) SET( PLAYUVER_VERSION_PATCH "0" ) -SET( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLAYUVER_VERSION_PATCH}") - +set( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLAYUVER_VERSION_PATCH}" CACHE INTERNAL "" FORCE ) ###################################################################################### # Variables From b02c5da27780c9649220edd325b3f261052ef202 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 23 Apr 2016 01:06:58 +0100 Subject: [PATCH 032/127] remove format from opencv stream handler --- lib/StreamHandlerOpenCV.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 73969e8..efb4fbe 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -35,7 +35,6 @@ namespace plaYUVer std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Grayscale Map ", "pgm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); @@ -87,7 +86,7 @@ Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) cv::Mat* pcCvFrame = pcFrame->getCvMat(); if( pcCvFrame ) { - bRet = cv::imwrite( m_cFilename.c_str(), *pcCvFrame ); + bRet = cv::imwrite( m_cFilename, *pcCvFrame ); delete pcCvFrame; } return bRet; From 335e6ee9f94614d99db2b9712037214efdd013ff Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 28 Apr 2016 11:49:39 +0100 Subject: [PATCH 033/127] Range CLAMP macros --- lib/PlaYUVerPixel.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 2ca1787..c3b7772 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -35,7 +35,8 @@ namespace plaYUVer { -#define CLAMP(X) X = X < 0 ? 0 : X > 255 ? 255 : X; +#define CLAMP_RANGE(X, MIN, MAX ) X = X < MIN ? MIN : X > MAX ? MAX : X; +#define CLAMP(X) CLAMP_RANGE(X, 0, 255); #define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ @@ -76,7 +77,7 @@ public: PlaYUVerPixel(); PlaYUVerPixel( Int ColorSpace ); PlaYUVerPixel( Int ColorSpace, Pel c0, Pel c1, Pel c2 ); - + Int ColorSpaceType() { return m_iColorSpace; @@ -129,7 +130,7 @@ public: PlaYUVerPixel operator+ ( const PlaYUVerPixel& ); PlaYUVerPixel operator- ( const PlaYUVerPixel& ); PlaYUVerPixel operator* ( const Double& ); - + /** * Convert a Pixel to a new color space * @param inputPixel input pixel (PlaYUVerPixel) From ba70f0668916b3c832ecdc79d12c2e3da04adcf5 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 28 Apr 2016 15:35:14 +0100 Subject: [PATCH 034/127] Add duplicated macros. redundant but safer --- lib/PlaYUVerPixel.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index c3b7772..daf8ff5 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -35,14 +35,14 @@ namespace plaYUVer { -#define CLAMP_RANGE(X, MIN, MAX ) X = X < MIN ? MIN : X > MAX ? MAX : X; -#define CLAMP(X) CLAMP_RANGE(X, 0, 255); +#define CLAMP_RANGE(X, MIN, MAX ) X = X < MIN ? MIN : X > MAX ? MAX : X +#define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; #define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); \ iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); \ - CLAMP(iR) CLAMP(iG) CLAMP(iB) + CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) static inline Void rgbToYuv( Int iR, Int iG, Int iB, Int &iY, Int &iU, Int &iV ) From 61ffbbe1f2fba6d870224573b212950efaff3046 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 28 Apr 2016 17:10:14 +0100 Subject: [PATCH 035/127] Fix PlaYUVerPixel macros --- lib/PlaYUVerPixel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index daf8ff5..92d566a 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -35,7 +35,7 @@ namespace plaYUVer { -#define CLAMP_RANGE(X, MIN, MAX ) X = X < MIN ? MIN : X > MAX ? MAX : X +#define CLAMP_RANGE(X, MIN, MAX ) X < MIN ? MIN : X > MAX ? MAX : X #define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; #define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ From af214bc28da03657171714b3d0b334d8837b919a Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 28 Apr 2016 17:42:27 +0100 Subject: [PATCH 036/127] Remove clamp --- lib/PlaYUVerPixel.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 92d566a..85ebe14 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -35,8 +35,6 @@ namespace plaYUVer { -#define CLAMP_RANGE(X, MIN, MAX ) X < MIN ? MIN : X > MAX ? MAX : X - #define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; #define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ From 85d93780b6ae0690dac2ddd173f3702a4d995547 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 28 Apr 2016 18:26:10 +0100 Subject: [PATCH 037/127] Add error handling when saving a frame --- app/PlaYUVerApp.cpp | 10 ++++++++-- lib/StreamHandlerPortableMap.cpp | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 7207dc6..c3f2d26 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -329,10 +329,16 @@ Void PlaYUVerApp::save() if( !fileName.isEmpty() ) { m_cLastOpenPath = QFileInfo( fileName ).path(); - if( !saveWindow->save( fileName ) ) + try + { + saveWindow->save( fileName ); + } + catch( const char *msg ) { QApplication::restoreOverrideCursor(); - QMessageBox::warning( this, tr( "plaYUVer" ), tr( "Cannot save file %1" ).arg( fileName ) ); + QString warningMsg = "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + msg; + QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); + printMessage( warningMsg, LOG_ERROR ); return; } } diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index 9784b96..b78f2be 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -83,6 +83,7 @@ Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput } else { + closeHandler(); return false; } } From f3590dff480032a2ca2a871c7b04bd093bd04879 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 29 Apr 2016 01:39:38 +0100 Subject: [PATCH 038/127] Increase support for opencv Add support for read and write streams Include device support --- app/VideoSubWindow.cpp | 5 +++ lib/PlaYUVerFrame.cpp | 47 +++++++++++-------- lib/PlaYUVerFrame.h | 1 + lib/PlaYUVerFramePixelFormats.cpp | 2 +- lib/PlaYUVerStream.cpp | 13 +++--- lib/StreamHandlerLibav.cpp | 3 +- lib/StreamHandlerOpenCV.cpp | 75 ++++++++++++++++++++++++++++--- lib/StreamHandlerOpenCV.h | 13 ++++-- 8 files changed, 123 insertions(+), 36 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index c861320..bfa2cbc 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -436,6 +436,11 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Bool bGuessedByFilesize = false; QString FilenameShort = QFileInfo( filename ).fileName(); QString fileExtension = QFileInfo( filename ).suffix(); + + if( filename.startsWith( "/dev/" ) ) + { + return false; + } if( !fileExtension.compare( "yuv" ) ) { bGuessed = false; diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index c1478bb..1e9c6a8 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -71,6 +71,16 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int color return formatsList; } +Int PlaYUVerFrame::findPixelFormat( std::string name ) +{ + for( Int i = 0; i < PLAYUVER_NUMBER_FORMATS; i++ ) + { + if( g_PlaYUVerPixFmtDescriptorsList[i].name == name ) + return i; + } + return -1; +} + PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) { init( width, height, pelFormat, bitsPixel, endianness ); @@ -967,23 +977,22 @@ cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) { #ifdef USE_OPENCV - if( m_iPixelFormat == NO_FMT ) - { - switch( pcCvFrame->channels() ) - { - case 1: - m_iPixelFormat = GRAY; - break; - case 3: - m_iPixelFormat = RGB24; - break; - default: - return; - } - } - if( !m_bInit ) { + if( m_iPixelFormat == NO_FMT ) + { + switch( pcCvFrame->channels() ) + { + case 1: + m_iPixelFormat = findPixelFormat( "GRAY" ); + break; + case 3: + m_iPixelFormat = findPixelFormat( "BGR24" ); + break; + default: + return; + } + } init( pcCvFrame->cols, pcCvFrame->rows, m_iPixelFormat, 8, -1 ); } @@ -998,9 +1007,11 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) Pel* pInputPelB = m_pppcInputPel[COLOR_B][0]; for( UInt i = 0; i < m_uiHeight * m_uiWidth; i++ ) { - *pInputPelR++ = pelRed( *pCvPel++ ); - *pInputPelG++ = pelGreen( *pCvPel++ ); - *pInputPelB++ = pelBlue( *pCvPel++ ); + *pInputPelB++ = *pCvPel++; + *pInputPelG++ = *pCvPel++; + *pInputPelR++ = *pCvPel++; + + } } else diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 317ae1f..98fe903 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -98,6 +98,7 @@ public: */ static std::vector supportedPixelFormatListNames(); static std::vector supportedPixelFormatListNames( Int colorSpace ); + static Int findPixelFormat( std::string name ); /** * Get number of bytes per frame of a specific diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 95d7b44..61d89e9 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -295,7 +295,7 @@ PlaYUVerPixFmtDescriptor RGB24 = PlaYUVerPixFmtDescriptor BGR24 = { - "BRG24", + "BGR24", PlaYUVerPixel::COLOR_RGB, 3, 1, diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index e3ffb8b..937dbe9 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -53,9 +53,9 @@ std::vector PlaYUVerStream::supportedReadFormats() #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Read ); #endif -//#ifdef USE_OPENCV -// APPEND_PLAYUVER_SUPPORTED_FMT( LibOpenCVHandler ); -//#endif +#ifdef USE_OPENCV + APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); +#endif END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -65,7 +65,6 @@ std::vector PlaYUVerStream::supportedWriteFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); #ifdef USE_FFMPEG APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerLibav, Write ); #endif @@ -118,7 +117,11 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( std::string strFilename } for( UInt i = 0; i < supportedFmts.size(); i++ ) { - if( supportedFmts[i].formatExt == currExt ) + if( currExt != "" && supportedFmts[i].formatExt == currExt ) + { + return supportedFmts[i].formatFct; + } + else if( strFilename.find( supportedFmts[i].formatExt ) != std::string::npos ) { return supportedFmts[i].formatFct; } diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 87d29b1..2909cea 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -35,8 +35,7 @@ namespace plaYUVer std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Grayscale Map", "pgm" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index efb4fbe..635aa6d 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -29,15 +29,16 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" +using namespace cv; + namespace plaYUVer { std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -45,19 +46,64 @@ std::vector StreamHandlerOpenCV::supportedWriteFormats( { INI_REGIST_PLAYUVER_SUPPORTED_FMT; APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable PixMap ", "ppm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } +StreamHandlerOpenCV::StreamHandlerOpenCV() +{ + pcMat = NULL; + pcVideoCapture = NULL; +} + Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) { m_cFilename = strFilename; - m_dFrameRate = 1; + if( bInput ) + { + + + /* + * Special filename to handle webcam input + */ + if( m_cFilename.find( "/dev/video" ) != std::string::npos ) + { + m_strFormatName = "DEV"; + m_strCodecName = "Raw Video"; + pcVideoCapture = new VideoCapture( 0 ); + m_uiWidth = pcVideoCapture->get( CV_CAP_PROP_FRAME_WIDTH ); + m_uiHeight = pcVideoCapture->get( CV_CAP_PROP_FRAME_HEIGHT ); + m_dFrameRate = 25; + } + else + { + m_strCodecName = m_strFormatName = uppercase (strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); + pcMat = new Mat( cv::imread( m_cFilename ) ); + m_uiWidth = pcMat->cols; + m_uiHeight = pcMat->rows; + m_dFrameRate = 1; + } + m_uiBitsPerPixel = 8; + m_iPixelFormat = PlaYUVerFrame::findPixelFormat( "BGR24" ); + } + return true; } Void StreamHandlerOpenCV::closeHandler() { - + if( pcVideoCapture ) + { + pcVideoCapture->release(); + delete pcVideoCapture; + pcVideoCapture = NULL; + } + if( pcMat ) + { + delete pcMat; + } } Bool StreamHandlerOpenCV::configureBuffer( PlaYUVerFrame* pcFrame ) @@ -67,6 +113,10 @@ Bool StreamHandlerOpenCV::configureBuffer( PlaYUVerFrame* pcFrame ) UInt64 StreamHandlerOpenCV::calculateFrameNumber() { + if( pcVideoCapture ) + { + return 2; + } return 1; } @@ -77,7 +127,20 @@ Bool StreamHandlerOpenCV::seek( UInt64 iFrameNum ) Bool StreamHandlerOpenCV::read( PlaYUVerFrame* pcFrame ) { - return false; + Bool bRet = false; + if( pcVideoCapture ) + { + Mat cvMat; + bRet = pcVideoCapture->read( cvMat ); + if( bRet ) + pcFrame->fromCvMat( &cvMat ); + } + if( pcMat ) + { + pcFrame->fromCvMat( pcMat ); + bRet = true; + } + return bRet; } Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index affe797..b59c885 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -31,9 +31,13 @@ #include #include #include "PlaYUVerDefs.h" -#include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" +namespace cv +{ + class VideoCapture; +} + namespace plaYUVer { @@ -48,9 +52,7 @@ public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - StreamHandlerOpenCV() - { - } + StreamHandlerOpenCV(); ~StreamHandlerOpenCV() { } @@ -63,6 +65,9 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); +private: + cv::VideoCapture* pcVideoCapture; + cv::Mat* pcMat; }; } // NAMESPACE From b1a926739333575ed7e06f50447817ae42066a37 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 29 Apr 2016 01:42:23 +0100 Subject: [PATCH 039/127] Add action to load device --- app/PlaYUVerApp.cpp | 15 +++++++++++++++ app/PlaYUVerApp.h | 4 ++++ 2 files changed, 19 insertions(+) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index c3f2d26..f0f958e 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -195,6 +195,11 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) printMessage( "File " + fileName + " do not exist!", LOG_ERROR ); return; } + load( fileName, pStreamInfo ); +} + +Void PlaYUVerApp::load( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) +{ VideoSubWindow *videoSubWindow = PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); if( videoSubWindow ) { @@ -289,6 +294,11 @@ Void PlaYUVerApp::open() } } +Void PlaYUVerApp::openDevice() +{ + load( "/dev/video0", NULL ); +} + Void PlaYUVerApp::openRecent() { QAction *action = qobject_cast( sender() ); @@ -607,6 +617,10 @@ Void PlaYUVerApp::createActions() m_arrayActions[OPEN_ACT]->setStatusTip( tr( "Open stream" ) ); connect( m_arrayActions[OPEN_ACT], SIGNAL( triggered() ), this, SLOT( open() ) ); + m_arrayActions[OPEN_DEVICE_ACT] = new QAction( tr( "&Open Capture Device" ), this ); + m_arrayActions[OPEN_DEVICE_ACT]->setStatusTip( tr( "Open capture device (webcam)" ) ); + connect( m_arrayActions[OPEN_DEVICE_ACT], SIGNAL( triggered() ), this, SLOT( openDevice() ) ); + m_arrayRecentFilesActions.resize( MAX_RECENT_FILES ); for( Int i = 0; i < MAX_RECENT_FILES; i++ ) { @@ -720,6 +734,7 @@ Void PlaYUVerApp::createMenus() m_arrayMenu[FILE_MENU] = menuBar()->addMenu( tr( "&File" ) ); m_arrayMenu[FILE_MENU]->addAction( m_arrayActions[OPEN_ACT] ); + m_arrayMenu[FILE_MENU]->addAction( m_arrayActions[OPEN_DEVICE_ACT] ); m_arrayMenu[RECENT_MENU] = m_arrayMenu[FILE_MENU]->addMenu( tr( "Open Recent" ) ); for( Int i = 0; i < MAX_RECENT_FILES; ++i ) { diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 7f26498..3d1f263 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -92,6 +92,7 @@ private Q_SLOTS: * File functions slots */ void open(); + void openDevice(); void openRecent(); void save(); void format(); @@ -131,6 +132,8 @@ private: static VideoSubWindow* findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, const QString& fileName ); + Void load( QString fileName, PlaYUVerStreamInfo* pStreamInfo ); + Void updateMenus(); Void createActions(); @@ -210,6 +213,7 @@ private: enum APP_ACTION_LIST { OPEN_ACT = 0, + OPEN_DEVICE_ACT, SAVE_ACT, FORMAT_ACT, RELOAD_ACT, From cb77bb5fda90fbdf2c9f0dfaf41f1414994a2bdd Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 02:52:06 +0100 Subject: [PATCH 040/127] New definition of module list in ModuleFactory --- modules/CMakeLists.txt | 24 +++++++++++++++--------- modules/PlaYUVerModuleFactory.cpp | 19 +------------------ 2 files changed, 16 insertions(+), 27 deletions(-) diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index c45cca9..7bb3718 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -12,22 +12,18 @@ set(plaYUver_Mod_SRCS MACRO(ADD_MODULE name file ) set(__modulename "Module${name}") - OPTION(MODULE_${name} "Use module ${name}" ON ) + OPTION(MODULE_${name} "Use module ${name}" ON ) ADD_FEATURE_INFO(${name} MODULE_${name} "Module ${name}" ) if( MODULE_${name} ) list(APPEND plaYUver_Mod_SRCS ${file} ) - LIST(APPEND MODULES_LIST ${name} ) + LIST(APPEND MODULES_LIST_NAME ${name} ) + LIST(APPEND MODULES_LIST_FILES ${file} ) file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${file}.h\"\n") endif() unset(__modulename) ENDMACRO() -file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "// This files add the header files of each module\n" - - "#ifndef __MODULESLISTHEADER_H__\n#define __MODULESLISTHEADER_H__\n" ) - - # # Modules List # @@ -52,9 +48,19 @@ ENDIF() # -# Finish header +# Create header # -file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#endif // __MODULESLISTHEADER_H__\n" ) +file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "// This files add the header files of each module\n" + + "#ifndef __MODULESLISTHEADER_H__\n#define __MODULESLISTHEADER_H__\n" ) +foreach(module ${MODULES_LIST_FILES} ) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${module}.h\"\n") +endforeach(module_Name) +file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#define REGISTER_ALL_MODULES \\\n" ) +foreach(module ${MODULES_LIST_NAME} ) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "Register( \"${module}\", &(${module}::Create) ); \\\n") +endforeach(module_Name) +file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "\n#endif // __MODULESLISTHEADER_H__\n" ) INCLUDE_DIRECTORIES( ${OpenCV_INCLUDE_DIRS} ) ADD_LIBRARY( PlaYUVerModules ${plaYUver_Mod_SRCS} ) diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index 957aa10..21f8e25 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -36,24 +36,7 @@ namespace plaYUVer PlaYUVerModuleFactory::PlaYUVerModuleFactory() { - Register( "FilterComponentLuma", &FilterComponentLuma::Create ); - Register( "FilterComponentChromaU", &FilterComponentChromaU::Create ); - Register( "FilterComponentChromaV", &FilterComponentChromaV::Create ); - Register( "AbsoluteFrameDifference", &AbsoluteFrameDifference::Create ); - Register( "FrameDifference", &FrameDifference::Create ); - Register( "FrameMask", &FrameMask::Create ); - Register( "SetChromaHalfScale", &SetChromaHalfScale::Create ); - Register( "FrameCrop", &FrameCrop::Create ); - Register( "FrameBinarization", &FrameBinarization::Create ); - Register( "FrameShift", &FrameShift::Create ); - Register( "EightBitsSampling", &EightBitsSampling::Create ); - Register( "LumaAverage", &LumaAverage::Create ); - Register( "WeightedPSNR", &WeightedPSNR::Create ); -#ifdef USE_OPENCV - //Register( "DisparityStereoVar", &DisparityStereoVar::Create ); - Register( "DisparityStereoBM", &DisparityStereoBM::Create ); - Register( "DisparityStereoSGBM", &DisparityStereoSGBM::Create ); -#endif + REGISTER_ALL_MODULES } PlaYUVerModuleFactory::~PlaYUVerModuleFactory() From bb071f25304a4e4db9d797c96eedd57803d15e4d Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 02:53:44 +0100 Subject: [PATCH 041/127] Update copyrights to 2014-2016 --- app/AboutDialog.cpp | 2 +- app/AboutDialog.h | 2 +- app/ConfigureFormatDialog.cpp | 2 +- app/ConfigureFormatDialog.h | 2 +- app/DialogSubWindowSelector.cpp | 2 +- app/DialogSubWindowSelector.h | 2 +- app/FramePropertiesDock.cpp | 2 +- app/FramePropertiesDock.h | 2 +- app/GridManager.cpp | 16 +++++------ app/GridManager.h | 2 +- app/HistogramWidget.cpp | 2 +- app/HistogramWidget.h | 2 +- app/ModuleHandleDock.cpp | 2 +- app/ModuleHandleDock.h | 2 +- app/ModulesHandle.cpp | 2 +- app/ModulesHandle.h | 2 +- app/ModulesHandleOptDialog.cpp | 2 +- app/ModulesHandleOptDialog.h | 2 +- app/PlaYUVerApp.cpp | 2 +- app/PlaYUVerApp.h | 2 +- app/PlaYUVerAppAdaptor.cpp | 2 +- app/PlaYUVerAppAdaptor.h | 2 +- app/PlaYUVerAppDefs.h | 4 +-- app/PlaYUVerAppModuleIf.cpp | 2 +- app/PlaYUVerAppModuleIf.h | 2 +- app/PlaYUVerMdiSubWindow.cpp | 2 +- app/PlaYUVerMdiSubWindow.h | 2 +- app/PlaYUVerSubWindowHandle.cpp | 2 +- app/PlaYUVerSubWindowHandle.h | 2 +- app/PlotSubWindow.cpp | 2 +- app/PlotSubWindow.h | 2 +- app/ProgressBar.cpp | 2 +- app/ProgressBar.h | 2 +- app/QualityHandle.cpp | 2 +- app/QualityHandle.h | 2 +- app/QualityMeasurementSidebar.cpp | 2 +- app/QualityMeasurementSidebar.h | 2 +- app/SeekStreamDialog.cpp | 2 +- app/SeekStreamDialog.h | 2 +- app/SubWindowAbstract.cpp | 2 +- app/SubWindowAbstract.h | 2 +- app/VideoHandle.cpp | 2 +- app/VideoHandle.h | 2 +- app/VideoSubWindow.cpp | 2 +- app/VideoSubWindow.h | 2 +- app/ViewArea.cpp | 28 +++++++++---------- app/ViewArea.h | 2 +- app/WidgetFrameNumber.cpp | 2 +- app/WidgetFrameNumber.h | 2 +- app/main.cpp | 2 +- config.h.in | 2 +- .../modules/AbsoluteFrameDifference_APIv2.cpp | 2 +- .../modules/AbsoluteFrameDifference_APIv2.h | 2 +- examples/modules/FrameBinarization_APIv1.cpp | 2 +- examples/modules/FrameBinarization_APIv1.h | 2 +- lib/LibMemory.h | 2 +- lib/PlaYUVerCmdParser.cpp | 2 +- lib/PlaYUVerCmdParser.h | 2 +- lib/PlaYUVerDefs.h | 2 +- lib/PlaYUVerFrame.cpp | 2 +- lib/PlaYUVerFrame.h | 2 +- lib/PlaYUVerFramePixelFormats.cpp | 2 +- lib/PlaYUVerFramePixelFormats.h | 2 +- lib/PlaYUVerLib.h | 2 +- lib/PlaYUVerModuleIf.h | 2 +- lib/PlaYUVerPixel.cpp | 2 +- lib/PlaYUVerPixel.h | 2 +- lib/PlaYUVerStream.cpp | 2 +- lib/PlaYUVerStream.h | 2 +- lib/PlaYUVerStreamHandlerIf.h | 2 +- lib/StreamHandlerLibav.cpp | 2 +- lib/StreamHandlerLibav.h | 2 +- lib/StreamHandlerOpenCV.cpp | 2 +- lib/StreamHandlerOpenCV.h | 2 +- lib/StreamHandlerPortableMap.cpp | 2 +- lib/StreamHandlerPortableMap.h | 2 +- lib/StreamHandlerRaw.cpp | 2 +- lib/StreamHandlerRaw.h | 2 +- modules/AbsoluteFrameDifference.cpp | 2 +- modules/AbsoluteFrameDifference.h | 2 +- modules/DisparityStereoBM.cpp | 2 +- modules/DisparityStereoBM.h | 2 +- modules/DisparityStereoSGBM.cpp | 2 +- modules/DisparityStereoSGBM.h | 2 +- modules/DisparityStereoVar.cpp | 2 +- modules/DisparityStereoVar.h | 2 +- modules/EightBitsSampling.cpp | 2 +- modules/EightBitsSampling.h | 2 +- modules/FilterComponent.cpp | 2 +- modules/FilterComponent.h | 2 +- modules/FrameBinarization.cpp | 2 +- modules/FrameBinarization.h | 2 +- modules/FrameCrop.cpp | 2 +- modules/FrameCrop.h | 2 +- modules/FrameDifference.cpp | 2 +- modules/FrameDifference.h | 2 +- modules/FrameMask.cpp | 4 +-- modules/FrameMask.h | 2 +- modules/FrameShift.cpp | 4 +-- modules/FrameShift.h | 2 +- modules/LumaAverage.cpp | 2 +- modules/LumaAverage.h | 2 +- modules/PlaYUVerModuleFactory.cpp | 2 +- modules/PlaYUVerModuleFactory.h | 2 +- modules/SetChromaHalfScale.cpp | 2 +- modules/SetChromaHalfScale.h | 2 +- modules/WeightedPSNR.cpp | 2 +- modules/WeightedPSNR.h | 2 +- tools/PlaYUVerTools.cpp | 2 +- tools/PlaYUVerTools.h | 2 +- tools/PlaYUVerToolsCmdParser.cpp | 2 +- tools/PlaYUVerToolsCmdParser.h | 2 +- tools/main.cpp | 2 +- 113 files changed, 136 insertions(+), 136 deletions(-) diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index 93f4069..c59d839 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/AboutDialog.h b/app/AboutDialog.h index c1df08d..9c2ee60 100644 --- a/app/AboutDialog.h +++ b/app/AboutDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 4df7fe1..5affd47 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index 660a1d9..f27e776 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index fd9a644..b5fd694 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/DialogSubWindowSelector.h b/app/DialogSubWindowSelector.h index 619b508..d8f189e 100644 --- a/app/DialogSubWindowSelector.h +++ b/app/DialogSubWindowSelector.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index d9ee2f3..544db11 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index 605fd5e..0aa5374 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/GridManager.cpp b/app/GridManager.cpp index be677fa..87c2355 100644 --- a/app/GridManager.cpp +++ b/app/GridManager.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -72,7 +72,7 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter case IntersectionCross: { painter->setPen( mainPen ); - // Draw crosses or dots on intersections + // Draw crosses or dots on intersections for( int x = offsetx; x <= area.right(); x += hSpacing ) { if( x >= imageWidth ) @@ -99,14 +99,14 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter } case Dashed: { - // Change pen to the dashed line + // Change pen to the dashed line mainPen.setStyle( Qt::DashLine ); } default: // Solid: { painter->setPen( mainPen ); - // Draw vertical line + // Draw vertical line for( int x = offsetx; x <= area.right(); x += hSpacing ) { if( x >= imageWidth ) @@ -114,8 +114,8 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter if( x >= area.x() ) { - // Always draw the full line otherwise the line stippling - // varies with the location of view area and we get glitchy + // Always draw the full line otherwise the line stippling + // varies with the location of view area and we get glitchy // patterns. painter->drawLine( x, 0, x, imageHeight - 1 ); } @@ -222,8 +222,8 @@ bool GridManager::isNear( int x, int y ) return false; } - // We go to consider an area with ray equal 25% of the distance between - // spaces of the gride. In this in case, we have one rectangle centered + // We go to consider an area with ray equal 25% of the distance between + // spaces of the gride. In this in case, we have one rectangle centered // in 25% of this distance. rectWidth = 2 * 0.25 * hSpacing; diff --git a/app/GridManager.h b/app/GridManager.h index 27bf0fb..83c10d7 100644 --- a/app/GridManager.h +++ b/app/GridManager.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index 3f6be8b..c2521c4 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index 16da264..c4b0f6f 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModuleHandleDock.cpp b/app/ModuleHandleDock.cpp index 59f1224..a524c66 100644 --- a/app/ModuleHandleDock.cpp +++ b/app/ModuleHandleDock.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModuleHandleDock.h b/app/ModuleHandleDock.h index 1166439..6f3514d 100644 --- a/app/ModuleHandleDock.h +++ b/app/ModuleHandleDock.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index ab4c095..0ddf6fa 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModulesHandle.h b/app/ModulesHandle.h index cb06b57..1fabdcb 100644 --- a/app/ModulesHandle.h +++ b/app/ModulesHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 5aa5a19..711c074 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ModulesHandleOptDialog.h b/app/ModulesHandleOptDialog.h index bb7eac2..e44fdc0 100644 --- a/app/ModulesHandleOptDialog.h +++ b/app/ModulesHandleOptDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index c3f2d26..0dea8b6 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 7f26498..2d333ca 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerAppAdaptor.cpp b/app/PlaYUVerAppAdaptor.cpp index ff1d86d..aaafa15 100644 --- a/app/PlaYUVerAppAdaptor.cpp +++ b/app/PlaYUVerAppAdaptor.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerAppAdaptor.h b/app/PlaYUVerAppAdaptor.h index ae64e69..df7cd13 100644 --- a/app/PlaYUVerAppAdaptor.h +++ b/app/PlaYUVerAppAdaptor.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerAppDefs.h b/app/PlaYUVerAppDefs.h index 418a6e5..0c1af91 100644 --- a/app/PlaYUVerAppDefs.h +++ b/app/PlaYUVerAppDefs.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -40,7 +40,7 @@ namespace plaYUVer # define QStringLiteral(str) QString::fromUtf8("" str "", sizeof(str) - 1) #endif - + } // NAMESPACE diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 348cd1d..00f60ef 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index 817055b..f43f4be 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerMdiSubWindow.cpp b/app/PlaYUVerMdiSubWindow.cpp index 7f407d6..5783032 100644 --- a/app/PlaYUVerMdiSubWindow.cpp +++ b/app/PlaYUVerMdiSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerMdiSubWindow.h b/app/PlaYUVerMdiSubWindow.h index 6982339..aa1e202 100644 --- a/app/PlaYUVerMdiSubWindow.h +++ b/app/PlaYUVerMdiSubWindow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index b2e1248..07aa6fc 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlaYUVerSubWindowHandle.h b/app/PlaYUVerSubWindowHandle.h index ad7412f..c167b74 100644 --- a/app/PlaYUVerSubWindowHandle.h +++ b/app/PlaYUVerSubWindowHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlotSubWindow.cpp b/app/PlotSubWindow.cpp index 9916e03..8c1cb61 100644 --- a/app/PlotSubWindow.cpp +++ b/app/PlotSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/PlotSubWindow.h b/app/PlotSubWindow.h index 7369e70..aa33776 100644 --- a/app/PlotSubWindow.h +++ b/app/PlotSubWindow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ProgressBar.cpp b/app/ProgressBar.cpp index 6f0104f..e906a81 100644 --- a/app/ProgressBar.cpp +++ b/app/ProgressBar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ProgressBar.h b/app/ProgressBar.h index 8cba896..bbdb0e5 100644 --- a/app/ProgressBar.h +++ b/app/ProgressBar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/QualityHandle.cpp b/app/QualityHandle.cpp index ab20471..10135c3 100644 --- a/app/QualityHandle.cpp +++ b/app/QualityHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/QualityHandle.h b/app/QualityHandle.h index e1bc0b4..0c3e69a 100644 --- a/app/QualityHandle.h +++ b/app/QualityHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/QualityMeasurementSidebar.cpp b/app/QualityMeasurementSidebar.cpp index 3dee836..fbceab4 100644 --- a/app/QualityMeasurementSidebar.cpp +++ b/app/QualityMeasurementSidebar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/QualityMeasurementSidebar.h b/app/QualityMeasurementSidebar.h index e94e3e1..8acd0c6 100644 --- a/app/QualityMeasurementSidebar.h +++ b/app/QualityMeasurementSidebar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index f342ca9..20b3026 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/SeekStreamDialog.h b/app/SeekStreamDialog.h index c268ab6..43e4c41 100644 --- a/app/SeekStreamDialog.h +++ b/app/SeekStreamDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/SubWindowAbstract.cpp b/app/SubWindowAbstract.cpp index 1c8a659..730c585 100644 --- a/app/SubWindowAbstract.cpp +++ b/app/SubWindowAbstract.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index bb6a080..2352dfd 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index 0510b73..0ca0c55 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/VideoHandle.h b/app/VideoHandle.h index 8d5442c..0a2b99a 100644 --- a/app/VideoHandle.h +++ b/app/VideoHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index bfa2cbc..449758e 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index b397429..48e97a4 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/ViewArea.cpp b/app/ViewArea.cpp index d9402ea..6f76928 100644 --- a/app/ViewArea.cpp +++ b/app/ViewArea.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -360,7 +360,7 @@ Void ViewArea::initZoomWinRect() } //////////////////////////////////////////////////////////////////////////////// -// Geometry Updates +// Geometry Updates //////////////////////////////////////////////////////////////////////////////// Void ViewArea::updateSize() { @@ -402,7 +402,7 @@ Void ViewArea::updateOffset() } //////////////////////////////////////////////////////////////////////////////// -// Resize Event +// Resize Event //////////////////////////////////////////////////////////////////////////////// Void ViewArea::resizeEvent( QResizeEvent *event ) { @@ -447,18 +447,18 @@ Void ViewArea::paintEvent( QPaintEvent *event ) if( m_bGridVisible ) { // Do we need to draw the whole grid? - // To know that, we need to perform a transformation of the rectangle + // To know that, we need to perform a transformation of the rectangle // area that the paInter needs to update - transform the windows - // coordinates (origin at the top-left corner of the widget), to the - // relatives coordinates of the image at it's original size (origin at - // the top-left corner of the image). + // coordinates (origin at the top-left corner of the widget), to the + // relatives coordinates of the image at it's original size (origin at + // the top-left corner of the image). QRect vr = windowToView( winRect ); - // Now we have the (to update) rectangle area on a coordinates system - // that has it's origin at the top-left corner of the image. That + // Now we have the (to update) rectangle area on a coordinates system + // that has it's origin at the top-left corner of the image. That // is, is referenced to the not scaled image. // To know what image area we need to update, just Intersects the - // rectangle area with the image area. + // rectangle area with the image area. vr &= QRect( 0, 0, m_pixmap.width(), m_pixmap.height() ); // Set up for the grid drawer. @@ -647,7 +647,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) myPath.addRect( sr ); //m_selectedArea paInter.drawPath( myPath ); - // 2) Draw the selection rectangle + // 2) Draw the selection rectangle paInter.setBrush( Qt::NoBrush ); paInter.setPen( Qt::darkCyan ); // paInter.drawRect( sr/*m_selectedArea*/ ); @@ -721,7 +721,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) } //////////////////////////////////////////////////////////////////////////////// -// Mouse Events +// Mouse Events //////////////////////////////////////////////////////////////////////////////// Void ViewArea::wheelEvent( QWheelEvent *event ) { @@ -765,7 +765,7 @@ Void ViewArea::mousePressEvent( QMouseEvent *event ) m_lastWindowPos = event->pos(); } - // Is the mouse over the image? If yes, save the mouse position; + // Is the mouse over the image? If yes, save the mouse position; // otherwise, QPoint( -1, -1 ) indicates an invalid position. if( isPosValid( vpos ) ) { @@ -804,7 +804,7 @@ Void ViewArea::mousePressEvent( QMouseEvent *event ) m_blockTrackEnable = false; } - // Block selection + // Block selection // m_selectedArea = m_grid.rectContains( m_lastPos ); QRect updateRect = viewToWindow( m_selectedArea ); diff --git a/app/ViewArea.h b/app/ViewArea.h index cd9fa5e..88eb48f 100644 --- a/app/ViewArea.h +++ b/app/ViewArea.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/WidgetFrameNumber.cpp b/app/WidgetFrameNumber.cpp index 1136b98..fe711e5 100644 --- a/app/WidgetFrameNumber.cpp +++ b/app/WidgetFrameNumber.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/WidgetFrameNumber.h b/app/WidgetFrameNumber.h index 34fd3c7..a8afede 100644 --- a/app/WidgetFrameNumber.h +++ b/app/WidgetFrameNumber.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/app/main.cpp b/app/main.cpp index d3b8afc..73a7895 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/config.h.in b/config.h.in index 20642c7..1869bd1 100644 --- a/config.h.in +++ b/config.h.in @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.cpp b/examples/modules/AbsoluteFrameDifference_APIv2.cpp index b4dc6ff..fecf27b 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.cpp +++ b/examples/modules/AbsoluteFrameDifference_APIv2.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.h b/examples/modules/AbsoluteFrameDifference_APIv2.h index c3663ac..d685c97 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.h +++ b/examples/modules/AbsoluteFrameDifference_APIv2.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/examples/modules/FrameBinarization_APIv1.cpp b/examples/modules/FrameBinarization_APIv1.cpp index 7fd5538..37b17bb 100644 --- a/examples/modules/FrameBinarization_APIv1.cpp +++ b/examples/modules/FrameBinarization_APIv1.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/examples/modules/FrameBinarization_APIv1.h b/examples/modules/FrameBinarization_APIv1.h index ceda8ac..e7f4cdf 100644 --- a/examples/modules/FrameBinarization_APIv1.h +++ b/examples/modules/FrameBinarization_APIv1.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/LibMemory.h b/lib/LibMemory.h index c2b44b3..b7ab838 100644 --- a/lib/LibMemory.h +++ b/lib/LibMemory.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerCmdParser.cpp b/lib/PlaYUVerCmdParser.cpp index 41759fe..da0832f 100644 --- a/lib/PlaYUVerCmdParser.cpp +++ b/lib/PlaYUVerCmdParser.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerCmdParser.h b/lib/PlaYUVerCmdParser.h index 8fd8584..3bc5246 100644 --- a/lib/PlaYUVerCmdParser.h +++ b/lib/PlaYUVerCmdParser.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index a37c383..e0e3fcc 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 1e9c6a8..d9f54d3 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 98fe903..320c1f6 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 61d89e9..aff995a 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index 551a995..ed90e4e 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerLib.h b/lib/PlaYUVerLib.h index 7a7497e..4aede6b 100644 --- a/lib/PlaYUVerLib.h +++ b/lib/PlaYUVerLib.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index 9de2d65..ce614dd 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index 6c2bdfc..7bd7051 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 85ebe14..72b024f 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 937dbe9..dc80121 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 95a2dbb..c382a70 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index f49509c..1271b8b 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 2909cea..42bc15c 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 90c3d9e..512f674 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 635aa6d..bb305a9 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index b59c885..cc177d9 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index b78f2be..e1f4e0f 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 5780e7b..666d219 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index a669108..47e6adb 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index 27bd0b9..13f806b 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 63d5dba..28d5add 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/AbsoluteFrameDifference.h b/modules/AbsoluteFrameDifference.h index a9678b9..39f51de 100644 --- a/modules/AbsoluteFrameDifference.h +++ b/modules/AbsoluteFrameDifference.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index fadd833..eed79a6 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index 0d75b19..32f863b 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index ef183b4..a34dbe4 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index cdd5142..a1adfbd 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index 6099935..55159ef 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 3f7d3e1..57872d6 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index 4ed2f20..0f3ea38 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/EightBitsSampling.h b/modules/EightBitsSampling.h index a72000e..becc81c 100644 --- a/modules/EightBitsSampling.h +++ b/modules/EightBitsSampling.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index 0cd2d18..b4e704a 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index 453cb0a..454bffd 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameBinarization.cpp b/modules/FrameBinarization.cpp index ed8662b..559169c 100644 --- a/modules/FrameBinarization.cpp +++ b/modules/FrameBinarization.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameBinarization.h b/modules/FrameBinarization.h index f13f016..b2e4b31 100644 --- a/modules/FrameBinarization.h +++ b/modules/FrameBinarization.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index 23c210f..34f1ab3 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameCrop.h b/modules/FrameCrop.h index 5adc315..08a8958 100644 --- a/modules/FrameCrop.h +++ b/modules/FrameCrop.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index f757f97..766014a 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameDifference.h b/modules/FrameDifference.h index f5776b1..9cf5c27 100644 --- a/modules/FrameDifference.h +++ b/modules/FrameDifference.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index baf5b64..6b93f8d 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -60,7 +60,7 @@ Bool FrameMask::create( std::vector apcFrameList ) return false; } } - + m_iWeight = m_iWeight > 100 || m_iWeight < 0 ? 5 : m_iWeight; m_iWeight = m_iWeight > 10 ? m_iWeight / 10 : m_iWeight; diff --git a/modules/FrameMask.h b/modules/FrameMask.h index ad797d9..4205ea6 100644 --- a/modules/FrameMask.h +++ b/modules/FrameMask.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index 8f2872b..a91ca70 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -135,7 +135,7 @@ Bool FrameShift::keyPressed( enum Module_Key_Supported value ) m_iShiftVer += 1; return true; } - + return false; } diff --git a/modules/FrameShift.h b/modules/FrameShift.h index b650ab3..28aa0e1 100644 --- a/modules/FrameShift.h +++ b/modules/FrameShift.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/LumaAverage.cpp b/modules/LumaAverage.cpp index 3636a72..c4988fe 100644 --- a/modules/LumaAverage.cpp +++ b/modules/LumaAverage.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/LumaAverage.h b/modules/LumaAverage.h index 870bee7..ccc5628 100644 --- a/modules/LumaAverage.h +++ b/modules/LumaAverage.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index 21f8e25..e8b4f74 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/PlaYUVerModuleFactory.h b/modules/PlaYUVerModuleFactory.h index 5672d37..c2d0243 100644 --- a/modules/PlaYUVerModuleFactory.h +++ b/modules/PlaYUVerModuleFactory.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index 7b8dc56..2d37b42 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/SetChromaHalfScale.h b/modules/SetChromaHalfScale.h index 947b1e2..041d3ba 100644 --- a/modules/SetChromaHalfScale.h +++ b/modules/SetChromaHalfScale.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index d5849c7..44f5fc1 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h index 0ca0f06..c5a3a5b 100644 --- a/modules/WeightedPSNR.h +++ b/modules/WeightedPSNR.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index e485e6a..5c3c58f 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 50a986f..3b9cb3a 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index c9a9225..9855d12 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 92bb8c2..c2bcf5b 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/tools/main.cpp b/tools/main.cpp index cf3140a..3683bc9 100644 --- a/tools/main.cpp +++ b/tools/main.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2015 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) * * Joao Carreira (jfmcarreira@gmail.com) * From 42d18a3a09d4ed26403c22e803ae9a0d12c46c58 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 03:11:11 +0100 Subject: [PATCH 042/127] Remove namespace --- app/AboutDialog.cpp | 4 +--- app/AboutDialog.h | 4 ---- app/ConfigureFormatDialog.cpp | 4 +--- app/ConfigureFormatDialog.h | 4 ---- app/DialogSubWindowSelector.cpp | 4 ---- app/DialogSubWindowSelector.h | 4 ---- app/FramePropertiesDock.cpp | 4 +--- app/FramePropertiesDock.h | 4 ---- app/GridManager.cpp | 4 ---- app/GridManager.h | 4 ---- app/HistogramWidget.cpp | 4 +--- app/HistogramWidget.h | 6 +----- app/ModuleHandleDock.cpp | 4 +--- app/ModuleHandleDock.h | 4 ---- app/ModulesHandle.cpp | 4 +--- app/ModulesHandle.h | 4 ---- app/ModulesHandleOptDialog.cpp | 4 +--- app/ModulesHandleOptDialog.h | 4 ---- app/PlaYUVerApp.cpp | 4 +--- app/PlaYUVerApp.h | 4 ---- app/PlaYUVerAppAdaptor.cpp | 4 +--- app/PlaYUVerAppAdaptor.h | 4 ---- app/PlaYUVerAppDefs.h | 4 +--- app/PlaYUVerAppModuleIf.cpp | 4 +--- app/PlaYUVerAppModuleIf.h | 4 ---- app/PlaYUVerMdiSubWindow.cpp | 4 +--- app/PlaYUVerMdiSubWindow.h | 4 ---- app/PlaYUVerSubWindowHandle.cpp | 4 +--- app/PlaYUVerSubWindowHandle.h | 4 ---- app/PlotSubWindow.cpp | 4 +--- app/PlotSubWindow.h | 4 ---- app/ProgressBar.cpp | 4 +--- app/ProgressBar.h | 4 ---- app/QualityHandle.cpp | 4 +--- app/QualityHandle.h | 4 ---- app/QualityMeasurementSidebar.cpp | 4 +--- app/QualityMeasurementSidebar.h | 4 ---- app/SeekStreamDialog.cpp | 4 +--- app/SeekStreamDialog.h | 4 ---- app/SubWindowAbstract.cpp | 4 +--- app/SubWindowAbstract.h | 4 ---- app/VideoHandle.cpp | 4 +--- app/VideoHandle.h | 4 ---- app/VideoSubWindow.cpp | 17 ----------------- app/VideoSubWindow.h | 8 ++------ app/ViewArea.cpp | 4 ---- app/ViewArea.h | 4 ---- app/WidgetFrameNumber.cpp | 4 +--- app/WidgetFrameNumber.h | 4 ---- app/main.cpp | 2 -- .../modules/AbsoluteFrameDifference_APIv2.cpp | 4 +--- .../modules/AbsoluteFrameDifference_APIv2.h | 4 ---- examples/modules/FrameBinarization_APIv1.cpp | 4 +--- examples/modules/FrameBinarization_APIv1.h | 4 ---- lib/LibMemory.h | 4 +--- lib/PlaYUVerCmdParser.cpp | 4 +--- lib/PlaYUVerCmdParser.h | 6 +++--- lib/PlaYUVerDefs.h | 4 +--- lib/PlaYUVerFrame.cpp | 4 +--- lib/PlaYUVerFrame.h | 4 ---- lib/PlaYUVerFramePixelFormats.cpp | 4 +--- lib/PlaYUVerFramePixelFormats.h | 4 +--- lib/PlaYUVerModuleIf.h | 4 ---- lib/PlaYUVerPixel.cpp | 4 +--- lib/PlaYUVerPixel.h | 4 ---- lib/PlaYUVerProgramOptions.cpp | 4 +--- lib/PlaYUVerProgramOptions.h | 4 ---- lib/PlaYUVerStream.cpp | 4 +--- lib/PlaYUVerStream.h | 4 ---- lib/PlaYUVerStreamHandlerIf.h | 5 ----- lib/StreamHandlerLibav.cpp | 4 +--- lib/StreamHandlerLibav.h | 4 ---- lib/StreamHandlerOpenCV.cpp | 4 +--- lib/StreamHandlerOpenCV.h | 4 ---- lib/StreamHandlerPortableMap.cpp | 4 +--- lib/StreamHandlerPortableMap.h | 4 ---- lib/StreamHandlerRaw.cpp | 4 +--- lib/StreamHandlerRaw.h | 5 ----- modules/AbsoluteFrameDifference.cpp | 4 +--- modules/AbsoluteFrameDifference.h | 4 ---- modules/DisparityStereoBM.cpp | 4 +--- modules/DisparityStereoBM.h | 4 ---- modules/DisparityStereoSGBM.cpp | 4 +--- modules/DisparityStereoSGBM.h | 4 ---- modules/DisparityStereoVar.cpp | 4 +--- modules/DisparityStereoVar.h | 4 ---- modules/EightBitsSampling.cpp | 4 +--- modules/EightBitsSampling.h | 4 ---- modules/FilterComponent.cpp | 4 +--- modules/FilterComponent.h | 4 ---- modules/FrameBinarization.cpp | 4 +--- modules/FrameBinarization.h | 4 ---- modules/FrameCrop.cpp | 4 +--- modules/FrameCrop.h | 4 ---- modules/FrameDifference.cpp | 4 +--- modules/FrameDifference.h | 4 ---- modules/FrameMask.cpp | 4 +--- modules/FrameMask.h | 4 ---- modules/FrameShift.cpp | 4 +--- modules/FrameShift.h | 4 ---- modules/LumaAverage.cpp | 6 ------ modules/LumaAverage.h | 4 ---- modules/PlaYUVerModuleFactory.cpp | 4 +--- modules/PlaYUVerModuleFactory.h | 9 --------- modules/SetChromaHalfScale.cpp | 4 +--- modules/SetChromaHalfScale.h | 4 ---- modules/WeightedPSNR.cpp | 4 +--- modules/WeightedPSNR.h | 4 ---- tools/PlaYUVerTools.cpp | 4 +--- tools/PlaYUVerTools.h | 4 ---- tools/PlaYUVerToolsCmdParser.cpp | 4 +--- tools/PlaYUVerToolsCmdParser.h | 4 ---- tools/main.cpp | 2 -- 113 files changed, 58 insertions(+), 420 deletions(-) diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index c59d839..4774895 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -32,8 +32,6 @@ #include #include -namespace plaYUVer -{ AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) @@ -79,4 +77,4 @@ AboutDialog::AboutDialog(QWidget *parent) setWindowTitle(tr("About %1").arg(QApplication::applicationName())); } -} // NAMESPACE + diff --git a/app/AboutDialog.h b/app/AboutDialog.h index 9c2ee60..d1a6cf9 100644 --- a/app/AboutDialog.h +++ b/app/AboutDialog.h @@ -28,8 +28,6 @@ #include -namespace plaYUVer -{ class AboutDialog : public QDialog { @@ -39,6 +37,4 @@ public: AboutDialog(QWidget *parent = 0); }; -} // NAMESPACE - #endif // __ABOUTDIALOG_H__ diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 5affd47..0d717be 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -26,8 +26,6 @@ #include "lib/PlaYUVerFrame.h" #include "lib/PlaYUVerStream.h" -namespace plaYUVer -{ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : QDialog( parent ) @@ -386,4 +384,4 @@ Void ConfigureFormatDialog::slotBitsChange( Int idx ) } } -} // NAMESPACE + diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index f27e776..89edce5 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -37,8 +37,6 @@ class QPixmap; class QColor; -namespace plaYUVer -{ /** * @@ -76,6 +74,4 @@ private: }; -} // NAMESPACE - #endif // __CONFIGUREFORMATDIALOG_H__ diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index b5fd694..2bf40c3 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -28,8 +28,6 @@ #include "DialogSubWindowSelector.h" #include "VideoSubWindow.h" -namespace plaYUVer -{ DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWindowHandle *windowManager, UInt uiCategory, Int minWindowsSelected, Int maxWindowsSelected ) : @@ -244,5 +242,3 @@ Void DialogSubWindowSelector::removeAllSubWindow() m_apcSelectedSubWindowList.clear(); update(); } - -} // Namespace SCode diff --git a/app/DialogSubWindowSelector.h b/app/DialogSubWindowSelector.h index d8f189e..c281b91 100644 --- a/app/DialogSubWindowSelector.h +++ b/app/DialogSubWindowSelector.h @@ -41,8 +41,6 @@ class QColor; class QCheckBox; class QGroupBox; -namespace plaYUVer -{ class PlaYUVerSubWindowHandle; class SubWindowAbstract; @@ -91,6 +89,4 @@ private Q_SLOTS: }; -} // NAMESPACE - #endif // __DIALOGSUBWINDOWSELECTOR_H__ diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index 544db11..8e56ad7 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -27,8 +27,6 @@ #include #include "FramePropertiesDock.h" -namespace plaYUVer -{ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ) : QWidget( parent ), @@ -617,5 +615,5 @@ Void FramePropertiesDock::slotUpdateIntervRange( Int range ) maxInterv->blockSignals( false ); } -} // NAMESPACE + diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index 0aa5374..45caaca 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -37,8 +37,6 @@ #include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" -namespace plaYUVer -{ class FramePropertiesDock: public QWidget { @@ -130,6 +128,4 @@ private Q_SLOTS: }; -} // NAMESPACE - #endif // __FRAMEPROPERTIESDOCK_H__ diff --git a/app/GridManager.cpp b/app/GridManager.cpp index 87c2355..01a5dba 100644 --- a/app/GridManager.cpp +++ b/app/GridManager.cpp @@ -34,8 +34,6 @@ #include "GridManager.h" -namespace plaYUVer -{ //////////////////////////////////////////////////////////////////////////////// // Constructor @@ -266,5 +264,3 @@ bool GridManager::isNear( const QPoint &pos ) { return isNear( pos.x(), pos.y() ); } - -} // NameSpace plaYUVer diff --git a/app/GridManager.h b/app/GridManager.h index 83c10d7..ea9d0bb 100644 --- a/app/GridManager.h +++ b/app/GridManager.h @@ -36,8 +36,6 @@ class QPoint; class QBitmap; class QPainter; -namespace plaYUVer -{ /** * @@ -102,6 +100,4 @@ private: QPoint m_nearPos; }; -} // NameSpace plaYUVer - #endif // __GRIDMANAGER_H__ diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index c2521c4..c470a25 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -31,8 +31,6 @@ #include #include "HistogramWidget.h" -namespace plaYUVer -{ class HistogramWorker: public QThread { @@ -1100,5 +1098,5 @@ Void HistogramWidget::slotMaxValueChanged( int max ) } } -} // NAMESPACE + diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index c4b0f6f..f58b3df 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -34,8 +34,6 @@ class QEvent; -namespace plaYUVer -{ class HistogramWorker; class HistogramWidgetPrivate; @@ -172,9 +170,7 @@ private: HistogramWidgetPrivate* d; }; -} - // NAMESPACE -Q_DECLARE_OPERATORS_FOR_FLAGS( plaYUVer::HistogramWidget::HistogramOptions ) +Q_DECLARE_OPERATORS_FOR_FLAGS( HistogramWidget::HistogramOptions ) #endif // __HISTOGRAMWIDGET_H__ diff --git a/app/ModuleHandleDock.cpp b/app/ModuleHandleDock.cpp index a524c66..df6d31f 100644 --- a/app/ModuleHandleDock.cpp +++ b/app/ModuleHandleDock.cpp @@ -27,8 +27,6 @@ #include "PlaYUVerAppModuleIf.h" #include "ModulesHandle.h" -namespace plaYUVer -{ ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ) : QWidget( parent ), @@ -90,5 +88,5 @@ QSize ModuleHandleDock::sizeHint() const return currSize; } -} // NAMESPACE + diff --git a/app/ModuleHandleDock.h b/app/ModuleHandleDock.h index 6f3514d..a8bfa3a 100644 --- a/app/ModuleHandleDock.h +++ b/app/ModuleHandleDock.h @@ -35,8 +35,6 @@ #endif -namespace plaYUVer -{ class PlaYUVerAppModuleIf; @@ -64,6 +62,4 @@ public Q_SLOTS: }; -} // NAMESPACE - #endif // __MODULEHANDLEDOCK_H__ diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index 0ddf6fa..f9fb0b9 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -32,8 +32,6 @@ #include "ModulesHandleOptDialog.h" #include "modules/PlaYUVerModuleFactory.h" -namespace plaYUVer -{ ModulesHandle::ModulesHandle( QWidget* parent, PlaYUVerSubWindowHandle *windowManager, VideoHandle *moduleVideo ) : QWidget( parent ), @@ -594,5 +592,5 @@ Void ModulesHandle::customEvent( QEvent *event ) } } -} // NAMESPACE + diff --git a/app/ModulesHandle.h b/app/ModulesHandle.h index 1fabdcb..f72892c 100644 --- a/app/ModulesHandle.h +++ b/app/ModulesHandle.h @@ -39,8 +39,6 @@ #include "PlaYUVerAppDefs.h" #include "lib/PlaYUVerFrame.h" -namespace plaYUVer -{ class VideoHandle; class PlaYUVerSubWindowHandle; @@ -116,7 +114,5 @@ private Q_SLOTS: }; -} // NAMESPACE - #endif // __MODULESHANDLE_H__ diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 711c074..6dbeea3 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -30,8 +30,6 @@ #include #include -namespace plaYUVer -{ class OpionConfiguration: public QWidget { @@ -147,4 +145,4 @@ Int ModulesHandleOptDialog::runConfiguration() return QDialog::Accepted; } -} // NAMESPACE + diff --git a/app/ModulesHandleOptDialog.h b/app/ModulesHandleOptDialog.h index e44fdc0..cfdfda1 100644 --- a/app/ModulesHandleOptDialog.h +++ b/app/ModulesHandleOptDialog.h @@ -31,8 +31,6 @@ #include #include -namespace plaYUVer -{ class OpionConfiguration; @@ -51,6 +49,4 @@ private: QVector m_apcOptionList; }; -} // NAMESPACE - #endif // __MODULEHANDLEOPTDIALOG_H__ diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 0dea8b6..dac2832 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -46,8 +46,6 @@ #define SYNCHRONISED_ZOON 1 -namespace plaYUVer -{ PlaYUVerApp::PlaYUVerApp() : m_pcCurrentSubWindow( NULL ), @@ -922,4 +920,4 @@ Void PlaYUVerApp::writeSettings() m_pcWindowHandle->writeSettings(); } -} // NAMESPACE + diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 2d333ca..a83d450 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -54,8 +54,6 @@ class QActionGroup; class QAction; class QSignalMapper; -namespace plaYUVer -{ class PlaYUVerCmdParser; class PlaYUVerStream; @@ -237,7 +235,5 @@ private: AboutDialog* m_pcAboutDialog; }; -} // NAMESPACE - #endif // __PLAYUVERAPP_H__ diff --git a/app/PlaYUVerAppAdaptor.cpp b/app/PlaYUVerAppAdaptor.cpp index aaafa15..32801d8 100644 --- a/app/PlaYUVerAppAdaptor.cpp +++ b/app/PlaYUVerAppAdaptor.cpp @@ -26,8 +26,6 @@ #include "PlaYUVerAppAdaptor.h" #include "PlaYUVerApp.h" -namespace plaYUVer -{ PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp *app ) : QDBusAbstractAdaptor( app ), @@ -64,4 +62,4 @@ bool PlaYUVerAppAdaptor::loadFile( const QString& filename ) return true; } -} // NAMESPACE + diff --git a/app/PlaYUVerAppAdaptor.h b/app/PlaYUVerAppAdaptor.h index df7cd13..ab1f6c9 100644 --- a/app/PlaYUVerAppAdaptor.h +++ b/app/PlaYUVerAppAdaptor.h @@ -32,8 +32,6 @@ #include #include -namespace plaYUVer -{ #define PLAYUVER_DBUS_SESSION_NAME "org.pixlra.PlaYUVer.application" #define PLAYUVER_DBUS_PATH "/MainApplication" @@ -81,7 +79,5 @@ private: PlaYUVerApp *m_app; }; -} // NAMESPACE - #endif // __PlaYUVerAppAdaptor_H__ diff --git a/app/PlaYUVerAppDefs.h b/app/PlaYUVerAppDefs.h index 0c1af91..7d7f4b8 100644 --- a/app/PlaYUVerAppDefs.h +++ b/app/PlaYUVerAppDefs.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerDefs.h" -namespace plaYUVer -{ // ==================================================================================================================== // Qt compatibility redefinition @@ -42,6 +40,6 @@ namespace plaYUVer #endif -} // NAMESPACE + #endif // __PLAYUVERAPPDEFS_H__ diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 00f60ef..65f0119 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -26,8 +26,6 @@ #include "VideoSubWindow.h" #include "VideoSubWindow.h" -namespace plaYUVer -{ PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ) : m_bIsRunning( false ), @@ -219,5 +217,5 @@ Void PlaYUVerAppModuleIf::destroy() } -} // NAMESPACE + diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index f43f4be..58c6cbe 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -37,8 +37,6 @@ class QAction; -namespace plaYUVer -{ //#define PLAYUVER_THREADED_MODULES @@ -119,7 +117,5 @@ protected: virtual void run(); }; -} // NAMESPACE - #endif // __PLAYUVERAPPMODULESIF_H__ diff --git a/app/PlaYUVerMdiSubWindow.cpp b/app/PlaYUVerMdiSubWindow.cpp index 5783032..04aef7b 100644 --- a/app/PlaYUVerMdiSubWindow.cpp +++ b/app/PlaYUVerMdiSubWindow.cpp @@ -26,8 +26,6 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" -namespace plaYUVer -{ PlaYUVerMdiSubWindow::PlaYUVerMdiSubWindow( QWidget *parent ) : QMdiSubWindow( parent ) @@ -51,4 +49,4 @@ Void PlaYUVerMdiSubWindow::closeEvent( QCloseEvent *event ) event->accept(); } -} // NAMESPACE + diff --git a/app/PlaYUVerMdiSubWindow.h b/app/PlaYUVerMdiSubWindow.h index aa1e202..e43b759 100644 --- a/app/PlaYUVerMdiSubWindow.h +++ b/app/PlaYUVerMdiSubWindow.h @@ -30,8 +30,6 @@ #include -namespace plaYUVer -{ class PlaYUVerMdiSubWindow: public QMdiSubWindow { @@ -48,7 +46,5 @@ protected: void closeEvent( QCloseEvent *event ); }; -} // NAMESPACE - #endif // __PLAYUVERMDISUBWINDOW_H__ diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index 07aa6fc..799839e 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -27,8 +27,6 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" -namespace plaYUVer -{ class PlaYUVerMdiArea: public QMdiArea { @@ -578,4 +576,4 @@ Void PlaYUVerSubWindowHandle::writeSettings() appSettings.setValue( "SubWindowManager/SubWindowMode", m_iWindowMode ); } -} // NAMESPACE + diff --git a/app/PlaYUVerSubWindowHandle.h b/app/PlaYUVerSubWindowHandle.h index c167b74..614995e 100644 --- a/app/PlaYUVerSubWindowHandle.h +++ b/app/PlaYUVerSubWindowHandle.h @@ -33,8 +33,6 @@ #include #endif -namespace plaYUVer -{ class PlaYUVerApp; class SubWindowAbstract; @@ -128,6 +126,4 @@ Q_SIGNALS: }; -} // NAMESPACE - #endif // __PLAYUVERSUBWINDOWHANDLE_H__ diff --git a/app/PlotSubWindow.cpp b/app/PlotSubWindow.cpp index 8c1cb61..2fe23e9 100644 --- a/app/PlotSubWindow.cpp +++ b/app/PlotSubWindow.cpp @@ -25,8 +25,6 @@ #include "PlotSubWindow.h" #include "qcustomplot.h" -namespace plaYUVer -{ Void PlotSubWindow::definePlotColors() { @@ -241,4 +239,4 @@ Void PlotSubWindow::addPlot( const QVector &arrayX, const QVector #include -namespace plaYUVer -{ ProgressBar::ProgressBar( QWidget *parent, UInt maxValue ) : QWidget( parent ), @@ -61,4 +59,4 @@ Void ProgressBar::incrementProgress( UInt increment ) m_pcProgressBar->setValue( m_uiProgress ); update(); } -} // NAMESPACE + diff --git a/app/ProgressBar.h b/app/ProgressBar.h index bbdb0e5..e13184f 100644 --- a/app/ProgressBar.h +++ b/app/ProgressBar.h @@ -31,8 +31,6 @@ class QProgressBar; -namespace plaYUVer -{ class ProgressBar: public QWidget { @@ -49,6 +47,4 @@ private: QProgressBar* m_pcProgressBar; }; -} // NAMESPACE - #endif // __PROGRESSBAR_H__ diff --git a/app/QualityHandle.cpp b/app/QualityHandle.cpp index 10135c3..bb44c07 100644 --- a/app/QualityHandle.cpp +++ b/app/QualityHandle.cpp @@ -34,8 +34,6 @@ #include "QtConcurrent/qtconcurrentrun.h" #endif -namespace plaYUVer -{ QualityHandle::QualityHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : m_pcParet( parent ), @@ -330,5 +328,5 @@ Void QualityHandle::slotPlotQualitySeveral() } } -} // NAMESPACE + diff --git a/app/QualityHandle.h b/app/QualityHandle.h index 0c3e69a..328173d 100644 --- a/app/QualityHandle.h +++ b/app/QualityHandle.h @@ -36,8 +36,6 @@ #include "QFuture" #include "QualityMeasurementSidebar.h" -namespace plaYUVer -{ class PlaYUVerSubWindowHandle; class VideoSubWindow; @@ -94,6 +92,4 @@ private Q_SLOTS: void slotPlotQualitySeveral(); }; -} // NAMESPACE - #endif // __QUALITYMEASUREMENTSIDEBAR_H__ diff --git a/app/QualityMeasurementSidebar.cpp b/app/QualityMeasurementSidebar.cpp index fbceab4..59fd21b 100644 --- a/app/QualityMeasurementSidebar.cpp +++ b/app/QualityMeasurementSidebar.cpp @@ -27,8 +27,6 @@ #include "QualityMeasurementSidebar.h" #include "VideoSubWindow.h" -namespace plaYUVer -{ QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerSubWindowHandle *windowManager ) : QWidget( parent ), @@ -260,5 +258,5 @@ Void QualityMeasurementSidebar::slotQualityMetricChanged( Int idx ) //updateQualityMetric( idx ); } -} // NAMESPACE + diff --git a/app/QualityMeasurementSidebar.h b/app/QualityMeasurementSidebar.h index 8acd0c6..5d93cd5 100644 --- a/app/QualityMeasurementSidebar.h +++ b/app/QualityMeasurementSidebar.h @@ -37,8 +37,6 @@ #include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" -namespace plaYUVer -{ class PlaYUVerSubWindowHandle; class VideoSubWindow; @@ -87,6 +85,4 @@ private Q_SLOTS: }; -} // NAMESPACE - #endif // __QUALITYMEASUREMENTSIDEBAR_H__ diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index 20b3026..5221b72 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -30,8 +30,6 @@ #include #include -namespace plaYUVer -{ SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *parent ) : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ), @@ -83,4 +81,4 @@ Int SeekStreamDialog::runDialog() return m_iSelectedFrameNum; } -} // NAMESPACE + diff --git a/app/SeekStreamDialog.h b/app/SeekStreamDialog.h index 43e4c41..7eff039 100644 --- a/app/SeekStreamDialog.h +++ b/app/SeekStreamDialog.h @@ -31,8 +31,6 @@ #include #include -namespace plaYUVer -{ /** * @@ -49,6 +47,4 @@ private: Int m_iSelectedFrameNum; }; -} // NAMESPACE - #endif // __MODULEHANDLEOPTDIALOG_H__ diff --git a/app/SubWindowAbstract.cpp b/app/SubWindowAbstract.cpp index 730c585..d5197d1 100644 --- a/app/SubWindowAbstract.cpp +++ b/app/SubWindowAbstract.cpp @@ -30,8 +30,6 @@ #include "SubWindowAbstract.h" #include "PlaYUVerMdiSubWindow.h" -namespace plaYUVer -{ SubWindowAbstract::SubWindowAbstract( QWidget * parent, UInt category ) : QWidget( parent ), @@ -115,4 +113,4 @@ Void SubWindowAbstract::closeSubWindow() m_cSubWindow->close(); } -} // NAMESPACE + diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index 2352dfd..c8c90fb 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -48,8 +48,6 @@ class QHBoxLayout; class QFocusEvent; class QCloseEvent; -namespace plaYUVer -{ class PlaYUVerMdiSubWindow; @@ -175,7 +173,5 @@ public Q_SLOTS: }; -} // NAMESPACE - #endif // __SUBWINDOWABSTRACT_H__ diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index 0ca0c55..27871eb 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -41,8 +41,6 @@ #include #endif -namespace plaYUVer -{ VideoHandle::VideoHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : m_pcParet( parent ), @@ -776,5 +774,5 @@ Void VideoHandle::toggleGrid( Bool checked ) } } -} // NAMESPACE + diff --git a/app/VideoHandle.h b/app/VideoHandle.h index 0a2b99a..5fa5699 100644 --- a/app/VideoHandle.h +++ b/app/VideoHandle.h @@ -42,8 +42,6 @@ class QLabel; class QSlider; class QElapsedTimer; -namespace plaYUVer -{ class PlaYUVerSubWindowHandle; class SubWindowAbstract; @@ -150,6 +148,4 @@ private Q_SLOTS: }; -} // NAMESPACE - #endif // __VIDEOHANDLE_H__ diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 449758e..3f2e68c 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -32,8 +32,6 @@ #include "QtConcurrent/qtconcurrentrun.h" #endif -namespace plaYUVer -{ /** * \brief Functions to control data stream from stream information @@ -946,18 +944,3 @@ Void VideoSubWindow::updatePixelValueStatusBar( const QPoint& pos ) } } } - -//Void VideoSubWindow::closeEvent( QCloseEvent *event ) -//{ -// Bool bAccept = m_bIsPlaying ? false : true; -// if( bAccept ) -// { -// event->accept(); -// } -// else -// { -// event->ignore(); -// } -//} - -}// NAMESPACE diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index 48e97a4..7de26cb 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -38,8 +38,6 @@ class QScrollArea; -namespace plaYUVer -{ class VideoInformation; class VideoSubWindow; @@ -263,10 +261,8 @@ public Q_SLOTS: void updatePixelValueStatusBar( const QPoint& pos ); }; -} // NAMESPACE - -Q_DECLARE_METATYPE( plaYUVer::PlaYUVerStreamInfo ); -Q_DECLARE_METATYPE( plaYUVer::PlaYUVerStreamInfoVector ); +Q_DECLARE_METATYPE( PlaYUVerStreamInfo ); +Q_DECLARE_METATYPE( PlaYUVerStreamInfoVector ); #endif // __VIDEOSUBWINDOW_H__ diff --git a/app/ViewArea.cpp b/app/ViewArea.cpp index 6f76928..f5a991c 100644 --- a/app/ViewArea.cpp +++ b/app/ViewArea.cpp @@ -39,8 +39,6 @@ #include "ViewArea.h" #include "GridManager.h" -namespace plaYUVer -{ static const QColor selectionColor = Qt::cyan; static const QColor imageMaskColor = Qt::green; @@ -1091,5 +1089,3 @@ Void ViewArea::updateMask( const QRect &rect ) ; } } - -} // NameSpace plaYUVer diff --git a/app/ViewArea.h b/app/ViewArea.h index 88eb48f..0b61acc 100644 --- a/app/ViewArea.h +++ b/app/ViewArea.h @@ -36,8 +36,6 @@ #include "GridManager.h" #include "lib/PlaYUVerFrame.h" -namespace plaYUVer -{ class PlaYUVerStream; @@ -208,6 +206,4 @@ private: }; -} // NameSpace plaYUVer - #endif // __VIEWAREA_H__ diff --git a/app/WidgetFrameNumber.cpp b/app/WidgetFrameNumber.cpp index fe711e5..4f7f4b0 100644 --- a/app/WidgetFrameNumber.cpp +++ b/app/WidgetFrameNumber.cpp @@ -31,8 +31,6 @@ #endif #include "WidgetFrameNumber.h" -namespace plaYUVer -{ WidgetFrameNumber::WidgetFrameNumber( QWidget *parent ) : QWidget( parent ) @@ -69,5 +67,5 @@ Void WidgetFrameNumber::clear() m_pcTotalFrameNumLabel->setText( "-" ); } -} // NAMESPACE + diff --git a/app/WidgetFrameNumber.h b/app/WidgetFrameNumber.h index a8afede..93619bf 100644 --- a/app/WidgetFrameNumber.h +++ b/app/WidgetFrameNumber.h @@ -35,8 +35,6 @@ #include #endif -namespace plaYUVer -{ class WidgetFrameNumber: public QWidget { @@ -51,6 +49,4 @@ private: }; -} // NAMESPACE - #endif // __WIDGETFRAMENUMBER_H__ diff --git a/app/main.cpp b/app/main.cpp index 73a7895..6f6cfee 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -34,8 +34,6 @@ #include "fvupdater.h" #endif -using namespace plaYUVer; - #if _WIN32 #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.cpp b/examples/modules/AbsoluteFrameDifference_APIv2.cpp index fecf27b..6b45546 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.cpp +++ b/examples/modules/AbsoluteFrameDifference_APIv2.cpp @@ -25,8 +25,6 @@ #include "AbsoluteFrameDifference_APIv2.h" #include -namespace plaYUVer -{ REGISTER_CLASS_MAKER( AbsoluteFrameDifference ) @@ -80,5 +78,5 @@ Void AbsoluteFrameDifference::destroy() m_pcFrameDifference = NULL; } -} // NAMESPACE + diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.h b/examples/modules/AbsoluteFrameDifference_APIv2.h index d685c97..a1e987b 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.h +++ b/examples/modules/AbsoluteFrameDifference_APIv2.h @@ -29,8 +29,6 @@ #include -namespace plaYUVer -{ class AbsoluteFrameDifference: public PlaYUVerModuleIf { @@ -50,7 +48,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMEDIFFERENCE_H__ diff --git a/examples/modules/FrameBinarization_APIv1.cpp b/examples/modules/FrameBinarization_APIv1.cpp index 37b17bb..6fee1ee 100644 --- a/examples/modules/FrameBinarization_APIv1.cpp +++ b/examples/modules/FrameBinarization_APIv1.cpp @@ -24,8 +24,6 @@ #include "FrameBinarization_APIv1.h" -namespace plaYUVer -{ REGISTER_CLASS_MAKER( FrameBinarization ) @@ -71,5 +69,5 @@ Void FrameBinarization::destroy() m_pcBinFrame = NULL; } -} // NAMESPACE + diff --git a/examples/modules/FrameBinarization_APIv1.h b/examples/modules/FrameBinarization_APIv1.h index e7f4cdf..1de89cf 100644 --- a/examples/modules/FrameBinarization_APIv1.h +++ b/examples/modules/FrameBinarization_APIv1.h @@ -27,8 +27,6 @@ #include "PlaYUVerModuleIf.h" -namespace plaYUVer -{ class FrameBinarization: public PlaYUVerModuleIf { @@ -48,7 +46,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMEBINARIZATION_H__ diff --git a/lib/LibMemory.h b/lib/LibMemory.h index b7ab838..c3e1076 100644 --- a/lib/LibMemory.h +++ b/lib/LibMemory.h @@ -30,8 +30,6 @@ #include #include -namespace plaYUVer -{ typedef void Void; typedef char Char; @@ -233,6 +231,6 @@ Void freeMem3ImageComponents( T*** array3D ) } } -} // NAMESPACE + #endif // __LIBMEMORY_H__ diff --git a/lib/PlaYUVerCmdParser.cpp b/lib/PlaYUVerCmdParser.cpp index da0832f..07e5172 100644 --- a/lib/PlaYUVerCmdParser.cpp +++ b/lib/PlaYUVerCmdParser.cpp @@ -30,8 +30,6 @@ #include "PlaYUVerCmdParser.h" #include "PlaYUVerFrame.h" -namespace plaYUVer -{ PlaYUVerCmdParser::PlaYUVerCmdParser() { @@ -139,4 +137,4 @@ Bool PlaYUVerCmdParser::checkListingOpts() return bRet; } -} // NAMESPACE + diff --git a/lib/PlaYUVerCmdParser.h b/lib/PlaYUVerCmdParser.h index 3bc5246..95f21d6 100644 --- a/lib/PlaYUVerCmdParser.h +++ b/lib/PlaYUVerCmdParser.h @@ -25,8 +25,8 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerProgramOptions.h" -namespace plaYUVer -{ +#ifndef __PLAYUVERCMDPARSER_H__ +#define __PLAYUVERCMDPARSER_H__ class PlaYUVerCmdParser { @@ -53,4 +53,4 @@ private: Void listModules(); }; -} // NAMESPACE +#endif // __PLAYUVERCMDPARSER_H__ diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index e0e3fcc..e029da2 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -29,8 +29,6 @@ #include #include -namespace plaYUVer -{ // ==================================================================================================================== // Basic type redefinition @@ -134,6 +132,6 @@ inline std::string uppercase( const std::string& in ) return out; } -} // NAMESPACE + #endif // __PLAYUVERDEFS_H__ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index d9f54d3..48ef1cd 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -36,8 +36,6 @@ #include "StreamHandlerOpenCV.h" #endif -namespace plaYUVer -{ std::vector PlaYUVerFrame::supportedColorSpacesListNames() { @@ -1172,5 +1170,5 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) return dSSIM; } -} // NAMESPACE + diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 320c1f6..2eb4fb6 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -39,8 +39,6 @@ namespace cv class Mat; } -namespace plaYUVer -{ struct PlaYUVerPixFmtDescriptor; @@ -339,6 +337,4 @@ private: Void FrametoRGB8Pixfc(); }; -} // NAMESPACE - #endif // __PLAYUVERFRAME_H__ diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index aff995a..3ee8b12 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -36,8 +36,6 @@ #endif #include "PlaYUVerFramePixelFormats.h" -namespace plaYUVer -{ /* ************************************************************** @@ -319,4 +317,4 @@ PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS RGB24, BGR24, }; -} // NAMESPACE + diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index ed90e4e..5dfe062 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -30,8 +30,6 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" -namespace plaYUVer -{ #define CHROMA_RESAMPLING( X ) ( ( ( X + 1 ) >> 1 ) << 1 ) @@ -147,6 +145,6 @@ typedef struct PlaYUVerPixFmtDescriptor #define PLAYUVER_NUMBER_FORMATS 7 extern PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS]; -} // NAMESPACE + #endif // __PLAYUVERFRAMEPIXELFORMATS_H__ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index ce614dd..b7cf31f 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -31,8 +31,6 @@ #include "PlaYUVerProgramOptions.h" #include -namespace plaYUVer -{ #define REGISTER_CLASS_MAKER(X) \ extern "C" PlaYUVerModuleIf* Maker() { return new X; } @@ -156,7 +154,5 @@ public: }; -} // NAMESPACE - #endif // __PLAYUVERMODULESIF_H__ diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index 7bd7051..dc91280 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -28,8 +28,6 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" -namespace plaYUVer -{ PlaYUVerPixel::PlaYUVerPixel() { @@ -101,4 +99,4 @@ PlaYUVerPixel PlaYUVerPixel::ConvertPixel( ColorSpace eOutputSpace ) return outPixel; } -} // NAMESPACE + diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 72b024f..34f43bf 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -32,8 +32,6 @@ #include #include "PlaYUVerDefs.h" -namespace plaYUVer -{ #define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; #define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ @@ -143,6 +141,4 @@ private: }; -} // NAMESPACE - #endif // __PLAYUVERPIXEL_H__ diff --git a/lib/PlaYUVerProgramOptions.cpp b/lib/PlaYUVerProgramOptions.cpp index a7ee257..b63ac32 100644 --- a/lib/PlaYUVerProgramOptions.cpp +++ b/lib/PlaYUVerProgramOptions.cpp @@ -48,8 +48,6 @@ using namespace std; -namespace plaYUVer -{ Options::Options( const std::string& name ) { @@ -491,5 +489,5 @@ Void Options::doHelp( ostream& out, unsigned columns ) } } -} // NAMESPACE + diff --git a/lib/PlaYUVerProgramOptions.h b/lib/PlaYUVerProgramOptions.h index b1ce0b9..b45792d 100644 --- a/lib/PlaYUVerProgramOptions.h +++ b/lib/PlaYUVerProgramOptions.h @@ -47,8 +47,6 @@ #include #include "PlaYUVerDefs.h" -namespace plaYUVer -{ struct Options; @@ -381,6 +379,4 @@ private: Options& parent; }; -} // NAMESPACE - #endif // __PROGRAMOPTIONS_H__ diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index dc80121..d55a141 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -39,8 +39,6 @@ #include "StreamHandlerOpenCV.h" #endif -namespace plaYUVer -{ std::vector PlaYUVerStream::supportedReadFormats() { @@ -605,4 +603,4 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) return true; } -} // NAMESPACE + diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index c382a70..c785740 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -32,8 +32,6 @@ #include #include "PlaYUVerFrame.h" -namespace plaYUVer -{ class LibOpenCVHandler; class PlaYUVerStreamHandlerIf; @@ -166,6 +164,4 @@ private: }; -} // NAMESPACE - #endif // __PLAYUVERSTREAM_H__ diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 1271b8b..952b232 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -29,8 +29,6 @@ #include "PlaYUVerStream.h" #include "PlaYUVerFrame.h" -namespace plaYUVer -{ #define REGISTER_STREAM_HANDLER(X) \ public: \ @@ -97,8 +95,5 @@ protected: std::string m_strCodecName; }; - -} // NAMESPACE - #endif // __PLAYUVERSTREAMHANDLERIF_H__ diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 42bc15c..700a42a 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -29,8 +29,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" -namespace plaYUVer -{ std::vector StreamHandlerLibav::supportedReadFormats() { @@ -381,4 +379,4 @@ Bool StreamHandlerLibav::seek( UInt64 iFrameNum ) return true; } -} // NAMESPACE + diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 512f674..68cb592 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -51,8 +51,6 @@ extern "C" #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" -namespace plaYUVer -{ class StreamHandlerLibav: public PlaYUVerStreamHandlerIf { @@ -103,6 +101,4 @@ private: Bool decodeVideoPkt(); }; -} // NAMESPACE - #endif // __LIBAVCONTEXTHANDLE_H__ diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index bb305a9..10635c4 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -31,8 +31,6 @@ using namespace cv; -namespace plaYUVer -{ std::vector StreamHandlerOpenCV::supportedReadFormats() { @@ -155,4 +153,4 @@ Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) return bRet; } -} // NAMESPACE + diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index cc177d9..3a29b66 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -38,8 +38,6 @@ namespace cv class VideoCapture; } -namespace plaYUVer -{ class PlaYUVerFrame; @@ -70,6 +68,4 @@ private: cv::Mat* pcMat; }; -} // NAMESPACE - #endif // __STREAMHANDLEROPENCV_H__ diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index e1f4e0f..6ff1600 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -30,8 +30,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" -namespace plaYUVer -{ Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput ) { @@ -141,4 +139,4 @@ Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) return true; } -} // NAMESPACE + diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 666d219..5bb8829 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -33,8 +33,6 @@ #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" -namespace plaYUVer -{ class PlaYUVerFrame; @@ -60,6 +58,4 @@ private: Int m_iMaxValue; }; -} // NAMESPACE - #endif // __STREAMHANDLERPORTABLEMAP_H__ diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 47e6adb..0781313 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -29,8 +29,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" -namespace plaYUVer -{ Bool PlaYUVerRawHandler::openHandler( std::string strFilename, Bool bInput ) { @@ -96,4 +94,4 @@ Bool PlaYUVerRawHandler::write( PlaYUVerFrame* pcFrame ) return true; } -} // NAMESPACE + diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index 13f806b..4ad8bc6 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -28,8 +28,6 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerStreamHandlerIf.h" -namespace plaYUVer -{ /** * \class PlaYUVerRawHandler @@ -58,8 +56,5 @@ public: }; - -} // NAMESPACE - #endif // __STREAMHANDLERRAW_H__ diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 28d5add..0792e57 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -25,8 +25,6 @@ #include "AbsoluteFrameDifference.h" #include -namespace plaYUVer -{ AbsoluteFrameDifference::AbsoluteFrameDifference() { @@ -83,5 +81,5 @@ Void AbsoluteFrameDifference::destroy() m_pcFrameDifference = NULL; } -} // NAMESPACE + diff --git a/modules/AbsoluteFrameDifference.h b/modules/AbsoluteFrameDifference.h index 39f51de..5f2aa34 100644 --- a/modules/AbsoluteFrameDifference.h +++ b/modules/AbsoluteFrameDifference.h @@ -29,8 +29,6 @@ #include -namespace plaYUVer -{ class AbsoluteFrameDifference: public PlaYUVerModuleIf { @@ -50,7 +48,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMEDIFFERENCE_H__ diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index eed79a6..ffdbae7 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -26,8 +26,6 @@ #include "DisparityStereoBM.h" -namespace plaYUVer -{ DisparityStereoBM::DisparityStereoBM() { @@ -110,5 +108,5 @@ Void DisparityStereoBM::destroy() m_pcDisparityFrame = NULL; } -} // NAMESPACE + diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index 32f863b..247d5d8 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -31,8 +31,6 @@ #include -namespace plaYUVer -{ class DisparityStereoBM: public PlaYUVerModuleIf { @@ -59,7 +57,5 @@ public: Void destroy(); }; -} // NAMESPACE - #endif // __DISPARITYSTEREOBM_H__ diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index a34dbe4..064dc1a 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -26,8 +26,6 @@ #include "DisparityStereoSGBM.h" -namespace plaYUVer -{ DisparityStereoSGBM::DisparityStereoSGBM() { @@ -117,5 +115,5 @@ Void DisparityStereoSGBM::destroy() m_pcDisparityFrame = NULL; } -} // NAMESPACE + diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index a1adfbd..074b816 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -43,8 +43,6 @@ #include -namespace plaYUVer -{ class DisparityStereoSGBM: public PlaYUVerModuleIf { @@ -72,7 +70,5 @@ public: Void destroy(); }; -} // NAMESPACE - #endif // __DISPARITYSTEREOSGBM_H__ diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index 55159ef..b1e8764 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -26,8 +26,6 @@ #include "DisparityStereoVar.h" -namespace plaYUVer -{ DisparityStereoVar::DisparityStereoVar() { @@ -85,5 +83,5 @@ Void DisparityStereoVar::destroy() m_pcDisparityFrame = NULL; } -} // NAMESPACE + diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 57872d6..66c1f85 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -31,8 +31,6 @@ #include -namespace plaYUVer -{ class DisparityStereoVar: public PlaYUVerModuleIf { @@ -52,7 +50,5 @@ public: Void destroy(); }; -} // NAMESPACE - #endif // __DISPARITYSTEREOVAR_H__ diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index 0f3ea38..e77635e 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -24,8 +24,6 @@ #include "EightBitsSampling.h" -namespace plaYUVer -{ EightBitsSampling::EightBitsSampling() { @@ -82,5 +80,5 @@ Void EightBitsSampling::destroy() m_pcSubSampledFrame = NULL; } -} // NAMESPACE + diff --git a/modules/EightBitsSampling.h b/modules/EightBitsSampling.h index becc81c..d643436 100644 --- a/modules/EightBitsSampling.h +++ b/modules/EightBitsSampling.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class EightBitsSampling: public PlaYUVerModuleIf { @@ -47,7 +45,5 @@ public: }; -} // NAMESPACE - #endif // __EIGHTBITSSAMPLING_H__ diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index b4e704a..0e88faa 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -26,8 +26,6 @@ #include #include "FilterComponent.h" -namespace plaYUVer -{ FilterComponentModule::FilterComponentModule() { @@ -132,5 +130,5 @@ PlaYUVerFrame* FilterComponentChromaV::process( std::vector apcF return filterComponent( apcFrameList[0], CHROMA_V ); } -} // NAMESPACE + diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index 454bffd..3f623b9 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class FilterComponentModule: public PlaYUVerModuleIf { @@ -83,7 +81,5 @@ public: PlaYUVerFrame* process( std::vector apcFrameList ); }; -} // NAMESPACE - #endif // __FILTERFRAME_H__ diff --git a/modules/FrameBinarization.cpp b/modules/FrameBinarization.cpp index 559169c..5afacac 100644 --- a/modules/FrameBinarization.cpp +++ b/modules/FrameBinarization.cpp @@ -24,8 +24,6 @@ #include "FrameBinarization.h" -namespace plaYUVer -{ FrameBinarization::FrameBinarization() { @@ -69,5 +67,5 @@ Void FrameBinarization::destroy() m_pcBinFrame = NULL; } -} // NAMESPACE + diff --git a/modules/FrameBinarization.h b/modules/FrameBinarization.h index b2e4b31..3d472ef 100644 --- a/modules/FrameBinarization.h +++ b/modules/FrameBinarization.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class FrameBinarization: public PlaYUVerModuleIf { @@ -48,7 +46,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMEBINARIZATION_H__ diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index 34f1ab3..2c57a64 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -24,8 +24,6 @@ #include "FrameCrop.h" -namespace plaYUVer -{ FrameCrop::FrameCrop() { @@ -77,5 +75,5 @@ Void FrameCrop::destroy() m_pcCropedFrame = NULL; } -} // NAMESPACE + diff --git a/modules/FrameCrop.h b/modules/FrameCrop.h index 08a8958..df8bf8b 100644 --- a/modules/FrameCrop.h +++ b/modules/FrameCrop.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class FrameCrop: public PlaYUVerModuleIf { @@ -51,7 +49,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMECROP_H__ diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index 766014a..dd4deaa 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -25,8 +25,6 @@ #include "FrameDifference.h" #include -namespace plaYUVer -{ FrameDifference::FrameDifference() { @@ -105,5 +103,5 @@ Void FrameDifference::destroy() m_pcFrameDifference = NULL; } -} // NAMESPACE + diff --git a/modules/FrameDifference.h b/modules/FrameDifference.h index 9cf5c27..cb497ca 100644 --- a/modules/FrameDifference.h +++ b/modules/FrameDifference.h @@ -29,8 +29,6 @@ #include -namespace plaYUVer -{ class FrameDifference: public PlaYUVerModuleIf { @@ -53,7 +51,5 @@ public: }; -} // NAMESPACE - #endif // __FRAMEDIFFERENCE_H__ diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index 6b93f8d..d29cd7b 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -26,8 +26,6 @@ #include class be; -namespace plaYUVer -{ FrameMask::FrameMask() { @@ -134,5 +132,5 @@ Void FrameMask::destroy() m_pcFrameProcessed = NULL; } -} // NAMESPACE + diff --git a/modules/FrameMask.h b/modules/FrameMask.h index 4205ea6..1a2cd56 100644 --- a/modules/FrameMask.h +++ b/modules/FrameMask.h @@ -29,8 +29,6 @@ #include -namespace plaYUVer -{ class FrameMask: public PlaYUVerModuleIf { @@ -52,8 +50,6 @@ public: }; -} // NAMESPACE - #endif // __FRAMEMASK_H__ diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index a91ca70..257d599 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -24,8 +24,6 @@ #include "FrameShift.h" -namespace plaYUVer -{ FrameShift::FrameShift() { @@ -146,5 +144,5 @@ Void FrameShift::destroy() m_pcProcessedFrame = NULL; } -} // NAMESPACE + diff --git a/modules/FrameShift.h b/modules/FrameShift.h index 28aa0e1..4e79c19 100644 --- a/modules/FrameShift.h +++ b/modules/FrameShift.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class FrameShift: public PlaYUVerModuleIf { @@ -50,7 +48,5 @@ public: }; -} // NAMESPACE - #endif // __FrameShift_H__ diff --git a/modules/LumaAverage.cpp b/modules/LumaAverage.cpp index c4988fe..22dcf68 100644 --- a/modules/LumaAverage.cpp +++ b/modules/LumaAverage.cpp @@ -24,9 +24,6 @@ #include "LumaAverage.h" -namespace plaYUVer -{ - LumaAverage::LumaAverage() { /* Module Definition */ @@ -62,6 +59,3 @@ Void LumaAverage::destroy() } -} -// NAMESPACE - diff --git a/modules/LumaAverage.h b/modules/LumaAverage.h index ccc5628..6b5889a 100644 --- a/modules/LumaAverage.h +++ b/modules/LumaAverage.h @@ -28,8 +28,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class LumaAverage: public PlaYUVerModuleIf { @@ -47,7 +45,5 @@ public: }; -} // NAMESPACE - #endif // __LUMAAVERAGE_H__ diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index e8b4f74..668aa29 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -31,8 +31,6 @@ #include "PlaYUVerModuleFactory.h" #include "ModulesListHeader.h" -namespace plaYUVer -{ PlaYUVerModuleFactory::PlaYUVerModuleFactory() { @@ -85,4 +83,4 @@ PlaYUVerModuleIf *PlaYUVerModuleFactory::CreateModule( const char* moduleName ) return NULL; } -} // NAMESPACE + diff --git a/modules/PlaYUVerModuleFactory.h b/modules/PlaYUVerModuleFactory.h index c2d0243..56bb0a1 100644 --- a/modules/PlaYUVerModuleFactory.h +++ b/modules/PlaYUVerModuleFactory.h @@ -29,8 +29,6 @@ #include #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ #define REGISTER_MODULE(X) Register( "X", &(X::Create) ); @@ -67,12 +65,5 @@ public: } }; -//// typedef to make it easier to set up our factory -//typedef PlaYUVerModuleIf *PlaYUVerModuleMaker(); -//// our global factory -//extern std::map > PlaYUVerModuleFactory; - -}// NAMESPACE - #endif // __PLAYUVERMODULESFACTORY_H__ diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index 2d37b42..3919a98 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -24,8 +24,6 @@ #include "SetChromaHalfScale.h" -namespace plaYUVer -{ SetChromaHalfScale::SetChromaHalfScale() { @@ -71,5 +69,5 @@ Void SetChromaHalfScale::destroy() m_pcProcessedFrame = NULL; } -} // NAMESPACE + diff --git a/modules/SetChromaHalfScale.h b/modules/SetChromaHalfScale.h index 041d3ba..1b0f69e 100644 --- a/modules/SetChromaHalfScale.h +++ b/modules/SetChromaHalfScale.h @@ -27,8 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" -namespace plaYUVer -{ class SetChromaHalfScale: public PlaYUVerModuleIf { @@ -47,7 +45,5 @@ public: }; -} // NAMESPACE - #endif // __CHROMA128_H__ diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 44f5fc1..84cb02d 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -26,8 +26,6 @@ #include #include -namespace plaYUVer -{ WeightedPSNR::WeightedPSNR() { @@ -121,5 +119,5 @@ Void WeightedPSNR::destroy() } -} // NAMESPACE + diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h index c5a3a5b..dd91602 100644 --- a/modules/WeightedPSNR.h +++ b/modules/WeightedPSNR.h @@ -29,8 +29,6 @@ #include -namespace plaYUVer -{ class WeightedPSNR: public PlaYUVerModuleIf { @@ -50,7 +48,5 @@ public: }; -} // NAMESPACE - #endif // __WEIGHTEDPSNR_H__ diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 5c3c58f..70dcf7c 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -28,8 +28,6 @@ #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" -namespace plaYUVer -{ PlaYUVerTools::PlaYUVerTools() { @@ -502,4 +500,4 @@ Int PlaYUVerTools::ModuleOperation() return 0; } -} // NAMESPACE + diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 3b9cb3a..11fa035 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -31,8 +31,6 @@ #include "lib/PlaYUVerStream.h" #include "PlaYUVerToolsCmdParser.h" -namespace plaYUVer -{ class PlaYUVerModuleIf; @@ -83,6 +81,4 @@ private: Int ModuleOperation(); }; -} // NAMESPACE - #endif // __PLAYUVERTOOLS_H__ diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 9855d12..36203bf 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -30,8 +30,6 @@ #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" -namespace plaYUVer -{ PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() { @@ -187,4 +185,4 @@ Void PlaYUVerToolsCmdParser::listModuleHelp() } } -} // NAMESPACE + diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index c2bcf5b..67deeb1 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -29,8 +29,6 @@ #include "lib/PlaYUVerDefs.h" #include "lib/PlaYUVerCmdParser.h" -namespace plaYUVer -{ class PlaYUVerStream; @@ -93,6 +91,4 @@ private: }; -} // NAMESPACE - #endif // __PLAYUVERTOOLSCMDPARSER_H__ diff --git a/tools/main.cpp b/tools/main.cpp index 3683bc9..6a4088e 100644 --- a/tools/main.cpp +++ b/tools/main.cpp @@ -25,8 +25,6 @@ #include "PlaYUVerTools.h" -using namespace plaYUVer; - int main( int argc, char *argv[] ) { Int iRet = 0; From 3dd3e458b95682c716a83c9b397fd19ab1a1f42d Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 03:31:41 +0100 Subject: [PATCH 043/127] Add type name String as std::string --- app/ConfigureFormatDialog.cpp | 4 +- app/DialogSubWindowSelector.cpp | 4 -- app/ModulesHandleOptDialog.cpp | 8 ++-- app/PlaYUVerApp.cpp | 6 +-- app/VideoSubWindow.cpp | 2 +- lib/PlaYUVerDefs.h | 10 +++-- lib/PlaYUVerFrame.cpp | 16 +++---- lib/PlaYUVerFrame.h | 16 +++---- lib/PlaYUVerProgramOptions.cpp | 10 ++--- lib/PlaYUVerProgramOptions.h | 72 ++++++++++++++++---------------- lib/PlaYUVerStream.cpp | 20 ++++----- lib/PlaYUVerStream.h | 24 +++++------ lib/PlaYUVerStreamHandlerIf.h | 12 +++--- lib/StreamHandlerLibav.cpp | 2 +- lib/StreamHandlerLibav.h | 2 +- lib/StreamHandlerOpenCV.cpp | 7 ++-- lib/StreamHandlerOpenCV.h | 2 +- lib/StreamHandlerPortableMap.cpp | 2 +- lib/StreamHandlerPortableMap.h | 2 +- lib/StreamHandlerRaw.cpp | 2 +- lib/StreamHandlerRaw.h | 2 +- tools/PlaYUVerTools.cpp | 14 +++---- tools/PlaYUVerTools.h | 2 +- tools/PlaYUVerToolsCmdParser.cpp | 2 +- tools/PlaYUVerToolsCmdParser.h | 14 +++---- 25 files changed, 128 insertions(+), 129 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 0d717be..9c53950 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -271,7 +271,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWi Int sampling = 0; if( rInputFormat >= 0 ) { - std::string pelFmtName = PlaYUVerFrame::supportedPixelFormatListNames()[rInputFormat]; + String pelFmtName = PlaYUVerFrame::supportedPixelFormatListNames()[rInputFormat]; for( UInt j = 0; j < PlaYUVerFrame::supportedColorSpacesListNames().size(); j++ ) { for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames( j ).size(); i++ ) @@ -314,7 +314,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWi rHeight = m_spinBoxheight->value(); colorSpace = m_comboBoxColorSpace->currentIndex(); sampling = m_comboBoxPixelFormat->currentIndex(); - std::string pelFmtName = PlaYUVerFrame::supportedPixelFormatListNames( colorSpace )[sampling]; + String pelFmtName = PlaYUVerFrame::supportedPixelFormatListNames( colorSpace )[sampling]; for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames().size(); i++ ) { if( pelFmtName == PlaYUVerFrame::supportedPixelFormatListNames()[i] ) diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index 2bf40c3..ab53ea5 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -136,9 +136,6 @@ Void DialogSubWindowSelector::updateSubWindowList() if( !m_apcSelectedSubWindowList.contains( m_apcSubWindowList.at( i ) ) ) m_pcGroupCheckBox->layout()->addWidget( m_apcWindowsListCheckBox.at( i ) ); } - -// qDebug( ) << "Selected windows: " -// << m_apcSelectedSubWindowList.size(); } Void DialogSubWindowSelector::selectSubWindow( SubWindowAbstract * subWindow ) @@ -147,7 +144,6 @@ Void DialogSubWindowSelector::selectSubWindow( SubWindowAbstract * subWindow ) if( iIdx >= 0 ) { m_apcWindowsListCheckBox.at( iIdx )->setChecked( true ); - //m_apcSelectedSubWindowList.append( m_apcSubWindowList.at( iIdx ) ); } } diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 6dbeea3..43ebe8e 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -66,7 +66,7 @@ public: } return m_pcValue->text(); } - const std::string& getName() + const String& getName() { return m_cName; } @@ -74,7 +74,7 @@ private: QLineEdit* m_pcValue; QCheckBox* m_pcChecked; QLabel* m_pcDescription; - std::string m_cName; + String m_cName; }; ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget *parent, PlaYUVerAppModuleIf *pcCurrModuleIf ) : @@ -118,8 +118,8 @@ Int ModulesHandleOptDialog::runConfiguration() return QDialog::Rejected; } - std::vector argsArray; - std::string optionString; + std::vector argsArray; + String optionString; QString valueString( "" ); for( Int i = 0; i < m_apcOptionList.size(); i++ ) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index dac2832..e980754 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -97,9 +97,9 @@ Bool PlaYUVerApp::parseArgs( Int argc, Char *argv[] ) m_pcCmdParser = new PlaYUVerCmdParser(); m_pcCmdParser->config( argc, argv ); - std::vector m_apcInputs; - std::string strResolution( "" ); - std::string strPelFmt( "" ); + std::vector m_apcInputs; + String strResolution( "" ); + String strPelFmt( "" ); m_pcCmdParser->Opts().addOptions()/**/ ( "input,i", m_apcInputs, "input file" ) /**/ diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 3f2e68c..ef158e4 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -443,7 +443,7 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, { bGuessed = false; // Guess pixel format - QVector formats_list = QVector::fromStdVector( PlaYUVerFrame::supportedPixelFormatListNames() ); + QVector formats_list = QVector::fromStdVector( PlaYUVerFrame::supportedPixelFormatListNames() ); for( Int i = 0; i < formats_list.size(); i++ ) { if( FilenameShort.contains( formats_list.at( i ).c_str(), Qt::CaseInsensitive ) ) diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index e029da2..6262817 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -49,6 +49,8 @@ typedef float Float; typedef unsigned char UInt8; typedef unsigned int UInt16; +typedef std::string String; + // ==================================================================================================================== // 64-bit integer type // ==================================================================================================================== @@ -118,16 +120,16 @@ enum RGBcomponent }; -inline std::string lowercase( const std::string& in ) +inline String lowercase( const String& in ) { - std::string out; + String out; transform( in.begin(), in.end(), std::back_inserter( out ), tolower ); return out; } -inline std::string uppercase( const std::string& in ) +inline String uppercase( const String& in ) { - std::string out; + String out; transform( in.begin(), in.end(), std::back_inserter( out ), toupper ); return out; } diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 48ef1cd..7df4a3a 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -37,18 +37,18 @@ #endif -std::vector PlaYUVerFrame::supportedColorSpacesListNames() +std::vector PlaYUVerFrame::supportedColorSpacesListNames() { - std::vector colorSpaceList; + std::vector colorSpaceList; colorSpaceList.push_back( "YUV" ); colorSpaceList.push_back( "RGB" ); colorSpaceList.push_back( "GRAY" ); return colorSpaceList; } -std::vector PlaYUVerFrame::supportedPixelFormatListNames() +std::vector PlaYUVerFrame::supportedPixelFormatListNames() { - std::vector formatsList; + std::vector formatsList; Int numberFormats = PLAYUVER_NUMBER_FORMATS; for( Int i = 0; i < numberFormats; i++ ) { @@ -57,9 +57,9 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames() return formatsList; } -std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int colorSpace ) +std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int colorSpace ) { - std::vector formatsList; + std::vector formatsList; Int numberFormats = PLAYUVER_NUMBER_FORMATS; for( Int i = 0; i < numberFormats; i++ ) { @@ -69,7 +69,7 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int color return formatsList; } -Int PlaYUVerFrame::findPixelFormat( std::string name ) +Int PlaYUVerFrame::findPixelFormat( String name ) { for( Int i = 0; i < PLAYUVER_NUMBER_FORMATS; i++ ) { @@ -257,7 +257,7 @@ Bool PlaYUVerFrame::haveSameFmt( PlaYUVerFrame* other, UInt match ) const return bRet; } -std::string PlaYUVerFrame::getPelFmtName() +String PlaYUVerFrame::getPelFmtName() { return m_pcPelFormat->name; } diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 2eb4fb6..cc49ed6 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -87,16 +87,16 @@ public: * of PlaYUVerFrame * @return vector of strings with pixel formats names */ - static std::vector supportedColorSpacesListNames(); + static std::vector supportedColorSpacesListNames(); /** * Function that handles the supported pixel formats * of PlaYUVerFrame * @return vector of strings with pixel formats names */ - static std::vector supportedPixelFormatListNames(); - static std::vector supportedPixelFormatListNames( Int colorSpace ); - static Int findPixelFormat( std::string name ); + static std::vector supportedPixelFormatListNames(); + static std::vector supportedPixelFormatListNames( Int colorSpace ); + static Int findPixelFormat( String name ); /** * Get number of bytes per frame of a specific @@ -221,7 +221,7 @@ public: Bool haveSameFmt( PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; - std::string getPelFmtName(); + String getPelFmtName(); /** * Histogram @@ -271,9 +271,9 @@ public: NUMBER_METRICS, }; - static std::vector supportedQualityMetricsList() + static std::vector supportedQualityMetricsList() { - std::vector metrics; + std::vector metrics; metrics.push_back( "PSNR" ); metrics.push_back( "MSE" ); metrics.push_back( "SSIM" ); @@ -293,7 +293,7 @@ private: //! Struct with the pixel format description. PlaYUVerPixFmtDescriptor* m_pcPelFormat; - std::string m_cPelFmtName; + String m_cPelFmtName; UInt m_uiWidth; //!< Width of the frame UInt m_uiHeight; //!< Height of the frame diff --git a/lib/PlaYUVerProgramOptions.cpp b/lib/PlaYUVerProgramOptions.cpp index b63ac32..436b1bb 100644 --- a/lib/PlaYUVerProgramOptions.cpp +++ b/lib/PlaYUVerProgramOptions.cpp @@ -49,7 +49,7 @@ using namespace std; -Options::Options( const std::string& name ) +Options::Options( const String& name ) { m_cOptionGroupName = name; m_bAllowUnkonw = true; @@ -63,12 +63,12 @@ Options::~Options() } } -OptionBase* Options::operator[]( const std::string& optName ) +OptionBase* Options::operator[]( const String& optName ) { return getOption( optName ); } -OptionBase* Options::getOption( const std::string& optName ) +OptionBase* Options::getOption( const String& optName ) { Options::OptionMap::iterator opt_it; opt_it = opt_short_map.find( optName ); @@ -92,7 +92,7 @@ OptionBase* Options::getOption( const std::string& optName ) return NULL; } -Bool Options::hasOpt( const std::string& optName ) +Bool Options::hasOpt( const String& optName ) { return getOption( optName )->count() > 0 ? true : false; } @@ -347,7 +347,7 @@ list Options::scanArgv( unsigned argc, const char* argv[] ) return non_option_arguments; } -Void Options::scanArgs( std::vector args_array) +Void Options::scanArgs( std::vector args_array) { for( unsigned i = 0; i < args_array.size(); i++ ) { diff --git a/lib/PlaYUVerProgramOptions.h b/lib/PlaYUVerProgramOptions.h index b45792d..d1bcd8a 100644 --- a/lib/PlaYUVerProgramOptions.h +++ b/lib/PlaYUVerProgramOptions.h @@ -52,7 +52,7 @@ struct Options; struct ParseFailure: public std::exception { - ParseFailure( std::string arg0, std::string val0 ) throw() : + ParseFailure( String arg0, String val0 ) throw() : arg( arg0 ), val( val0 ) { @@ -62,8 +62,8 @@ struct ParseFailure: public std::exception { } - std::string arg; - std::string val; + String arg; + String val; const char* what() const throw() { @@ -76,7 +76,7 @@ struct ParseFailure: public std::exception * information should be stored in a derived class. */ struct OptionBase { - OptionBase( const std::string& name, const std::string& desc ) : + OptionBase( const String& name, const String& desc ) : arg_count( 0 ), opt_string( name ), opt_desc( desc ) @@ -88,7 +88,7 @@ struct OptionBase } /* parse argument arg, to obtain a value for the option */ - virtual void parse( const std::string& arg ) = 0; + virtual void parse( const String& arg ) = 0; /* set the argument to the default value */ //virtual void setDefault() = 0; int count() @@ -101,15 +101,15 @@ struct OptionBase } int arg_count; - std::string opt_string; - std::string opt_desc; + String opt_string; + String opt_desc; Bool is_binary; }; /** Type specific option storage */ struct FlagOpt: public OptionBase { - FlagOpt( const std::string& name, Bool default_val, const std::string& desc ) : + FlagOpt( const String& name, Bool default_val, const String& desc ) : OptionBase( name, desc ), opt_storage( false ), opt_default_val( default_val ) @@ -117,7 +117,7 @@ struct FlagOpt: public OptionBase is_binary = true; } - void parse( const std::string& arg ) + void parse( const String& arg ) { opt_storage = true; arg_count++; @@ -135,14 +135,14 @@ struct FlagOpt: public OptionBase template struct StandardOpt: public OptionBase { - StandardOpt( const std::string& name, T& storage, const std::string& desc ) : + StandardOpt( const String& name, T& storage, const String& desc ) : OptionBase( name, desc ), opt_storage( storage ) { is_binary = false; } - void parse( const std::string& arg ); + void parse( const String& arg ); // void setDefault() // { @@ -154,7 +154,7 @@ struct StandardOpt: public OptionBase /* Generic parsing */ template -inline void StandardOpt::parse( const std::string& arg ) +inline void StandardOpt::parse( const String& arg ) { std::istringstream arg_ss( arg, std::istringstream::in ); arg_ss.exceptions( std::ios::failbit ); @@ -170,7 +170,7 @@ inline void StandardOpt::parse( const std::string& arg ) } template<> -inline void StandardOpt< std::vector >::parse( const std::string& arg ) +inline void StandardOpt< std::vector >::parse( const String& arg ) { UInt aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -188,7 +188,7 @@ inline void StandardOpt< std::vector >::parse( const std::string& arg ) } template<> -inline void StandardOpt< std::vector >::parse( const std::string& arg ) +inline void StandardOpt< std::vector >::parse( const String& arg ) { Int aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -207,7 +207,7 @@ inline void StandardOpt< std::vector >::parse( const std::string& arg ) /* string parsing is specialized */ template<> -inline void StandardOpt::parse( const std::string& arg ) +inline void StandardOpt::parse( const String& arg ) { opt_storage = arg; arg_count++; @@ -215,7 +215,7 @@ inline void StandardOpt::parse( const std::string& arg ) /* string vector parsing is specialized */ template<> -inline void StandardOpt >::parse( const std::string& arg ) +inline void StandardOpt >::parse( const String& arg ) { opt_storage.push_back( arg ); arg_count++; @@ -224,9 +224,9 @@ inline void StandardOpt >::parse( const std::string& ar /** Option class for argument handling using a user provided function */ struct OptionFunc: public OptionBase { - typedef Void (Func)( Options&, const std::string& ); + typedef Void (Func)( Options&, const String& ); - OptionFunc( const std::string& name, Options& parent_, Func *func_, const std::string& desc ) : + OptionFunc( const String& name, Options& parent_, Func *func_, const String& desc ) : OptionBase( name, desc ), parent( parent_ ), func( func_ ) @@ -234,7 +234,7 @@ struct OptionFunc: public OptionBase is_binary = false; } - void parse( const std::string& arg ) + void parse( const String& arg ) { func( parent, arg ); arg_count++; @@ -247,7 +247,7 @@ struct OptionFunc: public OptionBase private: Options& parent; - void (*func)( Options&, const std::string& ); + void (*func)( Options&, const String& ); }; class OptionSpecific; @@ -267,49 +267,49 @@ public: if( opt ) delete opt; } - std::list opt_long; - std::list opt_short; + std::list opt_long; + std::list opt_short; OptionBase* opt; }; typedef std::list OptionsList; - Options( const std::string& name = "" ); + Options( const String& name = "" ); ~Options(); std::list scanArgv( unsigned argc, const char* argv[] ); - Void scanArgs( std::vector args_array); + Void scanArgs( std::vector args_array); Void doHelp( std::ostream& out, unsigned columns = 80 ); OptionSpecific addOptions(); Void setDefaults(); - OptionBase* operator[]( const std::string& optName ); - OptionBase* getOption( const std::string& optName ); + OptionBase* operator[]( const String& optName ); + OptionBase* getOption( const String& optName ); OptionsList& getOptionList() { return opt_list; } - Bool hasOpt( const std::string& optName ); + Bool hasOpt( const String& optName ); void addOption( OptionBase *opt ); private: - typedef std::map OptionMap; + typedef std::map OptionMap; OptionMap opt_long_map; OptionMap opt_short_map; OptionsList opt_list; - std::string m_cOptionGroupName; + String m_cOptionGroupName; Bool m_bAllowUnkonw; - Bool storePair( Bool allow_long, Bool allow_short, const std::string& name, const std::string& value ); - Bool storePair( const std::string& name, const std::string& value ); + Bool storePair( Bool allow_long, Bool allow_short, const String& name, const String& value ); + Bool storePair( const String& name, const String& value ); UInt parseLONG( unsigned argc, const char* argv[] ); - UInt parseLONG( std::string arg ); + UInt parseLONG( String arg ); unsigned parseSHORT( unsigned argc, const char* argv[] ); }; @@ -330,7 +330,7 @@ public: */ template OptionSpecific& - operator()( const std::string& name, T& storage, const std::string& desc ) + operator()( const String& name, T& storage, const String& desc ) { parent.addOption( new StandardOpt( name, storage, desc ) ); return *this; @@ -343,7 +343,7 @@ public: * with desc as an optional help description */ OptionSpecific& - operator()( const std::string& name, const std::string& desc ) + operator()( const String& name, const String& desc ) { parent.addOption( new FlagOpt( name, false, desc ) ); return *this; @@ -356,7 +356,7 @@ public: * with desc as an optional help description */ OptionSpecific& - operator()( const std::string& name, Bool default_val, const std::string& desc ) + operator()( const String& name, Bool default_val, const String& desc ) { parent.addOption( new FlagOpt( name, default_val, desc ) ); return *this; @@ -370,7 +370,7 @@ public: * handle evaluating the option's value. */ OptionSpecific& - operator()( const std::string& name, OptionFunc::Func *func, const std::string& desc ) + operator()( const String& name, OptionFunc::Func *func, const String& desc ) { parent.addOption( new OptionFunc( name, parent, func, desc ) ); return *this; diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index d55a141..586cc96 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -99,9 +99,9 @@ std::vector PlaYUVerStream::stdResolutionSizes() } -CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( std::string strFilename, bool bRead ) +CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, bool bRead ) { - std::string currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 ); + String currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 ); currExt = lowercase( currExt ); std::vector supportedFmts; @@ -119,7 +119,7 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( std::string strFilename { return supportedFmts[i].formatFct; } - else if( strFilename.find( supportedFmts[i].formatExt ) != std::string::npos ) + else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) { return supportedFmts[i].formatFct; } @@ -150,16 +150,16 @@ PlaYUVerStream::~PlaYUVerStream() close(); } -std::string PlaYUVerStream::getFormatName() +String PlaYUVerStream::getFormatName() { return !m_pcHandler ? "" : m_pcHandler->getFormatName(); } -std::string PlaYUVerStream::getCodecName() +String PlaYUVerStream::getCodecName() { return !m_pcHandler ? "" : m_pcHandler->getCodecName(); } -Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::string input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( String filename, String resolution, String input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { UInt width; UInt height; @@ -184,7 +184,7 @@ Bool PlaYUVerStream::open( std::string filename, std::string resolution, std::st return open( filename, width, height, input_format, bitsPel, endianness, frame_rate, bInput ); } -Bool PlaYUVerStream::open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { if( m_bInit ) { @@ -331,7 +331,7 @@ Void PlaYUVerStream::close() m_bInit = false; } -std::string PlaYUVerStream::getFileName() +String PlaYUVerStream::getFileName() { return m_cFilename; } @@ -488,12 +488,12 @@ Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) return; } -Bool PlaYUVerStream::saveFrame( const std::string& filename ) +Bool PlaYUVerStream::saveFrame( const String& filename ) { return saveFrame( filename, m_pcCurrFrame ); } -Bool PlaYUVerStream::saveFrame( const std::string& filename, PlaYUVerFrame *saveFrame ) +Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame *saveFrame ) { PlaYUVerStream auxSaveStream; if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), saveFrame->getEndianness(), 1, false ) ) diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index c785740..3449985 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -38,7 +38,7 @@ class PlaYUVerStreamHandlerIf; typedef struct { - std::string shortName; + String shortName; UInt uiWidth; UInt uiHeight; } PlaYUVerStdResolution; @@ -48,8 +48,8 @@ typedef PlaYUVerStreamHandlerIf* (*CreateStreamHandlerFn)( void ); typedef struct { - std::string formatName; - std::string formatExt; + String formatName; + String formatExt; CreateStreamHandlerFn formatFct; } PlaYUVerSupportedFormat; @@ -84,7 +84,7 @@ public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - static CreateStreamHandlerFn findStreamHandler( std::string strFilename, bool bRead ); + static CreateStreamHandlerFn findStreamHandler( String strFilename, bool bRead ); static std::vector stdResolutionSizes(); @@ -100,15 +100,15 @@ public: END_OF_SEQ, }; - std::string getFormatName(); - std::string getCodecName(); + String getFormatName(); + String getCodecName(); - Bool open( std::string filename, std::string resolution, std::string input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); - Bool open( std::string filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); + Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); + Bool open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); Bool reload(); Void close(); - std::string getFileName(); + String getFileName(); UInt getFrameNum(); UInt getWidth() const; UInt getHeight() const; @@ -123,8 +123,8 @@ public: Void writeFrame(); Void writeFrame( PlaYUVerFrame *pcFrame ); - Bool saveFrame( const std::string& filename ); - static Bool saveFrame( const std::string& filename, PlaYUVerFrame *saveFrame ); + Bool saveFrame( const String& filename ); + static Bool saveFrame( const String& filename, PlaYUVerFrame *saveFrame ); Bool setNextFrame(); PlaYUVerFrame* getCurrFrame(); @@ -149,7 +149,7 @@ private: PlaYUVerStreamHandlerIf* m_pcHandler; Bool m_bIsInput; - std::string m_cFilename; + String m_cFilename; UInt64 m_uiTotalFrameNum; Int64 m_iCurrFrameNum; diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 952b232..939471e 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -58,7 +58,7 @@ public: { } - virtual Bool openHandler( std::string strFilename, Bool bInput ) = 0; + virtual Bool openHandler( String strFilename, Bool bInput ) = 0; virtual Void closeHandler() = 0; virtual Bool configureBuffer( PlaYUVerFrame* pcFrame ) = 0; virtual UInt64 calculateFrameNumber() = 0; @@ -70,18 +70,18 @@ public: { m_uiNBytesPerFrame = uiNBytes; } - std::string getFormatName() + String getFormatName() { return m_strFormatName; } - std::string getCodecName() + String getCodecName() { return m_strCodecName; } protected: Bool m_bIsInput; - std::string m_cFilename; + String m_cFilename; UInt m_uiWidth; UInt m_uiHeight; Int m_iPixelFormat; @@ -91,8 +91,8 @@ protected: Byte* m_pStreamBuffer; UInt64 m_uiNBytesPerFrame; - std::string m_strFormatName; - std::string m_strCodecName; + String m_strFormatName; + String m_strCodecName; }; #endif // __PLAYUVERSTREAMHANDLERIF_H__ diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 700a42a..8b9e9aa 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -87,7 +87,7 @@ static int open_codec_context( int *stream_idx, AVFormatContext *m_cFmtCtx, enum return 0; } -Bool StreamHandlerLibav::openHandler( std::string strFilename, Bool bInput ) +Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) { const char* filename = strFilename.c_str(); diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 68cb592..953c97e 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -68,7 +68,7 @@ public: { } - Bool openHandler( std::string strFilename, Bool bInput ); + Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 10635c4..43aa139 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -29,7 +29,8 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" -using namespace cv; +using cv::Mat; +using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() @@ -56,7 +57,7 @@ StreamHandlerOpenCV::StreamHandlerOpenCV() pcVideoCapture = NULL; } -Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) +Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) { m_cFilename = strFilename; if( bInput ) @@ -66,7 +67,7 @@ Bool StreamHandlerOpenCV::openHandler( std::string strFilename, Bool bInput ) /* * Special filename to handle webcam input */ - if( m_cFilename.find( "/dev/video" ) != std::string::npos ) + if( m_cFilename.find( "/dev/video" ) != String::npos ) { m_strFormatName = "DEV"; m_strCodecName = "Raw Video"; diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index 3a29b66..acb769a 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -55,7 +55,7 @@ public: { } - Bool openHandler( std::string strFilename, Bool bInput ); + Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index 6ff1600..f866f53 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -31,7 +31,7 @@ #include "LibMemory.h" -Bool StreamHandlerPortableMap::openHandler( std::string strFilename, Bool bInput ) +Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; m_pFile = NULL; diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 5bb8829..4cbd389 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -44,7 +44,7 @@ public: StreamHandlerPortableMap() {} ~StreamHandlerPortableMap() {} - Bool openHandler( std::string strFilename, Bool bInput ); + Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 0781313..6164c46 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -30,7 +30,7 @@ #include "LibMemory.h" -Bool PlaYUVerRawHandler::openHandler( std::string strFilename, Bool bInput ) +Bool PlaYUVerRawHandler::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; m_pFile = NULL; diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index 4ad8bc6..28c23a5 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -45,7 +45,7 @@ public: PlaYUVerRawHandler() {} ~PlaYUVerRawHandler() {} - Bool openHandler( std::string strFilename, Bool bInput ); + Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); UInt64 calculateFrameNumber(); diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 70dcf7c..d9b20d3 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -62,10 +62,10 @@ Int PlaYUVerTools::openInputs() */ if( m_cCmdLineHandler.Opts().hasOpt( "input" ) ) { - std::vector inputFileNames = m_cCmdLineHandler.m_apcInputs; + std::vector inputFileNames = m_cCmdLineHandler.m_apcInputs; - std::string resolutionString( "" ); - std::string fmtString( "yuv420p" ); + String resolutionString( "" ); + String fmtString( "yuv420p" ); UInt uiBitPerPixel = 8; UInt uiEndianness = 0; @@ -184,7 +184,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) */ if( m_cCmdLineHandler.Opts().hasOpt( "quality" ) ) { - std::string qualityMetric = m_cCmdLineHandler.m_strQualityMetric; + String qualityMetric = m_cCmdLineHandler.m_strQualityMetric; if( m_apcInputStreams.size() < 2 ) { m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of inputs! " ); @@ -212,7 +212,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) */ if( m_cCmdLineHandler.Opts().hasOpt( "module" ) ) { - std::string moduleName = m_cCmdLineHandler.m_strModule; + String moduleName = m_cCmdLineHandler.m_strModule; PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); PlaYUVerModuleFactoryMap::iterator it = PlaYUVerModuleFactoryMap.begin(); @@ -263,7 +263,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) if( m_pcCurrModuleIf->m_iModuleType == FRAME_PROCESSING_MODULE ) { // Check outputs - std::vector outputFileNames; + std::vector outputFileNames; if( m_cCmdLineHandler.Opts().hasOpt( "output" ) ) outputFileNames.push_back( m_cCmdLineHandler.m_strOutput ); @@ -341,7 +341,7 @@ Int PlaYUVerTools::QualityOperation() Double adAverageQuality[MAX_NUMBER_INPUTS - 1][MAX_NUMBER_COMPONENTS]; Double dQuality; - std::string metric_fmt = " "; + String metric_fmt = " "; switch( m_uiQualityMetric ) { case PlaYUVerFrame::PSNR_METRIC: diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 11fa035..baf0fcd 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -70,7 +70,7 @@ private: FpProcess m_fpProcess; Int64 m_iFrameNum; - std::vector m_pcOutputFileNames; + std::vector m_pcOutputFileNames; Int SaveOperation(); Int m_uiQualityMetric; diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 36203bf..2af415a 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -165,7 +165,7 @@ Void PlaYUVerToolsCmdParser::listModules() Void PlaYUVerToolsCmdParser::listModuleHelp() { - std::string moduleName = m_strModule; + String moduleName = m_strModule; PlaYUVerModuleIf* pcCurrModuleIf = NULL; PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 67deeb1..adfde00 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -71,16 +71,16 @@ private: Bool m_bShowVersion; Bool m_bQuiet; - std::vector m_apcInputs; - std::vector m_strResolution; - std::vector m_strPelFmt; + std::vector m_apcInputs; + std::vector m_strResolution; + std::vector m_strPelFmt; std::vector m_uiBitsPerPixel; - std::vector m_strEndianness; - std::string m_strOutput; + std::vector m_strEndianness; + String m_strOutput; Int64 m_iFrames; - std::string m_strQualityMetric; - std::string m_strModule; + String m_strQualityMetric; + String m_strModule; Bool m_bListPelFmts; Bool m_bListQuality; From 5b2d7d69b160c6ab981eb66f64a017edc765cadf Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 04:47:13 +0100 Subject: [PATCH 044/127] Clean up some includes --- app/ConfigureFormatDialog.cpp | 12 ++++++++++-- app/ConfigureFormatDialog.h | 19 +++++++++---------- app/PlaYUVerSubWindowHandle.cpp | 12 ++++++++++++ app/PlaYUVerSubWindowHandle.h | 17 ++++++++++------- app/SubWindowAbstract.h | 5 +++-- 5 files changed, 44 insertions(+), 21 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 9c53950..40f8f74 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -22,10 +22,19 @@ * \brief Dialog box to set the sequence resolution */ -#include "ConfigureFormatDialog.h" +#include +#include +#include +#include +#include +#include +#include +#include + #include "lib/PlaYUVerFrame.h" #include "lib/PlaYUVerStream.h" +#include "ConfigureFormatDialog.h" ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : QDialog( parent ) @@ -225,7 +234,6 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : framerateWidget->setContentsMargins( 0,0,0,0 ); framerateWidget->setLayout( framerateFormatLayout ); - /* * Confirmation buttons */ diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index 89edce5..3eefb8d 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -25,18 +25,17 @@ #ifndef __CONFIGUREFORMATDIALOG_H__ #define __CONFIGUREFORMATDIALOG_H__ -#include "config.h" +#include +#include +#include + #include "PlaYUVerAppDefs.h" -#if( QT_VERSION_PLAYUVER == 5 ) -#include -#elif( QT_VERSION_PLAYUVER == 4 ) -#include -#endif -#include - -class QPixmap; -class QColor; +class QComboBox; +class QHBoxLayout; +class QLabel; +class QSpinBox; +class QWidget; /** * diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index 799839e..4eb4768 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -22,7 +22,19 @@ * \brief Handle multiple sub-windows */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include "PlaYUVerSubWindowHandle.h" + #include "PlaYUVerApp.h" #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" diff --git a/app/PlaYUVerSubWindowHandle.h b/app/PlaYUVerSubWindowHandle.h index 614995e..de36a61 100644 --- a/app/PlaYUVerSubWindowHandle.h +++ b/app/PlaYUVerSubWindowHandle.h @@ -25,14 +25,17 @@ #ifndef __PLAYUVERSUBWINDOWHANDLE_H__ #define __PLAYUVERSUBWINDOWHANDLE_H__ -#include "config.h" -#include "PlaYUVerAppDefs.h" -#if( QT_VERSION_PLAYUVER == 5 ) -#include -#elif( QT_VERSION_PLAYUVER == 4 ) -#include -#endif +#include +#include +#include +#include "PlaYUVerAppDefs.h" + +class QAction; +class QActionGroup; +class QHBoxLayout; +class QMenu; +class QSignalMapper; class PlaYUVerApp; class SubWindowAbstract; diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index c8c90fb..c6d7515 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -63,14 +63,15 @@ private: PlaYUVerMdiSubWindow* m_cSubWindow; public: - enum SubWindowCategories + enum SubWindowCategory { SUBWINDOW = 0, VIDEO_SUBWINDOW = 1, VIDEO_STREAM_SUBWINDOW = 2, MODULE_SUBWINDOW = 4, PLOT_SUBWINDOW = 8, - }; + }; Q_DECLARE_FLAGS( SubWindowCategories, SubWindowCategory ) + SubWindowAbstract( QWidget *, UInt ); ~SubWindowAbstract(); From a654d89904b95c7bae9912fc8740b32b751d6bc3 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 30 Apr 2016 19:45:50 +0100 Subject: [PATCH 045/127] Improve portability of PlaYUVerFrame and PlaYUVerPixel --- app/HistogramWidget.cpp | 3 +- lib/PlaYUVerFrame.cpp | 551 ++++++++++++++++++++++++---------------- lib/PlaYUVerFrame.h | 175 ++++--------- lib/PlaYUVerPixel.cpp | 76 +++++- lib/PlaYUVerPixel.h | 112 ++++---- tools/PlaYUVerTools.cpp | 2 +- 6 files changed, 498 insertions(+), 421 deletions(-) diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index c470a25..e3d57ba 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -66,7 +66,8 @@ public: m_pcFrame->calcHistogram(); eventData->starting = false; - eventData->success = m_pcFrame->getHasHistogram(); +// eventData->success = m_pcFrame->getHasHistogram(); + eventData->success = true; eventData->frame = m_pcFrame; QCoreApplication::postEvent( m_parent, eventData ); } diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 7df4a3a..8f440fe 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -37,6 +37,10 @@ #endif +/*! \brief Supported formats + * + * List of supported pixels formats + */ std::vector PlaYUVerFrame::supportedColorSpacesListNames() { std::vector colorSpaceList; @@ -79,18 +83,69 @@ Int PlaYUVerFrame::findPixelFormat( String name ) return -1; } -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) +struct PlaYUVerFramePrivate { - init( width, height, pelFormat, bitsPixel, endianness ); + /** + * Common constructor function of a frame + * + * @param width width of the frame + * @param height height of the frame + * @param pel_format pixel format index (always use PixelFormats enum) + * + */ + Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ); + + Bool m_bInit; + + //! Struct with the pixel format description. + PlaYUVerPixFmtDescriptor* m_pcPelFormat; + String m_cPelFmtName; + + UInt m_uiWidth; //!< Width of the frame + UInt m_uiHeight; //!< Height of the frame + Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) + Int m_iNumberChannels; //!< Number of channels + UInt m_uiBitsPel; //!< Bits per pixel/channel + Int m_iEndianness; //!< Endiannes of bytes + UInt m_uiHalfPelValue; //!< Bits per pixel/channel + + Pel*** m_pppcInputPel; + + Bool m_bHasRGBPel; //!< Flag indicating that the ARGB buffer was computed + UChar* m_pcARGB32; //!< Buffer with the ARGB pixels used in Qt libs + + /** The histogram data.*/ + UInt* m_puiHistogram; + + /** If the image is RGB and calcLuma is true, we have 1 more channel */ + UInt m_uiHistoChannels; + + /** Numbers of histogram segments depending of image bytes depth*/ + UInt m_uiHistoSegments; + + /** Used to stop thread during calculations.*/ + Bool m_bRunningFlag; + + Bool m_bHasHistogram; +}; + + +/*! \brief Constructors + * + * Constructors and init functions + */ +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : d( new PlaYUVerFramePrivate ) +{ + d->init( width, height, pelFormat, bitsPixel, endianness ); } -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) +PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) : d( new PlaYUVerFramePrivate ) { - init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); copyFrom( other ); } -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) +PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : d( new PlaYUVerFramePrivate ) { PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) @@ -110,28 +165,10 @@ PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt a areaHeight++; } - init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + d->init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); copyFrom( other, posX, posY ); } -PlaYUVerFrame::~PlaYUVerFrame() -{ - if( m_puiHistogram ) - { - freeMem1D( m_puiHistogram ); - } - m_puiHistogram = NULL; - m_bHasHistogram = false; - - if( m_pppcInputPel ) - freeMem3ImageComponents( m_pppcInputPel ); - m_pppcInputPel = NULL; - - if( m_pcARGB32 ) - freeMem1D( m_pcARGB32 ); - m_pcARGB32 = NULL; -} - static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) { Int dim0 = 3; @@ -166,7 +203,7 @@ static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2 return total_mem_size; } -Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) +Void PlaYUVerFramePrivate::init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) { m_bInit = false; m_pppcInputPel = NULL; @@ -216,18 +253,38 @@ Void PlaYUVerFrame::init( UInt width, UInt height, Int pel_format, Int bitsPixel m_bInit = true; } +PlaYUVerFrame::~PlaYUVerFrame() +{ + if( d->m_puiHistogram ) + { + freeMem1D( d->m_puiHistogram ); + } + d->m_puiHistogram = NULL; + d->m_bHasHistogram = false; + + if( d->m_pppcInputPel ) + freeMem3ImageComponents( d->m_pppcInputPel ); + d->m_pppcInputPel = NULL; + + if( d->m_pcARGB32 ) + freeMem1D( d->m_pcARGB32 ); + d->m_pcARGB32 = NULL; + + delete d; +} + Void PlaYUVerFrame::clear() { Pel* pPel; Pel uiValue = 128; Int ratioH, ratioW; UInt i; - for( UInt ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - ratioW = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - pPel = m_pppcInputPel[ch][0]; - for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) + ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + pPel = d->m_pppcInputPel[ch][0]; + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) { *pPel++ = uiValue; } @@ -257,24 +314,81 @@ Bool PlaYUVerFrame::haveSameFmt( PlaYUVerFrame* other, UInt match ) const return bRet; } +Int PlaYUVerFrame::getPelFormat() const +{ + return d->m_iPixelFormat; +} + String PlaYUVerFrame::getPelFmtName() { - return m_pcPelFormat->name; + return d->m_pcPelFormat->name; } Int PlaYUVerFrame::getColorSpace() const { - return m_pcPelFormat->colorSpace; + return d->m_pcPelFormat->colorSpace; } UInt PlaYUVerFrame::getNumberChannels() const { - return m_pcPelFormat->numberChannels; + return d->m_pcPelFormat->numberChannels; +} + +UInt PlaYUVerFrame::getWidth( Int channel ) const +{ + return CHROMASHIFT( d->m_uiWidth, channel > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0 ); +} +UInt PlaYUVerFrame::getHeight( Int channel ) const +{ + return CHROMASHIFT( d->m_uiHeight, channel > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0 ); +} + +UInt PlaYUVerFrame::getPixels( Int channel ) const +{ + return getWidth( channel ) * getWidth( channel ); +} + +UInt8 PlaYUVerFrame::getChromaWidthRatio() const +{ + return d->m_pcPelFormat->log2ChromaWidth; +} + +UInt8 PlaYUVerFrame::getChromaHeightRatio() const +{ + return d->m_pcPelFormat->log2ChromaHeight; +} + +UInt PlaYUVerFrame::getChromaWidth() const +{ + if( d->m_pcPelFormat->colorSpace == GRAY ) + return 0; + return CHROMASHIFT( d->m_uiWidth, d->m_pcPelFormat->log2ChromaWidth ); +} + +UInt PlaYUVerFrame::getChromaHeight() const +{ + if( d->m_pcPelFormat->colorSpace == GRAY ) + return 0; + return CHROMASHIFT( d->m_uiHeight, d->m_pcPelFormat->log2ChromaHeight ); +} + +UInt PlaYUVerFrame::getChromaLength() const +{ + return getChromaWidth() * getChromaHeight(); +} + +UInt PlaYUVerFrame::getBitsPel() const +{ + return d->m_uiBitsPel; +} +Int PlaYUVerFrame::getEndianness() const +{ + return d->m_iEndianness; } UInt64 PlaYUVerFrame::getBytesPerFrame() { - return getBytesPerFrame( m_uiWidth, m_uiHeight, m_iPixelFormat, m_uiBitsPel ); + return getBytesPerFrame( d->m_uiWidth, d->m_uiHeight, d->m_iPixelFormat, d->m_uiBitsPel ); } UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ) @@ -290,65 +404,54 @@ UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelF return numberBytes * bytesPerPixel; } -UInt PlaYUVerFrame::getPixels() const +Pel*** PlaYUVerFrame::getPelBufferYUV() const { - return ( m_uiWidth * m_uiHeight ); + return d->m_pppcInputPel; +} +Pel*** PlaYUVerFrame::getPelBufferYUV() +{ + d->m_bHasHistogram = false; + d->m_bHasRGBPel = false; + return d->m_pppcInputPel; } -UInt8 PlaYUVerFrame::getChromaWidthRatio() const +UChar* PlaYUVerFrame::getRGBBuffer() const { - return m_pcPelFormat->log2ChromaWidth; + if( d->m_bHasRGBPel ) + { + return d->m_pcARGB32; + } + return NULL; } - -UInt8 PlaYUVerFrame::getChromaHeightRatio() const +UChar* PlaYUVerFrame::getRGBBuffer() { - return m_pcPelFormat->log2ChromaHeight; -} - -UInt PlaYUVerFrame::getChromaWidth() const -{ - if( m_pcPelFormat->colorSpace == GRAY ) - return 0; - return CHROMASHIFT( m_uiWidth, m_pcPelFormat->log2ChromaWidth ); -} - -UInt PlaYUVerFrame::getChromaHeight() const -{ - if( m_pcPelFormat->colorSpace == GRAY ) - return 0; - return CHROMASHIFT( m_uiHeight, m_pcPelFormat->log2ChromaHeight ); -} - -UInt PlaYUVerFrame::getChromaLength() const -{ - return getChromaWidth() * getChromaHeight(); -} - -UInt PlaYUVerFrame::getChromaSize() const -{ - return getChromaWidth() * getChromaHeight(); + if( !d->m_bHasRGBPel ) + { + fillRGBBuffer(); + } + return d->m_pcARGB32; } PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos ) { - PlaYUVerPixel PixelValue( m_pcPelFormat->colorSpace, m_uiHalfPelValue, m_uiHalfPelValue, m_uiHalfPelValue ); - for( UInt ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + PlaYUVerPixel PixelValue( d->m_pcPelFormat->colorSpace, d->m_uiHalfPelValue, d->m_uiHalfPelValue, d->m_uiHalfPelValue ); + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - Int ratioH = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - Int ratioW = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - PixelValue.Components()[ch] = m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )]; + Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + PixelValue[ch] = d->m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )]; } return PixelValue; } PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::ColorSpace eColorSpace ) { - PlaYUVerPixel PixelValue( m_pcPelFormat->colorSpace ); - for( UInt ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + PlaYUVerPixel PixelValue( d->m_pcPelFormat->colorSpace ); + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - Int ratioH = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - Int ratioW = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - PixelValue.Components()[ch] = m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )]; + Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + PixelValue[ch] = d->m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )]; } PixelValue = PixelValue.ConvertPixel( eColorSpace ); return PixelValue; @@ -356,41 +459,41 @@ PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::C Void PlaYUVerFrame::setPixelValue( Int xPos, Int yPos, PlaYUVerPixel pixel ) { - for( UInt ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - Int ratioH = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - Int ratioW = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )] = pixel.Components()[ch]; + Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + d->m_pppcInputPel[ch][( yPos >> ratioH )][( xPos >> ratioW )] = pixel.Components()[ch]; } - m_bHasHistogram = false; - m_bHasRGBPel = false; + d->m_bHasHistogram = false; + d->m_bHasRGBPel = false; } Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame ) { - if( m_iPixelFormat != input_frame->getPelFormat() && m_uiWidth == input_frame->getWidth() && m_uiHeight == input_frame->getHeight() ) + if( d->m_iPixelFormat != input_frame->getPelFormat() && d->m_uiWidth == input_frame->getWidth() && d->m_uiHeight == input_frame->getHeight() ) return; - m_bHasRGBPel = false; - m_bHasHistogram = false; - memcpy( *m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); + d->m_bHasRGBPel = false; + d->m_bHasHistogram = false; + memcpy( *d->m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); } Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) { - if( m_iPixelFormat != input_frame->getPelFormat() ) + if( d->m_iPixelFormat != input_frame->getPelFormat() ) return; Pel ***pInput = input_frame->getPelBufferYUV(); - for( UInt ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - Int ratioH = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - Int ratioW = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - for( UInt i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ); i++ ) + Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + for( UInt i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ); i++ ) { - memcpy( m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( m_uiWidth >> ratioW ) * sizeof( Pel ) ); + memcpy( d->m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( d->m_uiWidth >> ratioW ) * sizeof( Pel ) ); } } - m_bHasRGBPel = false; - m_bHasHistogram = false; + d->m_bHasRGBPel = false; + d->m_bHasHistogram = false; } Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) @@ -406,7 +509,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; Pel* pPel; - UInt bytesPixel = ( m_uiBitsPel - 1 ) / 8 + 1; + UInt bytesPixel = ( d->m_uiBitsPel - 1 ) / 8 + 1; Int ratioH, ratioW, step; UInt i, ch; Int startByte = 0; @@ -414,7 +517,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) Int incByte = 1; Int b; - if( m_iEndianness == 0 ) + if( d->m_iEndianness == 0 ) { startByte = bytesPixel - 1; endByte = -1; @@ -424,21 +527,21 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) ppBuff[0] = Buff; for( i = 1; i < MAX_NUMBER_PLANES; i++ ) { - ratioW = i > 1 ? m_pcPelFormat->log2ChromaWidth : 0; - ratioH = i > 1 ? m_pcPelFormat->log2ChromaHeight : 0; - ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ) * bytesPixel; + ratioW = i > 1 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = i > 1 ? d->m_pcPelFormat->log2ChromaHeight : 0; + ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; } - for( ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + for( ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - ratioW = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - step = m_pcPelFormat->comp[ch].step_minus1; + ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + step = d->m_pcPelFormat->comp[ch].step_minus1; - pPel = m_pppcInputPel[ch][0]; - pTmpBuff = ppBuff[m_pcPelFormat->comp[ch].plane] + ( m_pcPelFormat->comp[ch].offset_plus1 - 1 ); + pPel = d->m_pppcInputPel[ch][0]; + pTmpBuff = ppBuff[d->m_pcPelFormat->comp[ch].plane] + ( d->m_pcPelFormat->comp[ch].offset_plus1 - 1 ); - for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) { *pPel = 0; for( b = startByte; b != endByte; b += incByte ) @@ -450,13 +553,13 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) pTmpBuff += step; } } - m_bHasRGBPel = false; - m_bHasHistogram = false; + d->m_bHasRGBPel = false; + d->m_bHasHistogram = false; } Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) { - UInt bytesPixel = ( m_uiBitsPel - 1 ) / 8 + 1; + UInt bytesPixel = ( d->m_uiBitsPel - 1 ) / 8 + 1; Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; Pel* pTmpPel; @@ -467,7 +570,7 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) Int incByte = 1; Int b; - if( m_iEndianness == 0 ) + if( d->m_iEndianness == 0 ) { startByte = bytesPixel - 1; endByte = -1; @@ -477,21 +580,21 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) ppBuff[0] = output_buffer; for( Int i = 1; i < MAX_NUMBER_PLANES; i++ ) { - ratioW = i > 1 ? m_pcPelFormat->log2ChromaWidth : 0; - ratioH = i > 1 ? m_pcPelFormat->log2ChromaHeight : 0; - ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ) * bytesPixel; + ratioW = i > 1 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = i > 1 ? d->m_pcPelFormat->log2ChromaHeight : 0; + ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; } - for( ch = 0; ch < m_pcPelFormat->numberChannels; ch++ ) + for( ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { - ratioW = ch > 0 ? m_pcPelFormat->log2ChromaWidth : 0; - ratioH = ch > 0 ? m_pcPelFormat->log2ChromaHeight : 0; - step = m_pcPelFormat->comp[ch].step_minus1; + ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + step = d->m_pcPelFormat->comp[ch].step_minus1; - pTmpPel = m_pppcInputPel[ch][0]; - pTmpBuff = ppBuff[m_pcPelFormat->comp[ch].plane]; + pTmpPel = d->m_pppcInputPel[ch][0]; + pTmpBuff = ppBuff[d->m_pcPelFormat->comp[ch].plane]; - for( i = 0; i < CHROMASHIFT( m_uiHeight, ratioH ) * CHROMASHIFT( m_uiWidth, ratioW ); i++ ) + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) { for( b = startByte; b != endByte; b += incByte ) { @@ -506,16 +609,23 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) Void PlaYUVerFrame::fillRGBBuffer() { - if( m_bHasRGBPel ) +#define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; +#define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ +iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ +iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); \ +iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); \ +CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) + + if( d->m_bHasRGBPel ) return; Int iR, iG, iB; - Int shiftBits = m_uiBitsPel - 8; - UInt* pARGB = ( UInt* )m_pcARGB32; - if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) + Int shiftBits = d->m_uiBitsPel - 8; + UInt* pARGB = ( UInt* )d->m_pcARGB32; + if( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) { - Pel* pY = m_pppcInputPel[LUMA][0]; + Pel* pY = d->m_pppcInputPel[LUMA][0]; Int iY; - for( UInt i = 0; i < m_uiHeight * m_uiWidth; i++ ) + for( UInt i = 0; i < d->m_uiHeight * d->m_uiWidth; i++ ) { iY = *pY++; iY >>= shiftBits; @@ -525,13 +635,13 @@ Void PlaYUVerFrame::fillRGBBuffer() *pARGB++ = PEL_RGB( iR, iG, iB ); } } - else if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) + else if( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) { - Pel* pR = m_pppcInputPel[COLOR_R][0]; - Pel* pG = m_pppcInputPel[COLOR_G][0]; - Pel* pB = m_pppcInputPel[COLOR_B][0]; + Pel* pR = d->m_pppcInputPel[COLOR_R][0]; + Pel* pG = d->m_pppcInputPel[COLOR_G][0]; + Pel* pB = d->m_pppcInputPel[COLOR_B][0]; - for( UInt i = 0; i < m_uiHeight * m_uiWidth; i++ ) + for( UInt i = 0; i < d->m_uiHeight * d->m_uiWidth; i++ ) { iR = *pR++; iG = *pG++; @@ -539,12 +649,12 @@ Void PlaYUVerFrame::fillRGBBuffer() *pARGB++ = PEL_RGB( ( iR >> shiftBits ), ( iG >> shiftBits ), ( iB >> shiftBits ) ); } } - else if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV ) + else if( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV ) { - Pel* pLineY = m_pppcInputPel[LUMA][0]; - Pel* pLineU = m_pppcInputPel[CHROMA_U][0]; - Pel* pLineV = m_pppcInputPel[CHROMA_V][0]; - UInt uiChromaStride = CHROMASHIFT( m_uiWidth, m_pcPelFormat->log2ChromaWidth ); + Pel* pLineY = d->m_pppcInputPel[LUMA][0]; + Pel* pLineU = d->m_pppcInputPel[CHROMA_U][0]; + Pel* pLineV = d->m_pppcInputPel[CHROMA_V][0]; + UInt uiChromaStride = CHROMASHIFT( d->m_uiWidth, d->m_pcPelFormat->log2ChromaWidth ); Pel* pY; Pel* pU; Pel* pV; @@ -554,21 +664,21 @@ Void PlaYUVerFrame::fillRGBBuffer() UInt y, x; Int i, j; - for( y = 0; y < m_uiHeight >> m_pcPelFormat->log2ChromaHeight; y++ ) + for( y = 0; y < d->m_uiHeight >> d->m_pcPelFormat->log2ChromaHeight; y++ ) { - for( i = 0; i < 1 << m_pcPelFormat->log2ChromaHeight; i++ ) + for( i = 0; i < 1 << d->m_pcPelFormat->log2ChromaHeight; i++ ) { pY = pLineY; pU = pLineU; pV = pLineV; pARGB = pARGBLine; - for( x = 0; x < m_uiWidth >> m_pcPelFormat->log2ChromaWidth; x++ ) + for( x = 0; x < d->m_uiWidth >> d->m_pcPelFormat->log2ChromaWidth; x++ ) { iU = *pU++; iU >>= shiftBits; iV = *pV++; iV >>= shiftBits; - for( j = 0; j < ( 1 << m_pcPelFormat->log2ChromaWidth ); j++ ) + for( j = 0; j < ( 1 << d->m_pcPelFormat->log2ChromaWidth ); j++ ) { iY = *pY++; iY >>= shiftBits; @@ -576,14 +686,14 @@ Void PlaYUVerFrame::fillRGBBuffer() *pARGB++ = PEL_RGB( iR, iG, iB ); } } - pLineY += m_uiWidth; - pARGBLine += m_uiWidth; + pLineY += d->m_uiWidth; + pARGBLine += d->m_uiWidth; } pLineU += uiChromaStride; pLineV += uiChromaStride; } } - m_bHasRGBPel = true; + d->m_bHasRGBPel = true; } /** @@ -592,41 +702,40 @@ Void PlaYUVerFrame::fillRGBBuffer() Void PlaYUVerFrame::calcHistogram() { - if( m_bHasHistogram ) + if( d->m_bHasHistogram ) return; - if( !m_puiHistogram ) + if( !d->m_puiHistogram ) { - //m_puiHistogram = new UInt[m_uiHistoSegments * histoChannels]; - getMem1D( &( m_puiHistogram ), m_uiHistoSegments * m_uiHistoChannels ); - if( !m_puiHistogram ) + getMem1D( &( d->m_puiHistogram ), d->m_uiHistoSegments * d->m_uiHistoChannels ); + if( !d->m_puiHistogram ) { return; } } - m_bRunningFlag = true; + d->m_bRunningFlag = true; - xMemSet( UInt, m_uiHistoSegments * m_uiHistoChannels, m_puiHistogram ); + xMemSet( UInt, d->m_uiHistoSegments * d->m_uiHistoChannels, d->m_puiHistogram ); UInt i, j; - UInt numberChannels = m_pcPelFormat->numberChannels; - Int colorSpace = m_pcPelFormat->colorSpace; + UInt numberChannels = d->m_pcPelFormat->numberChannels; + Int colorSpace = d->m_pcPelFormat->colorSpace; if( colorSpace == PlaYUVerPixel::COLOR_YUV ) { const Pel *data[3]; - data[LUMA] = m_pppcInputPel[LUMA][0]; - data[CHROMA_U] = m_pppcInputPel[CHROMA_U][0]; - data[CHROMA_V] = m_pppcInputPel[CHROMA_V][0]; - for( i = 0; i < m_uiHeight * m_uiWidth && m_bRunningFlag; i++ ) + data[LUMA] = d->m_pppcInputPel[LUMA][0]; + data[CHROMA_U] = d->m_pppcInputPel[CHROMA_U][0]; + data[CHROMA_V] = d->m_pppcInputPel[CHROMA_V][0]; + for( i = 0; i < d->m_uiHeight * d->m_uiWidth && d->m_bRunningFlag; i++ ) { - m_puiHistogram[*( data[LUMA] ) + LUMA * m_uiHistoSegments]++; + d->m_puiHistogram[*( data[LUMA] ) + LUMA * d->m_uiHistoSegments]++; data[LUMA] += 1; } - for( i = 0; ( i < getChromaSize() ) && m_bRunningFlag; i++ ) + for( i = 0; ( i < getChromaLength() ) && d->m_bRunningFlag; i++ ) { for( j = 1; j < numberChannels; j++ ) { - m_puiHistogram[*( data[j] ) + j * m_uiHistoSegments]++; + d->m_puiHistogram[*( data[j] ) + j * d->m_uiHistoSegments]++; data[j] += 1; } } @@ -635,40 +744,40 @@ Void PlaYUVerFrame::calcHistogram() { const Pel* data[3]; Pel luma; - data[COLOR_R] = m_pppcInputPel[COLOR_R][0]; - data[COLOR_G] = m_pppcInputPel[COLOR_G][0]; - data[COLOR_B] = m_pppcInputPel[COLOR_B][0]; + data[COLOR_R] = d->m_pppcInputPel[COLOR_R][0]; + data[COLOR_G] = d->m_pppcInputPel[COLOR_G][0]; + data[COLOR_B] = d->m_pppcInputPel[COLOR_B][0]; - for( i = 0; ( i < m_uiHeight * m_uiWidth ) && m_bRunningFlag; i++ ) + for( i = 0; ( i < d->m_uiHeight * d->m_uiWidth ) && d->m_bRunningFlag; i++ ) { for( j = 0; j < numberChannels; j++ ) { - m_puiHistogram[*( data[j] ) + j * m_uiHistoSegments]++; + d->m_puiHistogram[*( data[j] ) + j * d->m_uiHistoSegments]++; } if( ( colorSpace == PlaYUVerPixel::COLOR_RGB || colorSpace == PlaYUVerPixel::COLOR_ARGB ) ) { PlaYUVerPixel currPixel( colorSpace, *( data[COLOR_R] ), *( data[COLOR_G] ), *( data[COLOR_B] ) ); luma = currPixel.ConvertPixel( PlaYUVerPixel::COLOR_YUV ).Y(); - m_puiHistogram[luma + j * m_uiHistoSegments]++; + d->m_puiHistogram[luma + j * d->m_uiHistoSegments]++; } for( j = 0; j < numberChannels; j++ ) data[j] += 1; } } - m_bHasHistogram = true; - m_bRunningFlag = false; + d->m_bHasHistogram = true; + d->m_bRunningFlag = false; } Int PlaYUVerFrame::getHistogramSegment() { - return m_uiHistoSegments; + return d->m_uiHistoSegments; } -Int PlaYUVerFrame::getRealHistoChannel( Int channel ) +Int getRealHistoChannel( Int colorSpace, Int channel ) { Int histoChannel; - switch( getColorSpace() ) + switch( colorSpace ) { case PlaYUVerPixel::COLOR_GRAY: if( channel != LUMA ) @@ -734,23 +843,23 @@ UInt PlaYUVerFrame::getCount( Int channel, UInt start, UInt end ) Int indexStart; UInt count = 0; - if( !m_bHasHistogram || start < 0 || end > m_uiHistoSegments - 1 || start > end ) + if( !d->m_bHasHistogram || start < 0 || end > d->m_uiHistoSegments - 1 || start > end ) { return 0.0; } - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; for( i = start; i <= end; i++ ) { - count += m_puiHistogram[indexStart + i]; + count += d->m_puiHistogram[indexStart + i]; } return count; } @@ -762,23 +871,23 @@ Double PlaYUVerFrame::getMean( Int channel, UInt start, UInt end ) Double mean = 0.0; Double count; - if( !m_bHasHistogram || start < 0 || end > m_uiHistoSegments - 1 || start > end ) + if( !d->m_bHasHistogram || start < 0 || end > d->m_uiHistoSegments - 1 || start > end ) { return 0.0; } - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0.0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; for( UInt i = start; i <= end; i++ ) { - mean += i * m_puiHistogram[indexStart + i]; + mean += i * d->m_puiHistogram[indexStart + i]; } count = getCount( channel, start, end ); @@ -798,25 +907,25 @@ Int PlaYUVerFrame::getMedian( Int channel, UInt start, UInt end ) Double sum = 0.0; Double count; - if( !m_bHasHistogram || start < 0 || end > m_uiHistoSegments - 1 || start > end ) + if( !d->m_bHasHistogram || start < 0 || end > d->m_uiHistoSegments - 1 || start > end ) { return 0; } - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; count = getCount( channel, start, end ); for( UInt i = start; i <= end; i++ ) { - sum += m_puiHistogram[indexStart + i]; + sum += d->m_puiHistogram[indexStart + i]; if( sum * 2 > count ) return i; } @@ -832,19 +941,19 @@ Double PlaYUVerFrame::getStdDev( Int channel, UInt start, UInt end ) Double count; Double mean; - if( !m_bHasHistogram || start < 0 || end > m_uiHistoSegments - 1 || start > end ) + if( !d->m_bHasHistogram || start < 0 || end > d->m_uiHistoSegments - 1 || start > end ) { return 0.0; } - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0.0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; mean = getMean( channel, start, end ); count = getCount( channel, start, end ); @@ -855,7 +964,7 @@ Double PlaYUVerFrame::getStdDev( Int channel, UInt start, UInt end ) for ( i = start ; i <= end ; i++ ) { - dev += ( i - mean ) * ( i - mean ) * m_puiHistogram[indexStart +i]; + dev += ( i - mean ) * ( i - mean ) * d->m_puiHistogram[indexStart +i]; } return sqrt( dev / count ); @@ -864,7 +973,7 @@ Double PlaYUVerFrame::getStdDev( Int channel, UInt start, UInt end ) for( UInt i = start; i <= end; i++ ) { - dev += ( i * i ) * m_puiHistogram[indexStart + i]; + dev += ( i * i ) * d->m_puiHistogram[indexStart + i]; } return sqrt( ( dev - count * mean * mean ) / ( count - 1 ) ); @@ -877,19 +986,19 @@ Double PlaYUVerFrame::getHistogramValue( Int channel, UInt bin ) Int histoChannel; Int indexStart; - if( !m_bHasHistogram || bin < 0 || bin > m_uiHistoSegments - 1 ) + if( !d->m_bHasHistogram || bin < 0 || bin > d->m_uiHistoSegments - 1 ) return 0.0; - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0.0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; - value = m_puiHistogram[indexStart + bin]; + value = d->m_puiHistogram[indexStart + bin]; return value; } @@ -901,23 +1010,23 @@ Double PlaYUVerFrame::getMaximum( Int channel ) Int histoChannel; Int indexStart; - if( !m_bHasHistogram ) + if( !d->m_bHasHistogram ) return 0.0; - histoChannel = getRealHistoChannel( channel ); + histoChannel = getRealHistoChannel( getColorSpace(), channel ); if( histoChannel == -1 ) { return 0.0; } - indexStart = histoChannel * m_uiHistoSegments; + indexStart = histoChannel * d->m_uiHistoSegments; - for( UInt x = 0; x < m_uiHistoSegments; x++ ) + for( UInt x = 0; x < d->m_uiHistoSegments; x++ ) { - if( m_puiHistogram[indexStart + x] > max ) + if( d->m_puiHistogram[indexStart + x] > max ) { - max = m_puiHistogram[indexStart + x]; + max = d->m_puiHistogram[indexStart + x]; } } @@ -933,18 +1042,18 @@ Double PlaYUVerFrame::getMaximum( Int channel ) cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) { #ifdef USE_OPENCV - if( convertToGray && !( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) ) + if( convertToGray && !( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) ) { return NULL; } - Int cvType = CV_MAKETYPE( CV_8U, convertToGray ? 1 : m_pcPelFormat->numberChannels ); - cv::Mat *pcCvFrame = new cv::Mat( m_uiHeight, m_uiWidth, cvType ); + Int cvType = CV_MAKETYPE( CV_8U, convertToGray ? 1 : d->m_pcPelFormat->numberChannels ); + cv::Mat *pcCvFrame = new cv::Mat( d->m_uiHeight, d->m_uiWidth, cvType ); UChar* pCvPel = pcCvFrame->data; - if( !convertToGray && ( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) ) + if( !convertToGray && ( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) ) { fillRGBBuffer(); - UChar* pARGB = m_pcARGB32; - for( UInt i = 0; i < m_uiWidth * m_uiHeight; i++ ) + UChar* pARGB = d->m_pcARGB32; + for( UInt i = 0; i < d->m_uiWidth * d->m_uiHeight; i++ ) { *pCvPel++ = *pARGB++; *pCvPel++ = *pARGB++; @@ -952,10 +1061,10 @@ cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) pARGB++; } } - else if( convertToGray || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) + else if( convertToGray || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) { - Pel* pPel = m_pppcInputPel[LUMA][0]; - for( UInt i = 0; i < m_uiWidth * m_uiHeight; i++ ) + Pel* pPel = d->m_pppcInputPel[LUMA][0]; + for( UInt i = 0; i < d->m_uiWidth * d->m_uiHeight; i++ ) { *pCvPel++ = *pPel++; } @@ -975,35 +1084,35 @@ cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) { #ifdef USE_OPENCV - if( !m_bInit ) + if( !d->m_bInit ) { - if( m_iPixelFormat == NO_FMT ) + if( d->m_iPixelFormat == NO_FMT ) { switch( pcCvFrame->channels() ) { case 1: - m_iPixelFormat = findPixelFormat( "GRAY" ); + d->m_iPixelFormat = findPixelFormat( "GRAY" ); break; case 3: - m_iPixelFormat = findPixelFormat( "BGR24" ); + d->m_iPixelFormat = findPixelFormat( "BGR24" ); break; default: return; } } - init( pcCvFrame->cols, pcCvFrame->rows, m_iPixelFormat, 8, -1 ); + d->init( pcCvFrame->cols, pcCvFrame->rows, d->m_iPixelFormat, 8, -1 ); } - m_bHasRGBPel = false; - m_bHasHistogram = false; + d->m_bHasRGBPel = false; + d->m_bHasHistogram = false; UChar* pCvPel = pcCvFrame->data; - if( m_iPixelFormat != GRAY ) + if( d->m_iPixelFormat != GRAY ) { - Pel* pInputPelR = m_pppcInputPel[COLOR_R][0]; - Pel* pInputPelG = m_pppcInputPel[COLOR_G][0]; - Pel* pInputPelB = m_pppcInputPel[COLOR_B][0]; - for( UInt i = 0; i < m_uiHeight * m_uiWidth; i++ ) + Pel* pInputPelR = d->m_pppcInputPel[COLOR_R][0]; + Pel* pInputPelG = d->m_pppcInputPel[COLOR_G][0]; + Pel* pInputPelB = d->m_pppcInputPel[COLOR_B][0]; + for( UInt i = 0; i < d->m_uiHeight * d->m_uiWidth; i++ ) { *pInputPelB++ = *pCvPel++; *pInputPelG++ = *pCvPel++; @@ -1014,8 +1123,8 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) } else { - Pel* pPel = m_pppcInputPel[LUMA][0]; - for( UInt i = 0; i < m_uiWidth * m_uiHeight; i++ ) + Pel* pPel = d->m_pppcInputPel[LUMA][0]; + for( UInt i = 0; i < d->m_uiWidth * d->m_uiHeight; i++ ) { *pPel++ = *pCvPel++; } @@ -1161,11 +1270,11 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) Double dSSIM = 1; if( component == LUMA ) { - dSSIM = compute_ssim( m_pppcInputPel[component], Org->getPelBufferYUV()[component], m_uiWidth, m_uiHeight, 8, 8, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], d->m_uiWidth, d->m_uiHeight, 8, 8, 255, 8 ); } else { - dSSIM = compute_ssim( m_pppcInputPel[component], Org->getPelBufferYUV()[component], getChromaWidth(), getChromaHeight(), 4, 4, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], getChromaWidth(), getChromaHeight(), 4, 4, 255, 8 ); } return dSSIM; } diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index cc49ed6..e94d9c4 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -41,8 +41,9 @@ class Mat; struct PlaYUVerPixFmtDescriptor; +struct PlaYUVerFramePrivate; -#define CHROMASHIFT( SIZE, SHIFT ) UInt( -( ( - ( Int( SIZE ) ) ) >> SHIFT ) ) +#define CHROMASHIFT( SIZE, SHIFT ) UInt( -( ( - ( Int( SIZE ) ) ) >> ( SHIFT ) ) ) /** * \class PlaYUVerFrame @@ -98,13 +99,6 @@ public: static std::vector supportedPixelFormatListNames( Int colorSpace ); static Int findPixelFormat( String name ); - /** - * Get number of bytes per frame of a specific - * pixel format - * @return number of bytes per frame - */ - static UInt64 getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ); - /** * Creates a new frame using the following configuration * @@ -141,53 +135,46 @@ public: Void clear(); - UInt getWidth() const - { - return m_uiWidth; - } - UInt getHeight() const - { - return m_uiHeight; - } - Int getPelFormat() const - { - return m_iPixelFormat; - } - UInt getBitsPel() const - { - return m_uiBitsPel; - } - Int getEndianness() const - { - return m_iEndianness; - } - Pel*** getPelBufferYUV() const - { - return m_pppcInputPel; - } - Pel*** getPelBufferYUV() - { - m_bHasHistogram = false; - m_bHasRGBPel = false; - return m_pppcInputPel; - } + Bool haveSameFmt( PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; - UChar* getRGBBuffer() const - { - if( m_bHasRGBPel ) - { - return m_pcARGB32; - } - return NULL; - } - UChar* getRGBBuffer() - { - if( !m_bHasRGBPel ) - { - fillRGBBuffer(); - } - return m_pcARGB32; - } + /** + * Get pixel format information + * @return pixel format index + */ + Int getPelFormat() const; + + /** + * @return pixel format name + */ + String getPelFmtName(); + + /** + * @return get color space index + * @ + */ + Int getColorSpace() const; + + UInt getNumberChannels() const; + + /** + * Get width/height of the frame or the entire + * number of pixels + * @param channel/component + * @return number of pixels + */ + UInt getWidth( Int channel = 0 ) const; + UInt getHeight( Int channel = 0 ) const; + UInt getPixels( Int channel = 0 ) const; + + UInt8 getChromaWidthRatio() const; + UInt8 getChromaHeightRatio() const; + UInt getChromaWidth() const; + UInt getChromaHeight() const; + UInt getChromaLength() const; + UInt getChromaSize() const; + + UInt getBitsPel() const; + Int getEndianness() const; /** * Get number of bytes per frame of an existing frame @@ -195,16 +182,17 @@ public: */ UInt64 getBytesPerFrame(); - Int getColorSpace() const; - UInt getNumberChannels() const; + /** + * Get number of bytes per frame of a specific + * pixel format + * @return number of bytes per frame + */ + static UInt64 getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ); - UInt getPixels() const; - UInt8 getChromaWidthRatio() const; - UInt8 getChromaHeightRatio() const; - UInt getChromaWidth() const; - UInt getChromaHeight() const; - UInt getChromaLength() const; - UInt getChromaSize() const; + Pel*** getPelBufferYUV() const; + Pel*** getPelBufferYUV(); + UChar* getRGBBuffer() const; + UChar* getRGBBuffer(); PlaYUVerPixel getPixelValue( Int xPos, Int yPos ); PlaYUVerPixel getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::ColorSpace eColorSpace ); @@ -219,10 +207,6 @@ public: Void fillRGBBuffer(); - Bool haveSameFmt( PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; - - String getPelFmtName(); - /** * Histogram */ @@ -236,15 +220,6 @@ public: Double getMaximum( Int channel ); Int getHistogramSegment(); - Void setRunningFlag( Bool bFlag ) - { - m_bRunningFlag = bFlag; - } - Bool getHasHistogram() - { - return m_bHasHistogram; - } - /** * Interface with OpenCV lib */ @@ -288,53 +263,7 @@ public: //! @} private: - - Bool m_bInit; - - //! Struct with the pixel format description. - PlaYUVerPixFmtDescriptor* m_pcPelFormat; - String m_cPelFmtName; - - UInt m_uiWidth; //!< Width of the frame - UInt m_uiHeight; //!< Height of the frame - Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) - Int m_iNumberChannels; //!< Number of channels - UInt m_uiBitsPel; //!< Bits per pixel/channel - Int m_iEndianness; //!< Endiannes of bytes - UInt m_uiHalfPelValue; //!< Bits per pixel/channel - - Pel*** m_pppcInputPel; - - Bool m_bHasRGBPel; //!< Flag indicating that the ARGB buffer was computed - UChar* m_pcARGB32; //!< Buffer with the ARGB pixels used in Qt libs - - /** The histogram data.*/ - UInt* m_puiHistogram; - - /** If the image is RGB and calcLuma is true, we have 1 more channel */ - UInt m_uiHistoChannels; - - /** Numbers of histogram segments depending of image bytes depth*/ - UInt m_uiHistoSegments; - - /** Used to stop thread during calculations.*/ - Bool m_bRunningFlag; - - Int getRealHistoChannel( Int channel ); - - Bool m_bHasHistogram; - - /** - * Common constructor function of a frame - * - * @param width width of the frame - * @param height height of the frame - * @param pel_format pixel format index (always use PixelFormats enum) - * - */ - Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ); - - Void FrametoRGB8Pixfc(); + PlaYUVerFramePrivate* d; }; #endif // __PLAYUVERFRAME_H__ diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index dc91280..f4b4e84 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -28,8 +28,8 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" - -PlaYUVerPixel::PlaYUVerPixel() +PlaYUVerPixel::PlaYUVerPixel() : + m_iColorSpace( COLOR_INVALID ) { m_iColorSpace = COLOR_INVALID; PixelComponents[0] = 0; @@ -38,7 +38,7 @@ PlaYUVerPixel::PlaYUVerPixel() PixelComponents[3] = 0; } -PlaYUVerPixel::PlaYUVerPixel( Int ColorSpace ) +PlaYUVerPixel::PlaYUVerPixel( const Int& ColorSpace ) { m_iColorSpace = ColorSpace == COLOR_GRAY ? COLOR_YUV : ColorSpace; PixelComponents[0] = 0; @@ -47,7 +47,7 @@ PlaYUVerPixel::PlaYUVerPixel( Int ColorSpace ) PixelComponents[3] = 0; } -PlaYUVerPixel::PlaYUVerPixel( Int ColorSpace, Pel c0, Pel c1, Pel c2 ) +PlaYUVerPixel::PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ) { m_iColorSpace = ColorSpace == COLOR_GRAY ? COLOR_YUV : ColorSpace; PixelComponents[0] = c0; @@ -56,6 +56,68 @@ PlaYUVerPixel::PlaYUVerPixel( Int ColorSpace, Pel c0, Pel c1, Pel c2 ) PixelComponents[3] = 0; } +PlaYUVerPixel::~PlaYUVerPixel() +{ +} + +Int PlaYUVerPixel::ColorSpaceType() +{ + return m_iColorSpace; +} + +Pel* PlaYUVerPixel::Components() +{ + return PixelComponents; +} + +Pel PlaYUVerPixel::Y() const +{ + return PixelComponents[0]; +} +Pel PlaYUVerPixel::Cb() const +{ + return PixelComponents[1]; +} +Pel PlaYUVerPixel::Cr() const +{ + return PixelComponents[2]; +} + + +Pel& PlaYUVerPixel::Y() +{ + return PixelComponents[0]; +} +Pel& PlaYUVerPixel::Cb() +{ + return PixelComponents[1]; +} +Pel& PlaYUVerPixel::Cr() +{ + return PixelComponents[2]; +} +Pel& PlaYUVerPixel::R() +{ + return PixelComponents[0]; +} +Pel& PlaYUVerPixel::G() +{ + return PixelComponents[1]; +} +Pel& PlaYUVerPixel::B() +{ + return PixelComponents[2]; +} + +Pel PlaYUVerPixel::operator[]( const Int& channel ) const +{ + return PixelComponents[channel]; +} +Pel& PlaYUVerPixel::operator[]( const Int& channel ) +{ + return PixelComponents[channel]; +} + PlaYUVerPixel PlaYUVerPixel::operator+ ( const PlaYUVerPixel& in ) { PlaYUVerPixel out( m_iColorSpace, Y() + in.Y(), Cb() + in.Cb(), Cr() + in.Cr() ); @@ -68,9 +130,9 @@ PlaYUVerPixel PlaYUVerPixel::operator- ( const PlaYUVerPixel& in ) return out; } -PlaYUVerPixel PlaYUVerPixel::operator* ( const Double& d ) +PlaYUVerPixel PlaYUVerPixel::operator* ( const Double& op ) { - PlaYUVerPixel out( m_iColorSpace, Y() * d, Cb() * d, Cr() * d ); + PlaYUVerPixel out( m_iColorSpace, Y() * op, Cb() * op, Cr() * op ); return out; } @@ -84,7 +146,7 @@ PlaYUVerPixel PlaYUVerPixel::ConvertPixel( ColorSpace eOutputSpace ) if( eOutputSpace == COLOR_RGB ) { - YUV2RGB( Y(), Cb(), Cr(), outA, outB, outC ); + YuvToRgb( Y(), Cb(), Cr(), outA, outB, outC ); outPixel.R() = outA; outPixel.G() = outB; outPixel.B() = outC; diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 34f43bf..6461377 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -33,95 +33,72 @@ #include "PlaYUVerDefs.h" -#define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; -#define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ - iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ - iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); \ - iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); \ - CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) +static inline Void YuvToRgb( const Int &iY, const Int &iU, const Int &iV, Int &iR, Int &iG, Int &iB ) +{ + iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); + iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); + iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); + iR = iR < 0 ? 0 : iR > 255 ? 255 : iR; + iG = iG < 0 ? 0 : iG > 255 ? 255 : iG; + iB = iB < 0 ? 0 : iB > 255 ? 255 : iB; +} - -static inline Void rgbToYuv( Int iR, Int iG, Int iB, Int &iY, Int &iU, Int &iV ) +static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int &iY, Int &iU, Int &iV ) { iY = ( 299 * iR + 587 * iG + 114 * iB + 500 ) / 1000; iU = ( 1000 * ( iB - iY ) + 226816 ) / 1772; iV = ( 1000 * ( iR - iY ) + 179456 ) / 1402; } -#define MAX_NUMBER_COMPONENTS 4 - /** * \class PlaYUVerPixel * \ingroup PlaYUVerLib PlaYUVerLib_Frame - * \brief Pel handling class + * \brief Pixel handling class */ class PlaYUVerPixel { public: - /** ColorSpace Enum + + static const UInt MAX_NUMBER_COMPONENTS = 5; + + /** ColorSpace list * List of supported color spaces */ enum ColorSpace { - COLOR_INVALID = -1, //!< Invalid - COLOR_YUV = 0, //!< YUV - COLOR_RGB = 1, //!< RGB - COLOR_GRAY = 2, //!< Grayscale - COLOR_ARGB = 3, //!< RGB + Alpha + COLOR_INVALID = -1, //!< Invalid + COLOR_YUV = 0, //!< YUV + COLOR_RGB = 1, //!< RGB + COLOR_GRAY = 2, //!< Grayscale + COLOR_ARGB = 3, //!< RGB + Alpha + COLOR_MAX = 255, //!< Accouunt for future formats }; PlaYUVerPixel(); - PlaYUVerPixel( Int ColorSpace ); - PlaYUVerPixel( Int ColorSpace, Pel c0, Pel c1, Pel c2 ); + PlaYUVerPixel( const Int& ColorSpace ); + PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ); + ~PlaYUVerPixel(); - Int ColorSpaceType() - { - return m_iColorSpace; - } - Pel* Components() - { - return PixelComponents; - } - Pel Y() const - { - return PixelComponents[0]; - } - Pel Cb() const - { - return PixelComponents[1]; - } - Pel Cr() const - { - return PixelComponents[2]; - } - Pel& Y() - { - return PixelComponents[0]; - } - Pel& Cb() - { - return PixelComponents[1]; - } - Pel& Cr() - { - return PixelComponents[2]; - } - Pel& R() - { - return PixelComponents[0]; - } - Pel& G() - { - return PixelComponents[1]; - } - Pel& B() - { - return PixelComponents[2]; - } - Pel& A() - { - return PixelComponents[3]; - } + Int ColorSpaceType(); + + Pel* Components(); + + Pel Y() const; + Pel Cb() const; + Pel Cr() const; + Pel R() const; + Pel G() const; + Pel B() const; + + Pel& Y(); + Pel& Cb(); + Pel& Cr(); + Pel& R(); + Pel& G(); + Pel& B(); + + Pel operator[] ( const Int& channel ) const; + Pel& operator[] ( const Int& channel ); PlaYUVerPixel operator+ ( const PlaYUVerPixel& ); PlaYUVerPixel operator- ( const PlaYUVerPixel& ); @@ -138,7 +115,6 @@ public: private: Int m_iColorSpace; Pel PixelComponents[MAX_NUMBER_COMPONENTS]; - }; #endif // __PLAYUVERPIXEL_H__ diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index d9b20d3..a714ad6 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -338,7 +338,7 @@ Int PlaYUVerTools::QualityOperation() const char *pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); PlaYUVerFrame* apcCurrFrame[MAX_NUMBER_INPUTS]; Bool abEOF[MAX_NUMBER_INPUTS]; - Double adAverageQuality[MAX_NUMBER_INPUTS - 1][MAX_NUMBER_COMPONENTS]; + Double adAverageQuality[MAX_NUMBER_INPUTS - 1][m_uiNumberOfComponents]; Double dQuality; String metric_fmt = " "; From e67e964790c0020a525562eb6d7d6ff5ce8546ab Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 1 May 2016 17:26:15 +0100 Subject: [PATCH 046/127] remove static build as default --- CMakeLists.txt | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 13a3162..07f5e04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,10 +23,11 @@ set( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLA OPTION( PLAYUVER_BUILD_APP "Build GUI Application" ON ) OPTION( PLAYUVER_BUILD_TOOLS "Build Command Line Application" ON ) OPTION( PLAYUVER_BUILD_EXAMPLES "Build Examples" OFF ) +OPTION( PLAYUVER_BUILD_DOC "Build Documentation" OFF ) OPTION( USE_SSE "Build with SSE support" OFF ) OPTION( USE_FERVOR "Add Fervor support" OFF ) OPTION( USE_WERROR "Warnings as errors" OFF ) -OPTION( USE_STATIC "Use static libs" ON ) +OPTION( USE_STATIC "Use static libs" OFF ) OPTION( USE_QT4 "Build with Qt4" OFF ) OPTION( USE_QTDBUS "Build with QtDBus" ON ) OPTION( USE_DYNLOAD "Use dynamic load of modules" ON ) @@ -84,6 +85,14 @@ SET( CMAKE_CXX_FLAGS "" ) # Dependencies ###################################################################################### + +OPTION( USE_OPENCV "Add OpenCV support" ON ) +find_package(Doxygen) +IF(DOXYGEN_FOUND) + SET( PLAYUVER_BUILD_DOC ON ) +ENDIF(DOXYGEN_FOUND) +SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) + OPTION( USE_OPENCV "Add OpenCV support" ON ) IF( USE_OPENCV ) FIND_PACKAGE( OpenCV ) @@ -142,6 +151,14 @@ IF( ${PLAYUVER_BUILD_APP} ) ADD_SUBDIRECTORY( app ) ENDIF() +# add a target to generate API documentation with Doxygen +# IF(PLAYUVER_BUILD_DOC) +# configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) +# add_custom_target(doc ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile +# WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} +# COMMENT "Generating API documentation with Doxygen" VERBATIM ) +# ENDIF(PLAYUVER_BUILD_DOC) + ###################################################################################### # Final information dump From c0eb9a80c7a50bd24c9323688653364f30b1ac45 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 1 May 2016 17:40:15 +0100 Subject: [PATCH 047/127] Add some comments to PlaYUVerFrame methods --- lib/PlaYUVerFrame.h | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index e94d9c4..d10a883 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -157,13 +157,22 @@ public: UInt getNumberChannels() const; /** - * Get width/height of the frame or the entire - * number of pixels + * Get width of the frame * @param channel/component * @return number of pixels */ UInt getWidth( Int channel = 0 ) const; + /** + * Get height of the frame + * @param channel/component + * @return number of pixels + */ UInt getHeight( Int channel = 0 ) const; + /** + * Get number of pixels of the frame + * @param channel/component + * @return number of pixels + */ UInt getPixels( Int channel = 0 ) const; UInt8 getChromaWidthRatio() const; From faee406a392371d24dea169b077ba6bd9dfe2701 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 1 May 2016 17:41:00 +0100 Subject: [PATCH 048/127] Rename PlaYUVerProgramOptions -> PlaYUVerOptions --- app/ModulesHandleOptDialog.cpp | 4 +++- lib/CMakeLists.txt | 8 ++++---- lib/PlaYUVerCmdParser.h | 2 +- lib/PlaYUVerModuleIf.h | 3 +-- lib/{PlaYUVerProgramOptions.cpp => PlaYUVerOptions.cpp} | 2 +- lib/{PlaYUVerProgramOptions.h => PlaYUVerOptions.h} | 2 +- 6 files changed, 11 insertions(+), 10 deletions(-) rename lib/{PlaYUVerProgramOptions.cpp => PlaYUVerOptions.cpp} (99%) rename lib/{PlaYUVerProgramOptions.h => PlaYUVerOptions.h} (99%) diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 43ebe8e..ac8bdd4 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -23,13 +23,15 @@ */ #include "ModulesHandleOptDialog.h" -#include "lib/PlaYUVerProgramOptions.h" + #include #include #include #include #include +#include "lib/PlaYUVerOptions.h" + class OpionConfiguration: public QWidget { diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 2d569ae..18a34e4 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -6,17 +6,16 @@ INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ) set(PlaYUVer_Lib_SRCS # Frame - PlaYUVerFrame.cpp PlaYUVerPixel.cpp + PlaYUVerFrame.cpp PlaYUVerFramePixelFormats.cpp - # PlaYUVerFrameStats.cpp # Stream PlaYUVerStream.cpp StreamHandlerRaw.cpp StreamHandlerPortableMap.cpp # Command Parser + PlaYUVerOptions.cpp PlaYUVerCmdParser.cpp - PlaYUVerProgramOptions.cpp ) IF( USE_FFMPEG ) @@ -30,9 +29,10 @@ ENDIF() set(PlaYUVer_Lib_HEADERS PlaYUVerDefs.h - PlaYUVerProgramOptions.h + PlaYUVerPixel.h PlaYUVerFrame.h PlaYUVerStream.h + PlaYUVerOptions.h PlaYUVerModuleIf.h ) diff --git a/lib/PlaYUVerCmdParser.h b/lib/PlaYUVerCmdParser.h index 95f21d6..3b12747 100644 --- a/lib/PlaYUVerCmdParser.h +++ b/lib/PlaYUVerCmdParser.h @@ -23,7 +23,7 @@ */ #include "PlaYUVerDefs.h" -#include "PlaYUVerProgramOptions.h" +#include "PlaYUVerOptions.h" #ifndef __PLAYUVERCMDPARSER_H__ #define __PLAYUVERCMDPARSER_H__ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index b7cf31f..cad1f7f 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -27,8 +27,7 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerFrame.h" -#include "PlaYUVerStream.h" -#include "PlaYUVerProgramOptions.h" +#include "PlaYUVerOptions.h" #include diff --git a/lib/PlaYUVerProgramOptions.cpp b/lib/PlaYUVerOptions.cpp similarity index 99% rename from lib/PlaYUVerProgramOptions.cpp rename to lib/PlaYUVerOptions.cpp index 436b1bb..d134be3 100644 --- a/lib/PlaYUVerProgramOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -32,7 +32,7 @@ */ /** - * \file ProgramOptions.cpp + * \file PlaYUVerOptions.cpp * \brief Input args handler */ diff --git a/lib/PlaYUVerProgramOptions.h b/lib/PlaYUVerOptions.h similarity index 99% rename from lib/PlaYUVerProgramOptions.h rename to lib/PlaYUVerOptions.h index d1bcd8a..b686a96 100644 --- a/lib/PlaYUVerProgramOptions.h +++ b/lib/PlaYUVerOptions.h @@ -32,7 +32,7 @@ */ /** - * \file ProgramOptions.h + * \file PlaYUVerOptions.h * \brief Input args handler */ From 816dcc345f81346432825aaa22ca733fc5b212a5 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 1 May 2016 20:02:29 +0100 Subject: [PATCH 049/127] start port the opt parser --- app/PlaYUVerApp.cpp | 2 +- lib/CMakeLists.txt | 2 +- lib/PlaYUVerCmdParser.cpp | 140 ---------- lib/PlaYUVerCmdParser.h | 56 ---- lib/PlaYUVerModuleIf.h | 2 +- lib/PlaYUVerOptions.cpp | 460 ++++++++++++++++++++++++++++--- lib/PlaYUVerOptions.h | 353 +++++------------------- tools/PlaYUVerToolsCmdParser.cpp | 80 +----- tools/PlaYUVerToolsCmdParser.h | 11 +- 9 files changed, 510 insertions(+), 596 deletions(-) delete mode 100644 lib/PlaYUVerCmdParser.cpp delete mode 100644 lib/PlaYUVerCmdParser.h diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index e980754..11ee89a 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -34,7 +34,7 @@ #ifdef USE_FERVOR #include "fvupdater.h" #endif -#include "lib/PlaYUVerCmdParser.h" +#include "lib/PlaYUVerOptions.h" #include "PlaYUVerSubWindowHandle.h" #include "AboutDialog.h" #include "SubWindowAbstract.h" diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 18a34e4..32da862 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -15,7 +15,7 @@ set(PlaYUVer_Lib_SRCS StreamHandlerPortableMap.cpp # Command Parser PlaYUVerOptions.cpp - PlaYUVerCmdParser.cpp +# PlaYUVerCmdParser.cpp ) IF( USE_FFMPEG ) diff --git a/lib/PlaYUVerCmdParser.cpp b/lib/PlaYUVerCmdParser.cpp deleted file mode 100644 index 07e5172..0000000 --- a/lib/PlaYUVerCmdParser.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) - * Joao Carreira (jfmcarreira@gmail.com) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -/** - * \file PlaYUVerCmdParser.cpp - * \brief Command parser - */ - -#include "config.h" -#include -#include -#include -#include -#include "PlaYUVerCmdParser.h" -#include "PlaYUVerFrame.h" - - -PlaYUVerCmdParser::PlaYUVerCmdParser() -{ - Opts().addOptions()/**/ - ( "help", "produce help message" )/**/ - ( "version", "show version and exit" )/**/ - ( "pel_fmts", "list pixel formats" ) /**/ - ( "quality_metrics", "list supported quality metrics" )/**/ - ( "module_list", "list supported modules" ) /**/ - ( "module_list_full", "detailed list supported modules" ); -} - -PlaYUVerCmdParser::~PlaYUVerCmdParser() -{ - -} - -Options& PlaYUVerCmdParser::Opts() -{ - return m_cParserOptions; -} - -std::list& PlaYUVerCmdParser::getNoArgs() -{ - return m_aUnhandledArgs; -} - -Bool PlaYUVerCmdParser::parse() -{ - try - { - // m_cParserOptions.setDefaults(); - m_aUnhandledArgs = m_cParserOptions.scanArgv( m_iArgc, ( const Char** )m_ppArgv ); - - if( checkListingOpts() ) - { - return false; - } - } - catch( std::exception& e ) - { - std::cerr << "error: " - << e.what() - << "\n"; - return false; - } - catch( ... ) - { - std::cerr << "Exception of unknown type!\n"; - } - return true; -} - -Bool PlaYUVerCmdParser::parse( Options& opts, Int argc, Char *argv[] ) -{ - try - { - // m_cParserOptions.setDefaults(); - m_aUnhandledArgs = opts.scanArgv( argc, ( const Char** )argv ); - - } - catch( std::exception& e ) - { - std::cerr << "error: " - << e.what() - << "\n"; - return false; - } - catch( ... ) - { - std::cerr << "Exception of unknown type!\n"; - } - return true; -} - -Bool PlaYUVerCmdParser::checkListingOpts() -{ - Bool bRet = false; - - if( m_cParserOptions["version"]->count() ) - { - std::cout << "PlaYUVer version " - << PLAYUVER_VERSION_STRING - << "\n"; - bRet |= true; - } - if( m_cParserOptions["pel_fmts"]->count() ) - { - printf( "PlaYUVer supported pixel formats: \n" ); - for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames().size(); i++ ) - { - printf( " %s\n", PlaYUVerFrame::supportedPixelFormatListNames()[i].c_str() ); - } - bRet |= true; - } - if( Opts()["quality_metrics"]->count() ) - { - printf( "PlaYUVer supported quality metrics: \n" ); - for( UInt i = 0; i < PlaYUVerFrame::supportedQualityMetricsList().size(); i++ ) - { - printf( " %s\n", PlaYUVerFrame::supportedQualityMetricsList()[i].c_str() ); - } - bRet |= true; - } - return bRet; -} - - diff --git a/lib/PlaYUVerCmdParser.h b/lib/PlaYUVerCmdParser.h deleted file mode 100644 index 3b12747..0000000 --- a/lib/PlaYUVerCmdParser.h +++ /dev/null @@ -1,56 +0,0 @@ -/* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) - * Joao Carreira (jfmcarreira@gmail.com) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -/** - * \file PlaYUVerCmdParser.h - * \brief Command parser - */ - -#include "PlaYUVerDefs.h" -#include "PlaYUVerOptions.h" - -#ifndef __PLAYUVERCMDPARSER_H__ -#define __PLAYUVERCMDPARSER_H__ - -class PlaYUVerCmdParser -{ -public: - PlaYUVerCmdParser(); - ~PlaYUVerCmdParser(); - - Void config( Int argc, Char *argv[] ) - { - m_iArgc = argc; - m_ppArgv = argv; - } - Bool parse(); - Bool parse( Options& opts, Int argc, Char *argv[] ); - std::list& getNoArgs(); - Options& Opts(); -private: - Int m_iArgc; - Char** m_ppArgv; - Options m_cParserOptions; - std::list m_aUnhandledArgs; - - Bool checkListingOpts(); - Void listModules(); -}; - -#endif // __PLAYUVERCMDPARSER_H__ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index cad1f7f..84bd99e 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -101,7 +101,7 @@ public: enum Module_NumberOfFrames m_uiNumberOfFrames; UInt m_uiModuleRequirements; - Options m_cModuleOptions; + PlaYUVerOptions m_cModuleOptions; PlaYUVerModuleIf() { diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index d134be3..58451c8 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -36,46 +36,273 @@ * \brief Input args handler */ +#include "config.h" +#include "PlaYUVerOptions.h" + #include #include #include #include #include +#include +#include #include #include #include -#include "PlaYUVerProgramOptions.h" + +#include "lib/PlaYUVerModuleIf.h" +#include "modules/PlaYUVerModuleFactory.h" + using namespace std; -Options::Options( const String& name ) +struct ParseFailure: public std::exception +{ + String arg; + String val; + ParseFailure( String arg0, String val0 ) throw() : + arg( arg0 ), + val( val0 ) { } + ~ParseFailure() throw() { } + const char* what() const throw() + { + return "Option Parse Failure"; + } +}; + + +/** OptionBase: Virtual base class for storing information relating to a + * specific option This base class describes common elements. Type specific + * information should be stored in a derived class. */ +class OptionBase +{ +public: + OptionBase( const String& name, const String& desc ) : + arg_count( 0 ), + opt_string( name ), + opt_desc( desc ) + { + } + + virtual ~OptionBase() + { + } + + /* parse argument arg, to obtain a value for the option */ + virtual void parse( const String& arg ) = 0; + /* set the argument to the default value */ + //virtual void setDefault() = 0; + int count() + { + return arg_count; + } + Bool isBinary() + { + return is_binary; + } + + int arg_count; + String opt_string; + String opt_desc; + Bool is_binary; +}; + +/** Type specific option storage */ +class BoolOption: public OptionBase +{ +public: + BoolOption( const String& name, Bool default_val, const String& desc ) : + OptionBase( name, desc ), + opt_storage( false ), + opt_default_val( default_val ) + { + is_binary = true; + } + + void parse( const String& arg ) + { + opt_storage = true; + arg_count++; + } + + void setDefault() + { + opt_storage = opt_default_val; + } + Bool opt_storage; + Bool opt_default_val; +}; + +/** Type specific option storage */ +template +class StandardOption: public OptionBase +{ +public: + StandardOption( const String& name, T& storage, const String& desc ) : + OptionBase( name, desc ), + opt_storage( storage ) + { + is_binary = false; + } + + void parse( const String& arg ); + T& opt_storage; +}; + +/* Generic parsing */ +template +inline void StandardOption::parse( const String& arg ) +{ + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> opt_storage; + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } + arg_count++; +} + +template<> +inline void StandardOption< std::vector >::parse( const String& arg ) +{ + UInt aux_opt_storage; + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> aux_opt_storage; + opt_storage.push_back( aux_opt_storage ); + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } + arg_count++; +} + +template<> +inline void StandardOption< std::vector >::parse( const String& arg ) +{ + Int aux_opt_storage; + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> aux_opt_storage; + opt_storage.push_back( aux_opt_storage ); + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } + arg_count++; +} + +/* string parsing is specialized */ +template<> +inline void StandardOption::parse( const String& arg ) +{ + opt_storage = arg; + arg_count++; +} + +/* string vector parsing is specialized */ +template<> +inline void StandardOption >::parse( const String& arg ) +{ + opt_storage.push_back( arg ); + arg_count++; +} + +/** Option class for argument handling using a user provided function */ +struct FunctionOption: public OptionBase +{ +public: + typedef Void( Func )( PlaYUVerOptions&, const String& ); + + FunctionOption( const String& name, PlaYUVerOptions& parent_, Func *func_, const String& desc ) : + OptionBase( name, desc ), + parent( parent_ ), + func( func_ ) + { + is_binary = false; + } + + void parse( const String& arg ) + { + func( parent, arg ); + arg_count++; + } + + void setDefault() + { + return; + } + +private: + PlaYUVerOptions& parent; + void ( *func )( PlaYUVerOptions&, const String& ); +}; + +struct PlaYUVerOptions::Option +{ + Option() : + opt( 0 ) + { + } + ~Option() + { + if( opt ) + delete opt; + } + std::list opt_long; + std::list opt_short; + OptionBase* opt; +}; + +PlaYUVerOptions::PlaYUVerOptions( const String& name ) { m_cOptionGroupName = name; m_bAllowUnkonw = true; + + /** + * Add default options + */ + addOptions()/**/ + ( "help", "produce help message" )/**/ + ( "version", "show version and exit" )/**/ + ( "pel_fmts", "list pixel formats" ) /**/ + ( "quality_metrics", "list supported quality metrics" )/**/ + ( "module_list", "list supported modules" ) /**/ + ( "module_list_full", "detailed list supported modules" ); } -Options::~Options() +PlaYUVerOptions::~PlaYUVerOptions() { - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) { delete *it; } } -OptionBase* Options::operator[]( const String& optName ) +OptionBase* PlaYUVerOptions::operator[]( const String& optName ) { return getOption( optName ); } -OptionBase* Options::getOption( const String& optName ) +OptionBase* PlaYUVerOptions::getOption( const String& optName ) { - Options::OptionMap::iterator opt_it; + PlaYUVerOptions::OptionMap::iterator opt_it; opt_it = opt_short_map.find( optName ); if( opt_it != opt_short_map.end() ) { OptionsList opt_list = ( *opt_it ).second; - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) { return ( *it )->opt; } @@ -84,7 +311,7 @@ OptionBase* Options::getOption( const String& optName ) if( opt_it != opt_long_map.end() ) { OptionsList opt_list = ( *opt_it ).second; - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) { return ( *it )->opt; } @@ -92,12 +319,17 @@ OptionBase* Options::getOption( const String& optName ) return NULL; } -Bool Options::hasOpt( const String& optName ) +Bool PlaYUVerOptions::hasOpt( const String& optName ) { return getOption( optName )->count() > 0 ? true : false; } -void Options::addOption( OptionBase *opt ) +OptionSpecific PlaYUVerOptions::addOptions() +{ + return OptionSpecific( *this ); +} + +void PlaYUVerOptions::addOption( OptionBase *opt ) { Option* names = new Option(); names->opt = opt; @@ -130,35 +362,81 @@ void Options::addOption( OptionBase *opt ) } /* Helper method to initiate adding options to Options */ -OptionSpecific Options::addOptions() + +/** + * Add option described by name to the parent Options list, + * with storage for the option's value + * with default_val as the default value + * with desc as an optional help description + */ +template +OptionSpecific& OptionSpecific::operator()( const String& name, T& storage, const String& desc ) { - return OptionSpecific( *this ); + parent.addOption( new StandardOption( name, storage, desc ) ); + return *this; } +/** + * Add option described by name to the parent Options list, + * with storage for the option's value + * with default_val as the default value + * with desc as an optional help description + */ +OptionSpecific& OptionSpecific::operator()( const String& name, const String& desc ) +{ + parent.addOption( new BoolOption( name, false, desc ) ); + return *this; +} + +/** + * Add option described by name to the parent Options list, + * with storage for the option's value + * with default_val as the default value + * with desc as an optional help description + */ +OptionSpecific& OptionSpecific::operator()( const String& name, Bool default_val, const String& desc ) +{ + parent.addOption( new BoolOption( name, default_val, desc ) ); + return *this; +} + +/** + * Add option described by name to the parent Options list, + * with desc as an optional help description + * instead of storing the value somewhere, a function of type + * FunctionOption::Func is called. It is upto this function to correctly + * handle evaluating the option's value. + */ +// OptionSpecific& OptionSpecific::operator()( const String& name, FunctionOption::Func *func, const String& desc ) +// { +// parent.addOption( new FunctionOption( name, parent, func, desc ) ); +// return *this; +// } + /* for all options in opts, set their storage to their specified * default value */ -Void Options::setDefaults() +Void PlaYUVerOptions::setDefaults() { -// for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) +// for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) // { // ( *it )->opt->setDefault(); // } } -static void setOptions( Options::OptionsList& opt_list, const string& value ) +static void setOptions( PlaYUVerOptions::OptionsList& opt_list, const string& value ) { /* multiple options may be registered for the same name: * allow each to parse value */ - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it ) { ( *it )->opt->parse( value ); } } -Bool Options::storePair( Bool allow_long, Bool allow_short, const string& name, const string& value ) +Bool PlaYUVerOptions::storePair( Bool allow_long, Bool allow_short, const string& name, const string& value ) { bool found = false; - Options::OptionMap::iterator opt_it; + PlaYUVerOptions::OptionMap::iterator opt_it; if( allow_long ) { opt_it = opt_long_map.find( name ); @@ -197,7 +475,7 @@ Bool Options::storePair( Bool allow_long, Bool allow_short, const string& name, return true; } -Bool Options::storePair( const string& name, const string& value ) +Bool PlaYUVerOptions::storePair( const string& name, const string& value ) { return storePair( true, true, name, value ); } @@ -205,7 +483,7 @@ Bool Options::storePair( const string& name, const string& value ) /** * returns number of extra arguments consumed */ -UInt Options::parseLONG( unsigned argc, const char* argv[] ) +UInt PlaYUVerOptions::parseLONG( unsigned argc, const char* argv[] ) { /* gnu style long options can take the forms: * --option=arg @@ -225,8 +503,8 @@ UInt Options::parseLONG( unsigned argc, const char* argv[] ) /* commented out, to return to true GNU style processing * where longopts have to include an =, otherwise they are * booleans */ - if (argc == 1) - return 0; /* run out of argv for argument */ + if( argc == 1 ) + return 0; /* run out of argv for argument */ extra_argc_consumed = 1; #endif if( !storePair( true, false, option, "1" ) ) @@ -246,7 +524,7 @@ UInt Options::parseLONG( unsigned argc, const char* argv[] ) /** * returns number of extra arguments consumed */ -UInt Options::parseLONG( string arg ) +UInt PlaYUVerOptions::parseLONG( string arg ) { /* gnu style long options can take the forms: * --option=arg @@ -275,7 +553,7 @@ UInt Options::parseLONG( string arg ) return extra_argc_consumed; } -unsigned Options::parseSHORT( unsigned argc, const char* argv[] ) +unsigned PlaYUVerOptions::parseSHORT( unsigned argc, const char* argv[] ) { /* short options can take the forms: * --option arg @@ -301,7 +579,33 @@ unsigned Options::parseSHORT( unsigned argc, const char* argv[] ) return 1; } -list Options::scanArgv( unsigned argc, const char* argv[] ) +Bool PlaYUVerOptions::parse( Int argc, Char *argv[] ) +{ + try + { + m_aUnhandledArgs = scanArgv( argc, ( const Char** )argv ); + + if( checkListingOpts() ) + { + return false; + } + } + catch( std::exception& e ) + { + std::cerr << "error: " + << e.what() + << "\n"; + return false; + } + catch( ... ) + { + std::cerr << "Exception of unknown type!\n"; + } + return true; +} + + +list PlaYUVerOptions::scanArgv( unsigned argc, const char* argv[] ) { /* a list for anything that didn't get handled as an option */ list non_option_arguments; @@ -325,7 +629,7 @@ list Options::scanArgv( unsigned argc, const char* argv[] ) { /* handle short (single dash) options */ #if 0 - i += parsePOSIX(opts, argc - i, &argv[i]); + i += parsePOSIX( opts, argc - i, &argv[i] ); #else i += parseSHORT( argc - i, &argv[i] ); #endif @@ -347,7 +651,7 @@ list Options::scanArgv( unsigned argc, const char* argv[] ) return non_option_arguments; } -Void Options::scanArgs( std::vector args_array) +Void PlaYUVerOptions::scanArgs( std::vector args_array ) { for( unsigned i = 0; i < args_array.size(); i++ ) { @@ -362,7 +666,7 @@ static const char spaces[41] = " "; * using the formatting: "-x, --long", * if a short/long option isn't specified, it is not printed */ -static void doHelpOpt( ostream& out, const Options::Option& entry, unsigned pad_short = 0 ) +static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, unsigned pad_short = 0 ) { pad_short = min( pad_short, 8u ); @@ -391,12 +695,12 @@ static void doHelpOpt( ostream& out, const Options::Option& entry, unsigned pad_ } /* format the help text */ -Void Options::doHelp( ostream& out, unsigned columns ) +Void PlaYUVerOptions::doHelp( ostream& out, unsigned columns ) { const unsigned pad_short = 3; /* first pass: work out the longest option name */ unsigned max_width = 0; - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) { ostringstream line( ios_base::out ); doHelpOpt( line, **it, pad_short ); @@ -411,7 +715,7 @@ Void Options::doHelp( ostream& out, unsigned columns ) * - if the option text is longer than opt_width, place the help * text at opt_width on the next line. */ - for( Options::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) + for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) { ostringstream line( ios_base::out ); line << " "; @@ -489,5 +793,97 @@ Void Options::doHelp( ostream& out, unsigned columns ) } } +Bool PlaYUVerOptions::checkListingOpts() +{ + Bool bRet = false; + + if( hasOpt( "version" ) ) + { + std::cout << "PlaYUVer version " + << PLAYUVER_VERSION_STRING + << "\n"; + bRet |= true; + } + if( hasOpt( "pel_fmts" ) ) + { + printf( "PlaYUVer supported pixel formats: \n" ); + for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames().size(); i++ ) + { + printf( " %s\n", PlaYUVerFrame::supportedPixelFormatListNames()[i].c_str() ); + } + bRet |= true; + } + if( hasOpt( "quality_metrics" ) ) + { + printf( "PlaYUVer supported quality metrics: \n" ); + for( UInt i = 0; i < PlaYUVerFrame::supportedQualityMetricsList().size(); i++ ) + { + printf( " %s\n", PlaYUVerFrame::supportedQualityMetricsList()[i].c_str() ); + } + bRet |= true; + } + if( hasOpt( "module_list" ) || hasOpt( "module_list_full" ) ) + { + listModules(); + bRet |= true; + } + return bRet; +} + +Void PlaYUVerOptions::listModules() +{ + Bool bDetailed = false; + + if( hasOpt( "module_list_full" ) ) + bDetailed = true; + + PlaYUVerModuleIf* pcCurrModuleIf; + PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); + PlaYUVerModuleFactoryMap::iterator it = PlaYUVerModuleFactoryMap.begin(); + + printf( "PlaYUVer available modules: \n" ); + printf( " [Internal Name] " ); + if( bDetailed ) + { + printf( " [Full Name] " ); + printf( " [Type] " ); + printf( " [Description]" ); + } + printf( " \n" ); + + Char ModuleNameString[40]; + + for( UInt i = 0; it != PlaYUVerModuleFactoryMap.end(); ++it, i++ ) + { + printf( " " ); + printf( "%-30s", it->first ); + if( bDetailed ) + { + ModuleNameString[0] = '\0'; + pcCurrModuleIf = it->second(); + + if( pcCurrModuleIf->m_pchModuleCategory ) + { + strcat( ModuleNameString, pcCurrModuleIf->m_pchModuleCategory ); + strcat( ModuleNameString, "/" ); + } + strcat( ModuleNameString, pcCurrModuleIf->m_pchModuleName ); + printf( " %-40s", ModuleNameString ); + switch( pcCurrModuleIf->m_iModuleType ) + { + case FRAME_PROCESSING_MODULE: + printf( " Processing " ); + break; + case FRAME_MEASUREMENT_MODULE: + printf( " Measurement " ); + break; + } + printf( " %s", pcCurrModuleIf->m_pchModuleTooltip ); + pcCurrModuleIf->Delete(); + } + printf( "\n" ); + } +} + diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index b686a96..75f19e7 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -45,282 +45,19 @@ #include #include #include + #include "PlaYUVerDefs.h" - -struct Options; - -struct ParseFailure: public std::exception -{ - ParseFailure( String arg0, String val0 ) throw() : - arg( arg0 ), - val( val0 ) - { - } - - ~ParseFailure() throw() - { - } - - String arg; - String val; - - const char* what() const throw() - { - return "Option Parse Failure"; - } -}; - -/** OptionBase: Virtual base class for storing information relating to a - * specific option This base class describes common elements. Type specific - * information should be stored in a derived class. */ -struct OptionBase -{ - OptionBase( const String& name, const String& desc ) : - arg_count( 0 ), - opt_string( name ), - opt_desc( desc ) - { - } - - virtual ~OptionBase() - { - } - - /* parse argument arg, to obtain a value for the option */ - virtual void parse( const String& arg ) = 0; - /* set the argument to the default value */ - //virtual void setDefault() = 0; - int count() - { - return arg_count; - } - Bool isBinary() - { - return is_binary; - } - - int arg_count; - String opt_string; - String opt_desc; - Bool is_binary; -}; - -/** Type specific option storage */ -struct FlagOpt: public OptionBase -{ - FlagOpt( const String& name, Bool default_val, const String& desc ) : - OptionBase( name, desc ), - opt_storage( false ), - opt_default_val( default_val ) - { - is_binary = true; - } - - void parse( const String& arg ) - { - opt_storage = true; - arg_count++; - } - - void setDefault() - { - opt_storage = opt_default_val; - } - Bool opt_storage; - Bool opt_default_val; -}; - -/** Type specific option storage */ -template -struct StandardOpt: public OptionBase -{ - StandardOpt( const String& name, T& storage, const String& desc ) : - OptionBase( name, desc ), - opt_storage( storage ) - { - is_binary = false; - } - - void parse( const String& arg ); - -// void setDefault() -// { -// opt_storage = opt_default_val; -// } - - T& opt_storage; -}; - -/* Generic parsing */ -template -inline void StandardOpt::parse( const String& arg ) -{ - std::istringstream arg_ss( arg, std::istringstream::in ); - arg_ss.exceptions( std::ios::failbit ); - try - { - arg_ss >> opt_storage; - } - catch( ... ) - { - throw ParseFailure( opt_string, arg ); - } - arg_count++; -} - -template<> -inline void StandardOpt< std::vector >::parse( const String& arg ) -{ - UInt aux_opt_storage; - std::istringstream arg_ss( arg, std::istringstream::in ); - arg_ss.exceptions( std::ios::failbit ); - try - { - arg_ss >> aux_opt_storage; - opt_storage.push_back( aux_opt_storage ); - } - catch( ... ) - { - throw ParseFailure( opt_string, arg ); - } - arg_count++; -} - -template<> -inline void StandardOpt< std::vector >::parse( const String& arg ) -{ - Int aux_opt_storage; - std::istringstream arg_ss( arg, std::istringstream::in ); - arg_ss.exceptions( std::ios::failbit ); - try - { - arg_ss >> aux_opt_storage; - opt_storage.push_back( aux_opt_storage ); - } - catch( ... ) - { - throw ParseFailure( opt_string, arg ); - } - arg_count++; -} - -/* string parsing is specialized */ -template<> -inline void StandardOpt::parse( const String& arg ) -{ - opt_storage = arg; - arg_count++; -} - -/* string vector parsing is specialized */ -template<> -inline void StandardOpt >::parse( const String& arg ) -{ - opt_storage.push_back( arg ); - arg_count++; -} - -/** Option class for argument handling using a user provided function */ -struct OptionFunc: public OptionBase -{ - typedef Void (Func)( Options&, const String& ); - - OptionFunc( const String& name, Options& parent_, Func *func_, const String& desc ) : - OptionBase( name, desc ), - parent( parent_ ), - func( func_ ) - { - is_binary = false; - } - - void parse( const String& arg ) - { - func( parent, arg ); - arg_count++; - } - - void setDefault() - { - return; - } - -private: - Options& parent; - void (*func)( Options&, const String& ); -}; - -class OptionSpecific; -class Options -{ -public: - - struct Option - { - Option() : - opt( 0 ) - { - } - ; - ~Option() - { - if( opt ) - delete opt; - } - std::list opt_long; - std::list opt_short; - OptionBase* opt; - }; - typedef std::list OptionsList; - - Options( const String& name = "" ); - ~Options(); - - std::list scanArgv( unsigned argc, const char* argv[] ); - Void scanArgs( std::vector args_array); - Void doHelp( std::ostream& out, unsigned columns = 80 ); - - OptionSpecific addOptions(); - Void setDefaults(); - - OptionBase* operator[]( const String& optName ); - OptionBase* getOption( const String& optName ); - - OptionsList& getOptionList() - { - return opt_list; - } - - Bool hasOpt( const String& optName ); - - void addOption( OptionBase *opt ); - -private: - - typedef std::map OptionMap; - OptionMap opt_long_map; - OptionMap opt_short_map; - - OptionsList opt_list; - - String m_cOptionGroupName; - Bool m_bAllowUnkonw; - - Bool storePair( Bool allow_long, Bool allow_short, const String& name, const String& value ); - Bool storePair( const String& name, const String& value ); - UInt parseLONG( unsigned argc, const char* argv[] ); - UInt parseLONG( String arg ); - unsigned parseSHORT( unsigned argc, const char* argv[] ); -}; +struct OptionBase; +class PlaYUVerOptions; /* Class with templated overloaded operator(), for use by Options::addOptions() */ class OptionSpecific { public: - OptionSpecific( Options& parent_ ) : - parent( parent_ ) - { - } + OptionSpecific( PlaYUVerOptions& parent_ ) : + parent( parent_ ) + { } /** * Add option described by name to the parent Options list, @@ -330,11 +67,7 @@ public: */ template OptionSpecific& - operator()( const String& name, T& storage, const String& desc ) - { - parent.addOption( new StandardOpt( name, storage, desc ) ); - return *this; - } + operator()( const String& name, T& storage, const String& desc ); /** * Add option described by name to the parent Options list, @@ -343,11 +76,7 @@ public: * with desc as an optional help description */ OptionSpecific& - operator()( const String& name, const String& desc ) - { - parent.addOption( new FlagOpt( name, false, desc ) ); - return *this; - } + operator()( const String& name, const String& desc ); /** * Add option described by name to the parent Options list, @@ -356,11 +85,7 @@ public: * with desc as an optional help description */ OptionSpecific& - operator()( const String& name, Bool default_val, const String& desc ) - { - parent.addOption( new FlagOpt( name, default_val, desc ) ); - return *this; - } + operator()( const String& name, Bool default_val, const String& desc ); /** * Add option described by name to the parent Options list, @@ -369,14 +94,60 @@ public: * OptionFunc::Func is called. It is upto this function to correctly * handle evaluating the option's value. */ - OptionSpecific& - operator()( const String& name, OptionFunc::Func *func, const String& desc ) - { - parent.addOption( new OptionFunc( name, parent, func, desc ) ); - return *this; - } +// OptionSpecific& +// operator()( const String& name, OptionFunc::Func *func, const String& desc ) private: - Options& parent; + PlaYUVerOptions& parent; }; + +class PlaYUVerOptions +{ +public: + + struct Option; + + typedef std::list OptionsList; + + PlaYUVerOptions( const String& name = "" ); + ~PlaYUVerOptions(); + + Bool parse( Int argc, Char *argv[] ); + std::list scanArgv( unsigned argc, const char* argv[] ); + Void scanArgs( std::vector args_array ); + Void doHelp( std::ostream& out, unsigned columns = 80 ); + + Bool checkListingOpts(); + Void listModules(); + Void setDefaults(); + + OptionBase* operator[]( const String& optName ); + OptionBase* getOption( const String& optName ); + + Bool hasOpt( const String& optName ); + + OptionSpecific addOptions(); + void addOption( OptionBase *opt ); + +private: + typedef std::map OptionMap; + OptionMap opt_long_map; + OptionMap opt_short_map; + + OptionsList opt_list; + + String m_cOptionGroupName; + Bool m_bAllowUnkonw; + std::list m_aUnhandledArgs; + + Bool storePair( Bool allow_long, Bool allow_short, const String& name, const String& value ); + Bool storePair( const String& name, const String& value ); + UInt parseLONG( unsigned argc, const char* argv[] ); + UInt parseLONG( String arg ); + UInt parseSHORT( unsigned argc, const char* argv[] ); + +}; + + + #endif // __PROGRAMOPTIONS_H__ diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 2af415a..1d5c1c1 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -58,26 +58,20 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) { Int iRet = 0; - Opts().addOptions()/**/ - ( "quiet,q", m_bQuiet, "disable verbose" ); - - Opts().addOptions()/**/ + m_cOptions.addOptions()/**/ + ( "quiet,q", m_bQuiet, "disable verbose" ) ( "input,i", m_apcInputs, "input file" ) /**/ - //( "input,i", m_strInput, "input file" ) /**/ ( "output,o", m_strOutput, "output file" ) /**/ ( "size,s", m_strResolution, "size (WxH)" ) /**/ ( "pel_fmt,p", m_strPelFmt, "pixel format" ) /**/ ( "bits_pel", m_uiBitsPerPixel, "bits per pixel" ) /**/ ( "endianness", m_strEndianness, "File endianness (big, little)" ) /**/ - ( "frames,f", m_iFrames, "number of frames to parse" ); - - Opts().addOptions()/**/ + ( "frames,f", m_iFrames, "number of frames to parse" )/**/ ( "quality", m_strQualityMetric, "select a quality metric" ) /**/ ( "module", m_strModule, "select a module (use internal name)" ) /**/ ( "save", "save a specific frame" ); - config( argc, argv ); - if( !parse() ) + if( !m_cOptions.parse( argc, argv ) ) { iRet = 1; } @@ -87,82 +81,26 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) m_uiLogLevel = LOG_RESULT; } - if( Opts().hasOpt("module") && Opts().hasOpt("help") ) + if( m_cOptions.hasOpt("module") && m_cOptions.hasOpt("help") ) { listModuleHelp(); iRet = 1; } - else if( Opts().hasOpt("help") ) + else if( m_cOptions.hasOpt("help") ) { printf( "Usage: %s modules/quality/save [options] -input=input_file [--output=output_file]\n", argv[0] ); - Opts().doHelp( std::cout ); + m_cOptions.doHelp( std::cout ); iRet = 1; } - if( Opts().hasOpt("module_list") || Opts().hasOpt("module_list_full") ) + if( m_cOptions.hasOpt("module_list") || m_cOptions.hasOpt("module_list_full") ) { - listModules(); + m_cOptions.listModules(); iRet = 1; } return iRet; } -Void PlaYUVerToolsCmdParser::listModules() -{ - Bool bDetailed = false; - - if( Opts().hasOpt("module_list_full") ) - bDetailed = true; - - PlaYUVerModuleIf* pcCurrModuleIf; - PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); - PlaYUVerModuleFactoryMap::iterator it = PlaYUVerModuleFactoryMap.begin(); - - printf( "PlaYUVer available modules: \n" ); - //printf( " " ); - printf( " [Internal Name] " ); - if( bDetailed ) - { - printf( " [Full Name] " ); - printf( " [Type] " ); - printf( " [Description]" ); - } - printf( " \n" ); - - Char ModuleNameString[40]; - - for( UInt i = 0; it != PlaYUVerModuleFactoryMap.end(); ++it, i++ ) - { - printf( " " ); - printf( "%-30s", it->first ); - if( bDetailed ) - { - ModuleNameString[0] = '\0'; - pcCurrModuleIf = it->second(); - - if( pcCurrModuleIf->m_pchModuleCategory ) - { - strcat( ModuleNameString, pcCurrModuleIf->m_pchModuleCategory ); - strcat( ModuleNameString, "/" ); - } - strcat( ModuleNameString, pcCurrModuleIf->m_pchModuleName ); - printf( " %-40s", ModuleNameString ); - switch( pcCurrModuleIf->m_iModuleType ) - { - case FRAME_PROCESSING_MODULE: - printf( " Processing " ); - break; - case FRAME_MEASUREMENT_MODULE: - printf( " Measurement " ); - break; - } - printf( " %s", pcCurrModuleIf->m_pchModuleTooltip ); - pcCurrModuleIf->Delete(); - } - printf( "\n" ); - } -} - Void PlaYUVerToolsCmdParser::listModuleHelp() { String moduleName = m_strModule; diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index adfde00..0796fd2 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -27,12 +27,12 @@ #include "config.h" #include "lib/PlaYUVerDefs.h" -#include "lib/PlaYUVerCmdParser.h" +#include "lib/PlaYUVerOptions.h" class PlaYUVerStream; -class PlaYUVerToolsCmdParser: public PlaYUVerCmdParser +class PlaYUVerToolsCmdParser { friend class PlaYUVerTools; public: @@ -60,8 +60,13 @@ public: Int parseToolsArgs( Int argc, Char *argv[] ); + PlaYUVerOptions& Opts() + { + return m_cOptions; + } + private: - Options m_cParserOptions; + PlaYUVerOptions m_cOptions; UInt m_uiLogLevel; /** From 3c1470b4cfa546b8e1a0c72aab698a6fba018fc0 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 1 May 2016 20:05:24 +0100 Subject: [PATCH 050/127] Fix error after rename file --- lib/PlaYUVerOptions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index d134be3..4947886 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -44,7 +44,7 @@ #include #include #include -#include "PlaYUVerProgramOptions.h" +#include "PlaYUVerOptions.h" using namespace std; From 67e6d49be14ed3720bdbbe7e50fa98057aac6959 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 2 May 2016 23:31:41 +0100 Subject: [PATCH 051/127] Change Option parsing implmentation Clean structs and classes. Hide implementation details Remove redundant classes --- app/ModulesHandle.cpp | 5 +- app/ModulesHandleOptDialog.cpp | 6 +- app/PlaYUVerApp.cpp | 15 +- app/PlaYUVerApp.h | 4 +- app/VideoSubWindow.cpp | 6 +- lib/PlaYUVerDefs.h | 16 ++ lib/PlaYUVerFrame.cpp | 20 +-- lib/PlaYUVerOptions.cpp | 265 +++++++++++-------------------- lib/PlaYUVerOptions.h | 139 ++++++++++------ lib/PlaYUVerStream.cpp | 22 +-- lib/PlaYUVerStream.h | 4 +- lib/StreamHandlerLibav.cpp | 2 +- tools/PlaYUVerTools.cpp | 120 +++++++------- tools/PlaYUVerTools.h | 3 +- tools/PlaYUVerToolsCmdParser.cpp | 8 +- tools/PlaYUVerToolsCmdParser.h | 3 +- tools/main.cpp | 2 +- 17 files changed, 307 insertions(+), 333 deletions(-) diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index f9fb0b9..2feee91 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -495,7 +495,7 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) if( !pcCurrModuleIf->m_pcModuleStream ) { UInt Width = 0, Height = 0, FrameRate = 30; - Int BitsPixel, InputFormat = -1; + Int BitsPixel, Endianness, InputFormat = -1; QString supported = tr( "Supported Files (" ); QStringList formatsList; @@ -525,10 +525,11 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight(); InputFormat = pcCurrModuleIf->m_pcProcessedFrame->getPelFormat(); BitsPixel = pcCurrModuleIf->m_pcProcessedFrame->getBitsPel(); + Endianness = pcCurrModuleIf->m_pcProcessedFrame->getEndianness(); FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate(); pcCurrModuleIf->m_pcModuleStream = new PlaYUVerStream; - if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, FrameRate, false ) ) + if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, Endianness, FrameRate, false ) ) { delete pcCurrModuleIf->m_pcModuleStream; pcCurrModuleIf->m_pcModuleStream = NULL; diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index ac8bdd4..6e1a61b 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -86,11 +86,11 @@ ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget *parent, PlaYUVerAppModu resize( 400, 10 ); setWindowTitle( "Select module parameters" ); - const Options::OptionsList& moduleOptions = m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList(); + const PlaYUVerOptions::OptionsList& moduleOptions = m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList(); QVBoxLayout* optionsLayout = new QVBoxLayout; OpionConfiguration* pcOption; - for( Options::OptionsList::const_iterator it = moduleOptions.begin(); it != moduleOptions.end(); ++it ) + for( PlaYUVerOptions::OptionsList::const_iterator it = moduleOptions.begin(); it != moduleOptions.end(); ++it ) { pcOption = new OpionConfiguration( ( *it )->opt ); m_apcOptionList.append( pcOption ); @@ -142,7 +142,7 @@ Int ModulesHandleOptDialog::runConfiguration() } if( argsArray.size() > 0 ) { - m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.scanArgs( argsArray ); + m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.parse( argsArray ); } return QDialog::Accepted; } diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 11ee89a..798fa98 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -94,37 +94,36 @@ PlaYUVerApp::PlaYUVerApp() : Bool PlaYUVerApp::parseArgs( Int argc, Char *argv[] ) { Bool bRet = false; - m_pcCmdParser = new PlaYUVerCmdParser(); - m_pcCmdParser->config( argc, argv ); + PlaYUVerOptions pcCmdParser; std::vector m_apcInputs; String strResolution( "" ); String strPelFmt( "" ); - m_pcCmdParser->Opts().addOptions()/**/ + pcCmdParser.addOptions()/**/ ( "input,i", m_apcInputs, "input file" ) /**/ ( "size,s", strResolution, "size (WxH)" ) /**/ ( "pel_fmt", strPelFmt, "pixel format" ); - if( !m_pcCmdParser->parse() ) + if( !pcCmdParser.parse( argc, argv ) ) { bRet |= true; } - if( m_pcCmdParser->Opts()["help"]->count() ) + if( pcCmdParser.hasOpt("help") ) { printf( "Usage: %s [options] input_file[s]\n", argv[0] ); - m_pcCmdParser->Opts().doHelp( std::cout ); + pcCmdParser.doHelp( std::cout ); bRet |= true; } - if( m_pcCmdParser->Opts()["input"]->count() ) + if( pcCmdParser.hasOpt("input") ) { for( UInt i = 1; i < m_apcInputs.size(); i++ ) { loadFile( QString::fromStdString( m_apcInputs[i] ) ); } } - std::list& argv_unhandled = m_pcCmdParser->getNoArgs(); + std::list& argv_unhandled = pcCmdParser.getUnhandledArgs(); for( std::list::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++ ) { loadFile( QString::fromStdString( *it ) ); diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index a83d450..02826b7 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -55,7 +55,7 @@ class QAction; class QSignalMapper; -class PlaYUVerCmdParser; +class PlaYUVerOptions; class PlaYUVerStream; class PlaYUVerSubWindowHandle; class VideoHandle; @@ -118,7 +118,7 @@ private Q_SLOTS: private: PlaYUVerAppAdaptor* m_pDBusAdaptor; - PlaYUVerCmdParser* m_pcCmdParser; + PlaYUVerOptions* m_pcCmdParser; /** * Save the current subwindow for every category */ diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index ef158e4..7413d1e 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -328,7 +328,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) try { - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate, true ); } catch( const char *msg ) { @@ -336,7 +336,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) { return false; } - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate, true ); } m_sStreamInfo.m_cFilename = cFilename; @@ -367,7 +367,7 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) } if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, streamInfo->m_iPelFormat, - streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate ) ) + streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate, true) ) { return false; } diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 6262817..b89e5f2 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -134,6 +134,22 @@ inline String uppercase( const String& in ) return out; } +struct PlaYUVerFailure: public std::exception +{ + String m_class_name; + String m_error_msg; + PlaYUVerFailure( String error_msg ) throw() : + m_error_msg( error_msg ) { } + PlaYUVerFailure( String class_name, String error_msg ) throw() : + m_class_name( class_name ), + m_error_msg( error_msg ) { } + ~PlaYUVerFailure() throw() { } + const Char* what() const throw() + { + String* msg = new String( "[" + m_class_name + "] " + m_error_msg ); + return msg->c_str(); + } +}; #endif // __PLAYUVERDEFS_H__ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 8f440fe..0f5b2c4 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -216,13 +216,13 @@ Void PlaYUVerFramePrivate::init( UInt width, UInt height, Int pel_format, Int bi m_iEndianness = endianness; if( m_uiBitsPel > 8 && m_iEndianness == -1 ) { - throw "Invalid endianness type for Bits per Pixel greater than 8"; + throw PlaYUVerFailure( "PlaYUVerFrame", "Invalid endianness type for Bits per Pixel greater than 8" ); } m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) { - throw "Cannot create a PlYUVerFrame of this type"; + throw PlaYUVerFailure( "PlaYUVerFrame", "Cannot create a PlYUVerFrame of this type" ); } m_pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[pel_format] ); @@ -1090,14 +1090,14 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) { switch( pcCvFrame->channels() ) { - case 1: - d->m_iPixelFormat = findPixelFormat( "GRAY" ); - break; - case 3: - d->m_iPixelFormat = findPixelFormat( "BGR24" ); - break; - default: - return; + case 1: + d->m_iPixelFormat = findPixelFormat( "GRAY" ); + break; + case 3: + d->m_iPixelFormat = findPixelFormat( "BGR24" ); + break; + default: + return; } } d->init( pcCvFrame->cols, pcCvFrame->rows, d->m_iPixelFormat, 8, -1 ); diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index 58451c8..816dba2 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -65,73 +65,27 @@ struct ParseFailure: public std::exception arg( arg0 ), val( val0 ) { } ~ParseFailure() throw() { } - const char* what() const throw() + const Char* what() const throw() { return "Option Parse Failure"; } }; -/** OptionBase: Virtual base class for storing information relating to a - * specific option This base class describes common elements. Type specific - * information should be stored in a derived class. */ -class OptionBase -{ -public: - OptionBase( const String& name, const String& desc ) : - arg_count( 0 ), - opt_string( name ), - opt_desc( desc ) - { - } - - virtual ~OptionBase() - { - } - - /* parse argument arg, to obtain a value for the option */ - virtual void parse( const String& arg ) = 0; - /* set the argument to the default value */ - //virtual void setDefault() = 0; - int count() - { - return arg_count; - } - Bool isBinary() - { - return is_binary; - } - - int arg_count; - String opt_string; - String opt_desc; - Bool is_binary; -}; - /** Type specific option storage */ class BoolOption: public OptionBase { public: - BoolOption( const String& name, Bool default_val, const String& desc ) : - OptionBase( name, desc ), - opt_storage( false ), - opt_default_val( default_val ) + BoolOption( const String& name, const String& desc ) : + OptionBase( name, desc ) { is_binary = true; } void parse( const String& arg ) { - opt_storage = true; arg_count++; } - - void setDefault() - { - opt_storage = opt_default_val; - } - Bool opt_storage; - Bool opt_default_val; }; /** Type specific option storage */ @@ -148,21 +102,25 @@ public: void parse( const String& arg ); T& opt_storage; + std::vector opt_storage_array; }; /* Generic parsing */ template inline void StandardOption::parse( const String& arg ) { - std::istringstream arg_ss( arg, std::istringstream::in ); - arg_ss.exceptions( std::ios::failbit ); - try + if( !is_binary ) { - arg_ss >> opt_storage; - } - catch( ... ) - { - throw ParseFailure( opt_string, arg ); + std::istringstream arg_ss( arg, std::istringstream::in ); + arg_ss.exceptions( std::ios::failbit ); + try + { + arg_ss >> opt_storage; + } + catch( ... ) + { + throw ParseFailure( opt_string, arg ); + } } arg_count++; } @@ -239,47 +197,63 @@ public: arg_count++; } - void setDefault() - { - return; - } - private: PlaYUVerOptions& parent; void ( *func )( PlaYUVerOptions&, const String& ); }; -struct PlaYUVerOptions::Option +/* Helper method to initiate adding options to Options */ + +/** + * Add option described by name to the parent Options list, + * with storage for the option's value + * with default_val as the default value + * with desc as an optional help description + */ +PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, const String& desc ) { - Option() : - opt( 0 ) - { - } - ~Option() - { - if( opt ) - delete opt; - } - std::list opt_long; - std::list opt_short; - OptionBase* opt; -}; + addOption( new BoolOption( name, desc ) ); + return *this; +} + +/** + * Add option described by name to the parent Options list, + * with storage for the option's value + * with desc as an optional help description + */ +template +PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, T& storage, const String& desc ) +{ + addOption( new StandardOption( name, storage, desc ) ); + return *this; +} + +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Bool& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, UInt& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int64& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, String& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); + +/** + * Add option described by name to the parent Options list, + * with desc as an optional help description + * instead of storing the value somewhere, a function of type + * FunctionOption::Func is called. It is upto this function to correctly + * handle evaluating the option's value. + */ +// PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, FunctionOption::Func *func, const String& desc ) +// { +// addOption( new FunctionOption( name, parent, func, desc ) ); +// return *this; +// } PlaYUVerOptions::PlaYUVerOptions( const String& name ) { m_cOptionGroupName = name; m_bAllowUnkonw = true; - - /** - * Add default options - */ - addOptions()/**/ - ( "help", "produce help message" )/**/ - ( "version", "show version and exit" )/**/ - ( "pel_fmts", "list pixel formats" ) /**/ - ( "quality_metrics", "list supported quality metrics" )/**/ - ( "module_list", "list supported modules" ) /**/ - ( "module_list_full", "detailed list supported modules" ); } PlaYUVerOptions::~PlaYUVerOptions() @@ -321,12 +295,25 @@ OptionBase* PlaYUVerOptions::getOption( const String& optName ) Bool PlaYUVerOptions::hasOpt( const String& optName ) { - return getOption( optName )->count() > 0 ? true : false; + OptionBase* opt = getOption( optName ); + return opt ? opt->count() > 0 ? true : false : false; } -OptionSpecific PlaYUVerOptions::addOptions() +Void PlaYUVerOptions::addDefaultOptions() { - return OptionSpecific( *this ); + addOptions()/**/ + ( "help,h", "produce help message" )/**/ + ( "version", "show version and exit" )/**/ + ( "pel_fmts", "list pixel formats" ) /**/ + ( "quality_metrics", "list supported quality metrics" )/**/ + ( "module_list", "list supported modules" ) /**/ + ( "module_list_full", "detailed list supported modules" ); +} + + +PlaYUVerOptions& PlaYUVerOptions::addOptions() +{ + return *this; } void PlaYUVerOptions::addOption( OptionBase *opt ) @@ -361,67 +348,7 @@ void PlaYUVerOptions::addOption( OptionBase *opt ) opt_list.push_back( names ); } -/* Helper method to initiate adding options to Options */ -/** - * Add option described by name to the parent Options list, - * with storage for the option's value - * with default_val as the default value - * with desc as an optional help description - */ -template -OptionSpecific& OptionSpecific::operator()( const String& name, T& storage, const String& desc ) -{ - parent.addOption( new StandardOption( name, storage, desc ) ); - return *this; -} - -/** - * Add option described by name to the parent Options list, - * with storage for the option's value - * with default_val as the default value - * with desc as an optional help description - */ -OptionSpecific& OptionSpecific::operator()( const String& name, const String& desc ) -{ - parent.addOption( new BoolOption( name, false, desc ) ); - return *this; -} - -/** - * Add option described by name to the parent Options list, - * with storage for the option's value - * with default_val as the default value - * with desc as an optional help description - */ -OptionSpecific& OptionSpecific::operator()( const String& name, Bool default_val, const String& desc ) -{ - parent.addOption( new BoolOption( name, default_val, desc ) ); - return *this; -} - -/** - * Add option described by name to the parent Options list, - * with desc as an optional help description - * instead of storing the value somewhere, a function of type - * FunctionOption::Func is called. It is upto this function to correctly - * handle evaluating the option's value. - */ -// OptionSpecific& OptionSpecific::operator()( const String& name, FunctionOption::Func *func, const String& desc ) -// { -// parent.addOption( new FunctionOption( name, parent, func, desc ) ); -// return *this; -// } - -/* for all options in opts, set their storage to their specified - * default value */ -Void PlaYUVerOptions::setDefaults() -{ -// for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) -// { -// ( *it )->opt->setDefault(); -// } -} static void setOptions( PlaYUVerOptions::OptionsList& opt_list, const string& value ) { @@ -483,7 +410,7 @@ Bool PlaYUVerOptions::storePair( const string& name, const string& value ) /** * returns number of extra arguments consumed */ -UInt PlaYUVerOptions::parseLONG( unsigned argc, const char* argv[] ) +UInt PlaYUVerOptions::parseLONG( UInt argc, Char* argv[] ) { /* gnu style long options can take the forms: * --option=arg @@ -494,7 +421,7 @@ UInt PlaYUVerOptions::parseLONG( unsigned argc, const char* argv[] ) size_t arg_opt_sep = arg.find_first_of( '=' ); string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start ); - unsigned extra_argc_consumed = 0; + UInt extra_argc_consumed = 0; if( arg_opt_sep == string::npos ) { /* no argument found => argument in argv[1] (maybe) */ @@ -534,7 +461,7 @@ UInt PlaYUVerOptions::parseLONG( string arg ) size_t arg_opt_sep = arg.find_first_of( '=' ); string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start ); - unsigned extra_argc_consumed = 0; + UInt extra_argc_consumed = 0; if( arg_opt_sep == string::npos ) { /* no argument found => argument in argv[1] (maybe) */ @@ -553,7 +480,7 @@ UInt PlaYUVerOptions::parseLONG( string arg ) return extra_argc_consumed; } -unsigned PlaYUVerOptions::parseSHORT( unsigned argc, const char* argv[] ) +UInt PlaYUVerOptions::parseSHORT( UInt argc, Char* argv[] ) { /* short options can take the forms: * --option arg @@ -579,11 +506,11 @@ unsigned PlaYUVerOptions::parseSHORT( unsigned argc, const char* argv[] ) return 1; } -Bool PlaYUVerOptions::parse( Int argc, Char *argv[] ) +Bool PlaYUVerOptions::parse( UInt argc, Char *argv[] ) { try { - m_aUnhandledArgs = scanArgv( argc, ( const Char** )argv ); + m_aUnhandledArgs = scanArgv( argc, argv ); if( checkListingOpts() ) { @@ -605,12 +532,12 @@ Bool PlaYUVerOptions::parse( Int argc, Char *argv[] ) } -list PlaYUVerOptions::scanArgv( unsigned argc, const char* argv[] ) +list PlaYUVerOptions::scanArgv( UInt argc, Char *argv[] ) { /* a list for anything that didn't get handled as an option */ - list non_option_arguments; + list non_option_arguments; - for( unsigned i = 1; i < argc; i++ ) + for( UInt i = 1; i < argc; i++ ) { if( argv[i][0] != '-' ) { @@ -651,9 +578,9 @@ list PlaYUVerOptions::scanArgv( unsigned argc, const char* argv[] ) return non_option_arguments; } -Void PlaYUVerOptions::scanArgs( std::vector args_array ) +Void PlaYUVerOptions::parse( std::vector args_array ) { - for( unsigned i = 0; i < args_array.size(); i++ ) + for( UInt i = 0; i < args_array.size(); i++ ) { i += parseLONG( args_array[i] ); } @@ -666,13 +593,13 @@ static const char spaces[41] = " "; * using the formatting: "-x, --long", * if a short/long option isn't specified, it is not printed */ -static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, unsigned pad_short = 0 ) +static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, UInt pad_short = 0 ) { pad_short = min( pad_short, 8u ); if( !entry.opt_short.empty() ) { - unsigned pad = max( ( int )pad_short - ( int )entry.opt_short.front().size(), 0 ); + UInt pad = max( ( int )pad_short - ( int )entry.opt_short.front().size(), 0 ); out << "-" << entry.opt_short.front(); if( !entry.opt_long.empty() ) @@ -695,20 +622,20 @@ static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, unsig } /* format the help text */ -Void PlaYUVerOptions::doHelp( ostream& out, unsigned columns ) +Void PlaYUVerOptions::doHelp( ostream& out, UInt columns ) { - const unsigned pad_short = 3; + const UInt pad_short = 3; /* first pass: work out the longest option name */ - unsigned max_width = 0; + UInt max_width = 0; for( PlaYUVerOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ ) { ostringstream line( ios_base::out ); doHelpOpt( line, **it, pad_short ); - max_width = max( max_width, ( unsigned )line.tellp() ); + max_width = max( max_width, ( UInt )line.tellp() ); } - unsigned opt_width = min( max_width + 2, 28u + pad_short ) + 2; - unsigned desc_width = columns - opt_width; + UInt opt_width = min( max_width + 2, 28u + pad_short ) + 2; + UInt desc_width = columns - opt_width; /* second pass: write out formatted option and help text. * - align start of help text to start at opt_width diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index 75f19e7..599e935 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -48,26 +48,89 @@ #include "PlaYUVerDefs.h" -struct OptionBase; -class PlaYUVerOptions; -/* Class with templated overloaded operator(), for use by Options::addOptions() */ -class OptionSpecific +/** OptionBase: Virtual base class for storing information relating to a + * specific option This base class describes common elements. + * Type specific information should be stored in a derived class. + */ +class OptionBase { public: - OptionSpecific( PlaYUVerOptions& parent_ ) : - parent( parent_ ) + OptionBase( const String& name, const String& desc ) : + arg_count( 0 ), + opt_string( name ), + opt_desc( desc ) { } - /** - * Add option described by name to the parent Options list, - * with storage for the option's value - * with default_val as the default value - * with desc as an optional help description - */ - template - OptionSpecific& - operator()( const String& name, T& storage, const String& desc ); + virtual ~OptionBase() {} + + /* parse argument arg, to obtain a value for the option */ + virtual void parse( const String& arg ) = 0; + Int count() + { + return arg_count; + } + Bool isBinary() + { + return is_binary; + } + + int arg_count; + String opt_string; + String opt_desc; + Bool is_binary; +}; + + +class PlaYUVerOptions +{ +public: + + struct Option + { + Option() : + opt( 0 ) + { + } + ~Option() + { + if( opt ) + delete opt; + } + std::list opt_long; + std::list opt_short; + OptionBase* opt; + }; + + + typedef std::list OptionsList; + + PlaYUVerOptions( const String& name = "" ); + ~PlaYUVerOptions(); + + Bool parse( UInt argc, Char *argv[] ); + Void parse( std::vector args_array ); + + std::list& getUnhandledArgs() + { + return m_aUnhandledArgs; + } + + Void doHelp( std::ostream& out, unsigned columns = 80 ); + + OptionBase* operator[]( const String& optName ); + OptionBase* getOption( const String& optName ); + + Bool hasOpt( const String& optName ); + + OptionsList getOptionList() + { + return opt_list; + } + + Void addDefaultOptions(); + PlaYUVerOptions& addOptions(); + void addOption( OptionBase *opt ); /** * Add option described by name to the parent Options list, @@ -75,7 +138,7 @@ public: * with default_val as the default value * with desc as an optional help description */ - OptionSpecific& + PlaYUVerOptions& operator()( const String& name, const String& desc ); /** @@ -84,8 +147,10 @@ public: * with default_val as the default value * with desc as an optional help description */ - OptionSpecific& - operator()( const String& name, Bool default_val, const String& desc ); + template + PlaYUVerOptions& + operator()( const String& name, T& storage, const String& desc ); + /** * Add option described by name to the parent Options list, @@ -94,40 +159,12 @@ public: * OptionFunc::Func is called. It is upto this function to correctly * handle evaluating the option's value. */ -// OptionSpecific& -// operator()( const String& name, OptionFunc::Func *func, const String& desc ) -private: - PlaYUVerOptions& parent; -}; +// PlaYUVerOptions& +// operator()( const String& name, OptionFunc::Func *func, const String& desc ); -class PlaYUVerOptions -{ -public: - - struct Option; - - typedef std::list OptionsList; - - PlaYUVerOptions( const String& name = "" ); - ~PlaYUVerOptions(); - - Bool parse( Int argc, Char *argv[] ); - std::list scanArgv( unsigned argc, const char* argv[] ); - Void scanArgs( std::vector args_array ); - Void doHelp( std::ostream& out, unsigned columns = 80 ); - Bool checkListingOpts(); Void listModules(); - Void setDefaults(); - - OptionBase* operator[]( const String& optName ); - OptionBase* getOption( const String& optName ); - - Bool hasOpt( const String& optName ); - - OptionSpecific addOptions(); - void addOption( OptionBase *opt ); private: typedef std::map OptionMap; @@ -142,12 +179,12 @@ private: Bool storePair( Bool allow_long, Bool allow_short, const String& name, const String& value ); Bool storePair( const String& name, const String& value ); - UInt parseLONG( unsigned argc, const char* argv[] ); + UInt parseLONG( UInt argc, Char* argv[] ); UInt parseLONG( String arg ); - UInt parseSHORT( unsigned argc, const char* argv[] ); + UInt parseSHORT( UInt argc, Char* argv[] ); + std::list scanArgv( UInt argc, Char* argv[] ); }; - #endif // __PROGRAMOPTIONS_H__ diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 586cc96..c7b1a3e 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -196,14 +196,14 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); if( !m_pfctCreateHandler ) { - throw "[PlaYUVerStream] Invalid handler"; + throw PlaYUVerFailure("PlaYUVerStream", "Invalid handler"); } m_pcHandler = m_pfctCreateHandler(); if( !m_pcHandler ) { - throw "[PlaYUVerStream] Cannot create handler"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot create handler"); } m_cFilename = filename; @@ -220,7 +220,7 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { close(); - throw "[PlaYUVerStream] Cannot open file"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot open file " + m_cFilename ); return m_bInit; } @@ -228,7 +228,7 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 ) { close(); - throw "[PlaYUVerStream] Incorrect configuration"; + throw PlaYUVerFailure("PlaYUVerStream", "Incorrect configuration"); return m_bInit; } @@ -244,7 +244,7 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f catch( const char *msg ) { close(); - throw "[PlaYUVerStream] Cannot allocated frame buffer"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot allocated frame buffer"); return m_bInit; } } @@ -261,14 +261,14 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f if( m_bIsInput && m_uiTotalFrameNum <= 0 ) { close(); - throw "[PlaYUVerStream] Incorrect configuration: less than one frame"; + throw PlaYUVerFailure("PlaYUVerStream", "Incorrect configuration: less than one frame"); return m_bInit; } if( !m_pcHandler->configureBuffer( m_pcCurrFrame ) ) { close(); - throw "[PlaYUVerStream] Cannot allocated memory"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot allocated memory"); return m_bInit; } @@ -286,7 +286,7 @@ Bool PlaYUVerStream::reload() m_pcHandler->closeHandler(); if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { - throw "[PlaYUVerStream] Cannot open file using FFmpeg libs"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot open file"); } m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); @@ -466,7 +466,7 @@ Void PlaYUVerStream::readFrame() if( !m_pcHandler->read( m_pcNextFrame ) ) { - throw "[PlaYUVerStream] Cannot read file"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot read file"); return; } @@ -483,7 +483,7 @@ Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) { if( !m_pcHandler->write( pcFrame ) ) { - throw "[PlaYUVerStream] Cannot write into the file"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot write into the file"); } return; } @@ -588,7 +588,7 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) if( !m_pcHandler->seek( new_frame_num ) ) { - throw "[PlaYUVerStream] Cannot write into the file"; + throw PlaYUVerFailure("PlaYUVerStream", "Cannot write into the file"); } m_uiCurrFrameFileIdx = new_frame_num; diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 3449985..690c2dc 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -103,8 +103,8 @@ public: String getFormatName(); String getCodecName(); - Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); - Bool open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput = true ); + Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); + Bool open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); Bool reload(); Void close(); diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 8b9e9aa..d62216e 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -216,7 +216,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) } if( m_iPixelFormat == PlaYUVerFrame::NO_FMT ) { - throw "Cannot open file using FFmpeg libs - unsupported pixel format"; + throw PlaYUVerFailure("Cannot open file using FFmpeg libs - unsupported pixel format"); return false; } diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index a714ad6..5c2c1a1 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -60,9 +60,9 @@ Int PlaYUVerTools::openInputs() /** * Create input streams */ - if( m_cCmdLineHandler.Opts().hasOpt( "input" ) ) + if( Opts().hasOpt( "input" ) ) { - std::vector inputFileNames = m_cCmdLineHandler.m_apcInputs; + std::vector inputFileNames = m_apcInputs; String resolutionString( "" ); String fmtString( "yuv420p" ); @@ -72,25 +72,25 @@ Int PlaYUVerTools::openInputs() PlaYUVerStream* pcStream; for( UInt i = 0; i < inputFileNames.size() && i < MAX_NUMBER_INPUTS; i++ ) { - if( m_cCmdLineHandler.Opts().hasOpt( "size" ) ) + if( Opts().hasOpt( "size" ) ) { - resolutionString = GET_PARAM( m_cCmdLineHandler.m_strResolution, 0 ); + resolutionString = GET_PARAM( m_strResolution, 0 ); } - if( m_cCmdLineHandler.Opts().hasOpt( "pel_fmt" ) ) + if( Opts().hasOpt( "pel_fmt" ) ) { - fmtString = GET_PARAM( m_cCmdLineHandler.m_strPelFmt, i ); + fmtString = GET_PARAM( m_strPelFmt, i ); } - if( m_cCmdLineHandler.Opts().hasOpt( "bits_pel" ) ) + if( Opts().hasOpt( "bits_pel" ) ) { - uiBitPerPixel = GET_PARAM( m_cCmdLineHandler.m_uiBitsPerPixel, i ); + uiBitPerPixel = GET_PARAM( m_uiBitsPerPixel, i ); } - if( m_cCmdLineHandler.Opts().hasOpt( "endianness" ) ) + if( Opts().hasOpt( "endianness" ) ) { - if( GET_PARAM( m_cCmdLineHandler.m_strEndianness, i ) == "big" ) + if( GET_PARAM( m_strEndianness, i ) == "big" ) { uiEndianness = 0; } - if( GET_PARAM( m_cCmdLineHandler.m_strEndianness, i ) == "little" ) + if( GET_PARAM( m_strEndianness, i ) == "little" ) { uiEndianness = 1; } @@ -98,25 +98,25 @@ Int PlaYUVerTools::openInputs() pcStream = new PlaYUVerStream; try { - if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, uiEndianness, 1 ) ) + if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, uiEndianness, 1, true ) ) { - m_cCmdLineHandler.log( LOG_ERROR, "Cannot open input stream %s! ", inputFileNames[i].c_str() ); + log( LOG_ERROR, "Cannot open input stream %s! ", inputFileNames[i].c_str() ); return 2; } m_apcInputStreams.push_back( pcStream ); } catch( const char *msg ) { - m_cCmdLineHandler.log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", inputFileNames[i].c_str(), msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", inputFileNames[i].c_str(), msg ); return 2; } } } m_uiNumberOfFrames = MAX_UINT; - if( m_cCmdLineHandler.Opts().hasOpt( "frames" ) ) + if( Opts().hasOpt( "frames" ) ) { - m_uiNumberOfFrames = m_cCmdLineHandler.m_iFrames; + m_uiNumberOfFrames = m_iFrames; } m_uiNumberOfComponents = MAX_UINT; @@ -135,7 +135,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) { Int iRet = 0; - if( ( iRet = m_cCmdLineHandler.parseToolsArgs( argc, argv ) ) > 0 ) + if( ( iRet = parseToolsArgs( argc, argv ) ) > 0 ) { return iRet; } @@ -145,11 +145,11 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) return 2; } - if( m_cCmdLineHandler.Opts().hasOpt( "save" ) ) + if( Opts().hasOpt( "save" ) ) { if( m_apcInputStreams.size() == 0 ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of input streams! " ); + log( LOG_ERROR, "Invalid number of input streams! " ); return 2; } Int64 currFrames = 0; @@ -160,34 +160,34 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) if( currFrames < numberOfFrames ) numberOfFrames = currFrames; } - m_iFrameNum = m_cCmdLineHandler.m_iFrames; + m_iFrameNum = m_iFrames; if( !( m_iFrameNum >= 0 && m_iFrameNum < numberOfFrames ) ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid frame number! Use --frame option " ); + log( LOG_ERROR, "Invalid frame number! Use --frame option " ); return 2; } - if( m_cCmdLineHandler.Opts().hasOpt( "output" ) ) - m_pcOutputFileNames.push_back( m_cCmdLineHandler.m_strOutput ); + if( Opts().hasOpt( "output" ) ) + m_pcOutputFileNames.push_back( m_strOutput ); if( m_pcOutputFileNames.size() != m_apcInputStreams.size() ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of outputs! Each input must have an output filename. " ); + log( LOG_ERROR, "Invalid number of outputs! Each input must have an output filename. " ); return 2; } m_uiOperation = SAVE_OPERATION; m_fpProcess = &PlaYUVerTools::SaveOperation; - m_cCmdLineHandler.log( LOG_INFO, "PlaYUVer Save Frame\n" ); + log( LOG_INFO, "PlaYUVer Save Frame\n" ); } /** * Check Quality operation */ - if( m_cCmdLineHandler.Opts().hasOpt( "quality" ) ) + if( Opts().hasOpt( "quality" ) ) { - String qualityMetric = m_cCmdLineHandler.m_strQualityMetric; + String qualityMetric = m_strQualityMetric; if( m_apcInputStreams.size() < 2 ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of inputs! " ); + log( LOG_ERROR, "Invalid number of inputs! " ); return 2; } for( UInt i = 0; i < PlaYUVerFrame::supportedQualityMetricsList().size(); i++ ) @@ -199,20 +199,20 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) } if( m_uiQualityMetric == -1 ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid quality metric! " ); + log( LOG_ERROR, "Invalid quality metric! " ); return 2; } m_uiOperation = QUALITY_OPERATION; m_fpProcess = &PlaYUVerTools::QualityOperation; - m_cCmdLineHandler.log( LOG_INFO, "PlaYUVer Quality\n" ); + log( LOG_INFO, "PlaYUVer Quality\n" ); } /** * Check Module operation */ - if( m_cCmdLineHandler.Opts().hasOpt( "module" ) ) + if( Opts().hasOpt( "module" ) ) { - String moduleName = m_cCmdLineHandler.m_strModule; + String moduleName = m_strModule; PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); PlaYUVerModuleFactoryMap::iterator it = PlaYUVerModuleFactoryMap.begin(); @@ -226,17 +226,17 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) } if( !m_pcCurrModuleIf ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid module! " ); + log( LOG_ERROR, "Invalid module! " ); return 2; } if( m_apcInputStreams.size() != m_pcCurrModuleIf->m_uiNumberOfFrames ) { - m_cCmdLineHandler.log( LOG_ERROR, "Invalid number of inputs! " ); + log( LOG_ERROR, "Invalid number of inputs! " ); return 2; } - m_pcCurrModuleIf->m_cModuleOptions.scanArgv( argc, ( const Char** )argv ); + m_pcCurrModuleIf->m_cModuleOptions.parse( argc, argv ); // Create Module Bool moduleCreated = false; @@ -256,7 +256,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) } if( !moduleCreated ) { - m_cCmdLineHandler.log( LOG_ERROR, "Module is not supported with the selected inputs! " ); + log( LOG_ERROR, "Module is not supported with the selected inputs! " ); return 2; } @@ -264,8 +264,8 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) { // Check outputs std::vector outputFileNames; - if( m_cCmdLineHandler.Opts().hasOpt( "output" ) ) - outputFileNames.push_back( m_cCmdLineHandler.m_strOutput ); + if( Opts().hasOpt( "output" ) ) + outputFileNames.push_back( m_strOutput ); if( outputFileNames.size() == 1 ) { @@ -279,7 +279,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) pcModFrame = applyFrameModule(); } PlaYUVerStream* pcModStream = new PlaYUVerStream; - if( !pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), 1, false ) ) + if( !pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), pcModFrame->getEndianness(), 1, false ) ) { delete pcModStream; pcModStream = NULL; @@ -289,19 +289,19 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) } else { - m_cCmdLineHandler.log( LOG_ERROR, "One output is required! " ); + log( LOG_ERROR, "One output is required! " ); return 2; } } m_uiOperation = MODULE_OPERATION; m_fpProcess = &PlaYUVerTools::ModuleOperation; - m_cCmdLineHandler.log( LOG_INFO, "PlaYUVer Module\n" ); + log( LOG_INFO, "PlaYUVer Module\n" ); } if( m_uiOperation == INVALID_OPERATION ) { - m_cCmdLineHandler.log( LOG_ERROR, "No operation was selected! " ); + log( LOG_ERROR, "No operation was selected! " ); return 2; } return iRet; @@ -361,19 +361,19 @@ Int PlaYUVerTools::QualityOperation() } metric_fmt += " "; - m_cCmdLineHandler.log( LOG_INFO, " Measuring Quality using %s ... \n", pchQualityMetricName ); - m_cCmdLineHandler.log( LOG_INFO, "# Frame ", pchQualityMetricName ); + log( LOG_INFO, " Measuring Quality using %s ... \n", pchQualityMetricName ); + log( LOG_INFO, "# Frame ", pchQualityMetricName ); for( UInt s = 1; s < m_apcInputStreams.size(); s++ ) { for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) { - m_cCmdLineHandler.log( LOG_INFO, "%s_%d_%d ", pchQualityMetricName, s, c ); + log( LOG_INFO, "%s_%d_%d ", pchQualityMetricName, s, c ); } - m_cCmdLineHandler.log( LOG_INFO, " " ); + log( LOG_INFO, " " ); } - m_cCmdLineHandler.log( LOG_INFO, "\n" ); + log( LOG_INFO, "\n" ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) { @@ -385,22 +385,22 @@ Int PlaYUVerTools::QualityOperation() } for( UInt frame = 0; frame < m_uiNumberOfFrames; frame++ ) { - m_cCmdLineHandler.log( LOG_INFO, " %3d ", frame ); + log( LOG_INFO, " %3d ", frame ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) apcCurrFrame[s] = m_apcInputStreams[s]->getCurrFrame(); for( UInt s = 1; s < m_apcInputStreams.size(); s++ ) { - m_cCmdLineHandler.log( LOG_RESULT, " " ); + log( LOG_RESULT, " " ); for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) { dQuality = apcCurrFrame[s]->getQuality( m_uiQualityMetric, apcCurrFrame[0], c ); adAverageQuality[s - 1][c] = ( adAverageQuality[s - 1][c] * Double( frame ) + dQuality ) / Double( frame + 1 ); - m_cCmdLineHandler.log( LOG_RESULT, metric_fmt.c_str(), dQuality ); + log( LOG_RESULT, metric_fmt.c_str(), dQuality ); } - m_cCmdLineHandler.log( LOG_RESULT, " " ); + log( LOG_RESULT, " " ); } - m_cCmdLineHandler.log( LOG_RESULT, "\n" ); + log( LOG_RESULT, "\n" ); for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) { abEOF[s] = m_apcInputStreams[s]->setNextFrame(); @@ -410,16 +410,16 @@ Int PlaYUVerTools::QualityOperation() } } } - m_cCmdLineHandler.log( LOG_INFO, "\n Mean Values: \n " ); + log( LOG_INFO, "\n Mean Values: \n " ); for( UInt s = 0; s < m_apcInputStreams.size() - 1; s++ ) { for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) { - m_cCmdLineHandler.log( LOG_INFO, metric_fmt.c_str(), adAverageQuality[s][c] ); + log( LOG_INFO, metric_fmt.c_str(), adAverageQuality[s][c] ); } - m_cCmdLineHandler.log( LOG_RESULT, " " ); + log( LOG_RESULT, " " ); } - m_cCmdLineHandler.log( LOG_INFO, "\n" ); + log( LOG_INFO, "\n" ); return 0; } @@ -436,7 +436,7 @@ PlaYUVerFrame* PlaYUVerTools::applyFrameModule() Int PlaYUVerTools::ModuleOperation() { std::vector apcFrameList; - m_cCmdLineHandler.log( LOG_INFO, " Applying Module %s/%s ...\n", m_pcCurrModuleIf->m_pchModuleCategory, m_pcCurrModuleIf->m_pchModuleName ); + log( LOG_INFO, " Applying Module %s/%s ...\n", m_pcCurrModuleIf->m_pchModuleCategory, m_pcCurrModuleIf->m_pchModuleName ); PlaYUVerFrame* pcProcessedFrame = NULL; Double dMeasurementResult = 0.0; @@ -477,8 +477,8 @@ Int PlaYUVerTools::ModuleOperation() { dMeasurementResult = m_pcCurrModuleIf->measure( m_apcInputStreams[0]->getCurrFrame() ); } - m_cCmdLineHandler.log( LOG_INFO, " %3d", frame ); - m_cCmdLineHandler.log( LOG_RESULT, " %8.3f \n", dMeasurementResult ); + log( LOG_INFO, " %3d", frame ); + log( LOG_RESULT, " %8.3f \n", dMeasurementResult ); dAveragedMeasurementResult = ( dAveragedMeasurementResult * Double( frame ) + dMeasurementResult ) / Double( frame + 1 ); } @@ -494,7 +494,7 @@ Int PlaYUVerTools::ModuleOperation() if( m_pcCurrModuleIf->m_iModuleType == FRAME_MEASUREMENT_MODULE ) { - m_cCmdLineHandler.log( LOG_INFO, "\n Mean Value: \n %8.3f\n", dAveragedMeasurementResult ); + log( LOG_INFO, "\n Mean Value: \n %8.3f\n", dAveragedMeasurementResult ); } return 0; diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index baf0fcd..1b8634f 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -36,7 +36,7 @@ class PlaYUVerModuleIf; #define MAX_NUMBER_INPUTS 10 -class PlaYUVerTools +class PlaYUVerTools: public PlaYUVerToolsCmdParser { public: PlaYUVerTools(); @@ -47,7 +47,6 @@ public: Int Close(); private: - PlaYUVerToolsCmdParser m_cCmdLineHandler; Bool m_bVerbose; UInt m_uiOperation; diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 1d5c1c1..012f492 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -36,6 +36,8 @@ PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() m_uiLogLevel = 0; m_bQuiet = false; m_iFrames = -1; + + m_cOptions.addDefaultOptions(); } PlaYUVerToolsCmdParser::~PlaYUVerToolsCmdParser() @@ -92,12 +94,6 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) m_cOptions.doHelp( std::cout ); iRet = 1; } - - if( m_cOptions.hasOpt("module_list") || m_cOptions.hasOpt("module_list_full") ) - { - m_cOptions.listModules(); - iRet = 1; - } return iRet; } diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 0796fd2..6aa4e12 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -34,7 +34,6 @@ class PlaYUVerStream; class PlaYUVerToolsCmdParser { - friend class PlaYUVerTools; public: PlaYUVerToolsCmdParser(); ~PlaYUVerToolsCmdParser(); @@ -65,7 +64,7 @@ public: return m_cOptions; } -private: +protected: PlaYUVerOptions m_cOptions; UInt m_uiLogLevel; diff --git a/tools/main.cpp b/tools/main.cpp index 6a4088e..97fbaf7 100644 --- a/tools/main.cpp +++ b/tools/main.cpp @@ -25,7 +25,7 @@ #include "PlaYUVerTools.h" -int main( int argc, char *argv[] ) +int main( int argc, Char *argv[] ) { Int iRet = 0; PlaYUVerTools PlaYUVerToolsApp; From 8e4812005708836f4cace4d1d580c0c773b07a5e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 3 May 2016 18:38:26 +0100 Subject: [PATCH 052/127] Change interface with opencv in PlaYUVerFrame Replace pointers with references --- lib/PlaYUVerFrame.cpp | 35 +++++++++++++++++---------------- lib/PlaYUVerFrame.h | 4 ++-- lib/StreamHandlerOpenCV.cpp | 33 ++++++++++++------------------- lib/StreamHandlerOpenCV.h | 1 - modules/DisparityStereoBM.cpp | 13 +++++++----- modules/DisparityStereoSGBM.cpp | 17 ++++++++-------- 6 files changed, 49 insertions(+), 54 deletions(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 0f5b2c4..74f9522 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1039,16 +1039,17 @@ Double PlaYUVerFrame::getMaximum( Int channel ) ************************************************************** */ -cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) +Bool PlaYUVerFrame::toMat( cv::Mat& cvMat, Bool convertToGray ) { + Bool bRet = false; #ifdef USE_OPENCV if( convertToGray && !( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) ) { - return NULL; + return bRet; } Int cvType = CV_MAKETYPE( CV_8U, convertToGray ? 1 : d->m_pcPelFormat->numberChannels ); - cv::Mat *pcCvFrame = new cv::Mat( d->m_uiHeight, d->m_uiWidth, cvType ); - UChar* pCvPel = pcCvFrame->data; + cvMat.create( d->m_uiHeight, d->m_uiWidth, cvType ); + UChar* pCvPel = cvMat.data; if( !convertToGray && ( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) ) { fillRGBBuffer(); @@ -1060,6 +1061,7 @@ cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) *pCvPel++ = *pARGB++; pARGB++; } + bRet = true; } else if( convertToGray || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) { @@ -1068,27 +1070,25 @@ cv::Mat* PlaYUVerFrame::getCvMat( Bool convertToGray ) { *pCvPel++ = *pPel++; } + bRet = true; } else { - if( pcCvFrame ) - delete pcCvFrame; - pcCvFrame = NULL; + return false; } - return pcCvFrame; -#else - return NULL; #endif + return bRet; } -Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) +Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) { + Bool bRet = false; #ifdef USE_OPENCV if( !d->m_bInit ) { if( d->m_iPixelFormat == NO_FMT ) { - switch( pcCvFrame->channels() ) + switch( cvMat.channels() ) { case 1: d->m_iPixelFormat = findPixelFormat( "GRAY" ); @@ -1097,16 +1097,16 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) d->m_iPixelFormat = findPixelFormat( "BGR24" ); break; default: - return; + return false; } } - d->init( pcCvFrame->cols, pcCvFrame->rows, d->m_iPixelFormat, 8, -1 ); + d->init( cvMat.cols, cvMat.rows, d->m_iPixelFormat, 8, -1 ); } d->m_bHasRGBPel = false; d->m_bHasHistogram = false; - UChar* pCvPel = pcCvFrame->data; + UChar* pCvPel = cvMat.data; if( d->m_iPixelFormat != GRAY ) { Pel* pInputPelR = d->m_pppcInputPel[COLOR_R][0]; @@ -1117,9 +1117,8 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) *pInputPelB++ = *pCvPel++; *pInputPelG++ = *pCvPel++; *pInputPelR++ = *pCvPel++; - - } + bRet = true; } else { @@ -1128,8 +1127,10 @@ Void PlaYUVerFrame::fromCvMat( cv::Mat* pcCvFrame ) { *pPel++ = *pCvPel++; } + bRet = true; } #endif + return bRet; } /* diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index d10a883..69b62f7 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -232,8 +232,8 @@ public: /** * Interface with OpenCV lib */ - cv::Mat* getCvMat( Bool convertToGray = false ); - Void fromCvMat( cv::Mat* ); + Bool toMat( cv::Mat& cvMat, Bool convertToGray = false ); + Bool fromMat( cv::Mat& cvMat ); /** * @defgroup PlaYUVerLib_QualityMetrics Quality Metrics Interface diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 43aa139..d5d762f 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -36,7 +36,7 @@ using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -44,8 +44,8 @@ std::vector StreamHandlerOpenCV::supportedReadFormats() std::vector StreamHandlerOpenCV::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - APPEND_PLAYUVER_SUPPORTED_FMT( StreamHandlerOpenCV, Read ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable PixMap ", "ppm" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -53,7 +53,6 @@ std::vector StreamHandlerOpenCV::supportedWriteFormats( StreamHandlerOpenCV::StreamHandlerOpenCV() { - pcMat = NULL; pcVideoCapture = NULL; } @@ -62,8 +61,6 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) m_cFilename = strFilename; if( bInput ) { - - /* * Special filename to handle webcam input */ @@ -79,9 +76,9 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) else { m_strCodecName = m_strFormatName = uppercase (strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); - pcMat = new Mat( cv::imread( m_cFilename ) ); - m_uiWidth = pcMat->cols; - m_uiHeight = pcMat->rows; + Mat cvMat = cv::imread( m_cFilename ); + m_uiWidth = cvMat.cols; + m_uiHeight = cvMat.rows; m_dFrameRate = 1; } m_uiBitsPerPixel = 8; @@ -99,10 +96,6 @@ Void StreamHandlerOpenCV::closeHandler() delete pcVideoCapture; pcVideoCapture = NULL; } - if( pcMat ) - { - delete pcMat; - } } Bool StreamHandlerOpenCV::configureBuffer( PlaYUVerFrame* pcFrame ) @@ -132,12 +125,12 @@ Bool StreamHandlerOpenCV::read( PlaYUVerFrame* pcFrame ) Mat cvMat; bRet = pcVideoCapture->read( cvMat ); if( bRet ) - pcFrame->fromCvMat( &cvMat ); + bRet = pcFrame->fromMat( cvMat ); } - if( pcMat ) + else { - pcFrame->fromCvMat( pcMat ); - bRet = true; + Mat cvMat = cv::imread( m_cFilename ); + bRet = pcFrame->fromMat( cvMat ); } return bRet; } @@ -145,11 +138,11 @@ Bool StreamHandlerOpenCV::read( PlaYUVerFrame* pcFrame ) Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) { Bool bRet = false; - cv::Mat* pcCvFrame = pcFrame->getCvMat(); - if( pcCvFrame ) + Mat cvFrame; + bRet = pcFrame->toMat( cvFrame ); + if( bRet ) { - bRet = cv::imwrite( m_cFilename, *pcCvFrame ); - delete pcCvFrame; + bRet = cv::imwrite( m_cFilename, cvFrame ); } return bRet; } diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index acb769a..0a661fe 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -65,7 +65,6 @@ public: private: cv::VideoCapture* pcVideoCapture; - cv::Mat* pcMat; }; #endif // __STREAMHANDLEROPENCV_H__ diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index ffdbae7..2ac0e0a 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -85,19 +85,22 @@ PlaYUVerFrame* DisparityStereoBM::process( std::vector apcFrameL PlaYUVerFrame* InputLeft = apcFrameList[0]; PlaYUVerFrame* InputRight = apcFrameList[1]; - cv::Mat* leftImage = InputLeft->getCvMat( true ); - cv::Mat* rightImage = InputRight->getCvMat( true ); + cv::Mat leftImage, rightImage; + if( !InputLeft->toMat( leftImage, true ) || !InputRight->toMat( rightImage, true ) ) + { + return m_pcDisparityFrame; + } cv::Mat disparityImage, disparityImage8; #if( CV_MAJOR_VERSION == 2) - m_cStereoBM( *leftImage, *rightImage, disparityImage ); + m_cStereoBM( leftImage, rightImage, disparityImage ); #else - m_cStereoBM->compute( *leftImage, *rightImage, disparityImage ); + m_cStereoBM->compute( leftImage, rightImage, disparityImage ); #endif disparityImage.convertTo( disparityImage8, CV_8U ); - m_pcDisparityFrame->fromCvMat( &disparityImage8 ); + m_pcDisparityFrame->fromMat( disparityImage8 ); return m_pcDisparityFrame; } diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index 064dc1a..c6065fd 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -91,20 +91,19 @@ PlaYUVerFrame* DisparityStereoSGBM::process( std::vector apcFram { PlaYUVerFrame* InputLeft = apcFrameList[0]; PlaYUVerFrame* InputRight = apcFrameList[1]; - - cv::Mat* leftImage = InputLeft->getCvMat( true ); - cv::Mat* rightImage = InputRight->getCvMat( true ); + cv::Mat leftImage, rightImage; + if( !InputLeft->toMat( leftImage, true ) || !InputRight->toMat( rightImage, true ) ) + { + return m_pcDisparityFrame; + } cv::Mat disparityImage, disparityImage8; - #if( CV_MAJOR_VERSION == 3) - m_cStereoMatch->compute( *leftImage, *rightImage, disparityImage ); + m_cStereoMatch->compute( leftImage, rightImage, disparityImage ); #else - m_cStereoMatch( *leftImage, *rightImage, disparityImage ); + m_cStereoMatch( leftImage, rightImage, disparityImage ); #endif - disparityImage.convertTo( disparityImage8, CV_8U ); - - m_pcDisparityFrame->fromCvMat( &disparityImage8 ); + m_pcDisparityFrame->fromMat( disparityImage8 ); return m_pcDisparityFrame; } From 831c04bee3f158f8d233c2cf380ee77ea266114b Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 3 May 2016 19:01:56 +0100 Subject: [PATCH 053/127] Add dual TVL1 optical flow algoritm --- modules/CMakeLists.txt | 1 + modules/OpticalFlowDualTVL1.cpp | 123 ++++++++++++++++++++++++++++++++ modules/OpticalFlowDualTVL1.h | 54 ++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 modules/OpticalFlowDualTVL1.cpp create mode 100644 modules/OpticalFlowDualTVL1.h diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 7bb3718..1971450 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -41,6 +41,7 @@ ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) ADD_MODULE( WeightedPSNR "WeightedPSNR" ) IF( USE_OPENCV ) + ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" ) ADD_MODULE( DisparityStereoBM "DisparityStereoBM" ) ADD_MODULE( DisparityStereoSGBM "DisparityStereoSGBM" ) #ADD_MODULE( DisparityStereoVar "DisparityStereoVar" ) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp new file mode 100644 index 0000000..8f3f580 --- /dev/null +++ b/modules/OpticalFlowDualTVL1.cpp @@ -0,0 +1,123 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file OpticalFlowDualTVL1.cpp + * \brief Absolute Frame Difference module + */ + +#include "OpticalFlowDualTVL1.h" +#include + +using cv::Scalar; +using cv::Mat; +using cv::Mat_; +using cv::Ptr; +using cv::Point; +using cv::Point2f; + + + +OpticalFlowDualTVL1::OpticalFlowDualTVL1() +{ + /* Module Definition */ + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + // See this example for details on the functions prototype + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "OpticalFlowDualTVL1"; // Name + m_pchModuleTooltip = "Measure optical flow"; // Description + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW; + m_pcOutputFrame = NULL; +} + +Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) +{ + _BASIC_MODULE_API_2_CHECK_ + + for( UInt i = 1; i < apcFrameList.size(); i++ ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + return false; + + m_iStep = 16; + m_cTvl1 = cv::createOptFlow_DualTVL1(); + m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + + return true; +} + +inline bool isFlowCorrect( Point2f u ) +{ + return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; +} + +PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) +{ + Mat cvMatPrev, cvMatAfter; + if( !apcFrameList[0]->toMat( cvMatPrev, true ) || !apcFrameList[1]->toMat( cvMatAfter, true ) ) + { + return m_pcOutputFrame; + } + + Mat_ flow; + m_cTvl1->calc( cvMatPrev, cvMatAfter, flow ); + + + // determine motion range: + Double maxrad = 1; + + for( int y = 0; y < flow.rows; y++ ) + { + for( int x = 0; x < flow.cols; x++ ) + { + Point2f u = flow( y, x ); + if( !isFlowCorrect( u ) ) + continue; + maxrad = cv::max( maxrad, sqrt( u.x * u.x + u.y * u.y ) ); + } + } + + Scalar vectorColor( 255,0,0,0 ); + for( int y = 0; y < flow.rows; y+=m_iStep ) + { + for( int x = 0; x < flow.cols; x+=m_iStep ) + { + Point p = Point( x,y ); + Point2f u = flow( y, x ); + Point ui( u.x, u.y ); + + if( isFlowCorrect( u ) ) + arrowedLine( cvMatAfter, p, p+ui, vectorColor ); + } + } + + m_pcOutputFrame->fromMat( cvMatAfter ); + return m_pcOutputFrame; +} + +Void OpticalFlowDualTVL1::destroy() +{ + if( m_pcOutputFrame ) + delete m_pcOutputFrame; + m_pcOutputFrame = NULL; +} + + + diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h new file mode 100644 index 0000000..5c77981 --- /dev/null +++ b/modules/OpticalFlowDualTVL1.h @@ -0,0 +1,54 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file OpticalFlowDualTVL1.h + * \brief Absolute Frame Difference module + */ + +#ifndef __OPTICALFLOWDUALTVL1_H__ +#define __OPTICALFLOWDUALTVL1_H__ + +#include + +#include "lib/PlaYUVerModuleIf.h" + + +class OpticalFlowDualTVL1: public PlaYUVerModuleIf +{ +REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) + +private: + Int m_iStep; + cv::Ptr m_cTvl1; + PlaYUVerFrame* m_pcOutputFrame; + +public: + OpticalFlowDualTVL1(); + virtual ~OpticalFlowDualTVL1() + { + } + Bool create( std::vector apcFrameList ); + PlaYUVerFrame* process( std::vector apcFrameList ); + Void destroy(); + +}; + +#endif // __OPTICALFLOWDUALTVL1_H__ + From 137bfa0dcf17f4b92597e6e8e2a06a8d228977f1 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 3 May 2016 19:13:40 +0100 Subject: [PATCH 054/127] make function in OpticalFlowDualTVL1 static --- modules/OpticalFlowDualTVL1.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index 8f3f580..a83936e 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -63,7 +63,7 @@ Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) return true; } -inline bool isFlowCorrect( Point2f u ) +static inline bool isFlowCorrect( Point2f u ) { return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; } From 399065965bfd6f27a58a15623d7cbbb6ae334e98 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 00:47:08 +0100 Subject: [PATCH 055/127] Change the start point of optical flow draw --- modules/OpticalFlowDualTVL1.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index a83936e..d2a8508 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -95,9 +95,9 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram } Scalar vectorColor( 255,0,0,0 ); - for( int y = 0; y < flow.rows; y+=m_iStep ) + for( int y = m_iStep / 2; y < flow.rows; y += m_iStep ) { - for( int x = 0; x < flow.cols; x+=m_iStep ) + for( int x = m_iStep / 2; x < flow.cols; x += m_iStep ) { Point p = Point( x,y ); Point2f u = flow( y, x ); From 501e24fc5d28867ab267fb9a7614b4ba4fc8c1e9 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 01:50:12 +0100 Subject: [PATCH 056/127] Clean some comments --- Doxyfile | 128 +++++++++++++++--------------- lib/CMakeLists.txt | 3 +- lib/PlaYUVerDefs.h | 1 + lib/PlaYUVerFrame.cpp | 14 ++-- lib/PlaYUVerFrame.h | 25 +++--- lib/PlaYUVerFramePixelFormats.cpp | 10 ++- lib/PlaYUVerFramePixelFormats.h | 4 +- lib/PlaYUVerLib.h | 11 ++- lib/PlaYUVerModuleIf.h | 47 +++++++++-- lib/PlaYUVerOptions.cpp | 2 +- lib/PlaYUVerOptions.h | 2 +- lib/PlaYUVerPixel.cpp | 1 - lib/PlaYUVerPixel.h | 1 - lib/PlaYUVerStream.cpp | 17 ++-- lib/PlaYUVerStream.h | 7 +- lib/PlaYUVerStreamHandlerIf.h | 2 +- lib/StreamHandlerLibav.cpp | 1 - lib/StreamHandlerLibav.h | 11 ++- lib/StreamHandlerOpenCV.cpp | 1 - lib/StreamHandlerOpenCV.h | 1 - lib/StreamHandlerPortableMap.cpp | 3 +- lib/StreamHandlerPortableMap.h | 3 +- lib/StreamHandlerRaw.cpp | 15 ++-- lib/StreamHandlerRaw.h | 11 ++- 24 files changed, 168 insertions(+), 153 deletions(-) diff --git a/Doxyfile b/Doxyfile index f0930c2..d9522cd 100644 --- a/Doxyfile +++ b/Doxyfile @@ -38,13 +38,13 @@ PROJECT_NAME = PlaYUVer # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = +PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. -PROJECT_BRIEF = +PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 @@ -162,7 +162,7 @@ FULL_PATH_NAMES = YES # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. -STRIP_FROM_PATH = +STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which @@ -171,7 +171,7 @@ STRIP_FROM_PATH = # specify the list of include paths that are normally passed to the compiler # using the -I flag. -STRIP_FROM_INC_PATH = +STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't @@ -244,7 +244,7 @@ ALIASES = "returns=\"\par Returns\" " # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. -TCL_SUBST = +TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For @@ -291,7 +291,7 @@ OPTIMIZE_OUTPUT_VHDL = NO # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. -EXTENSION_MAPPING = +EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable @@ -554,7 +554,7 @@ INLINE_INFO = YES # name. If set to NO, the members will appear in declaration order. # The default value is: YES. -SORT_MEMBER_DOCS = YES +SORT_MEMBER_DOCS = NO # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member @@ -632,7 +632,7 @@ GENERATE_DEPRECATEDLIST= YES # sections, marked by \if ... \endif and \cond # ... \endcond blocks. -ENABLED_SECTIONS = +ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the @@ -674,7 +674,7 @@ SHOW_NAMESPACES = YES # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. -FILE_VERSION_FILTER = +FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated @@ -687,7 +687,7 @@ FILE_VERSION_FILTER = # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. -LAYOUT_FILE = +LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib @@ -697,7 +697,7 @@ LAYOUT_FILE = # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. -CITE_BIB_FILES = +CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages @@ -756,7 +756,7 @@ WARN_FORMAT = "$file:$line: $text" # messages should be written. If left blank the output is written to standard # error (stderr). -WARN_LOGFILE = +WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files @@ -768,7 +768,7 @@ WARN_LOGFILE = # spaces. # Note: If this tag is empty the current directory is searched. -INPUT = +INPUT = # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -869,7 +869,7 @@ EXCLUDE_SYMLINKS = NO # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* -EXCLUDE_PATTERNS = +EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the @@ -880,13 +880,13 @@ EXCLUDE_PATTERNS = # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* -EXCLUDE_SYMBOLS = +EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). -EXAMPLE_PATH = +EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and @@ -906,7 +906,7 @@ EXAMPLE_RECURSIVE = NO # that contain images that are to be included in the documentation (see the # \image command). -IMAGE_PATH = +IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program @@ -923,7 +923,7 @@ IMAGE_PATH = # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. -INPUT_FILTER = +INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the @@ -932,7 +932,7 @@ INPUT_FILTER = # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. -FILTER_PATTERNS = +FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for @@ -947,14 +947,14 @@ FILTER_SOURCE_FILES = NO # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. -FILTER_SOURCE_PATTERNS = +FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing @@ -1066,7 +1066,7 @@ COLS_IN_ALPHA_INDEX = 5 # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. -IGNORE_PREFIX = +IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output @@ -1110,7 +1110,7 @@ HTML_FILE_EXTENSION = .html # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_HEADER = +HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard @@ -1120,7 +1120,7 @@ HTML_HEADER = # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_FOOTER = +HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of @@ -1132,7 +1132,7 @@ HTML_FOOTER = # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_STYLESHEET = +HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets @@ -1145,7 +1145,7 @@ HTML_STYLESHEET = # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_STYLESHEET = +HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note @@ -1155,7 +1155,7 @@ HTML_EXTRA_STYLESHEET = # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_FILES = +HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to @@ -1283,7 +1283,7 @@ GENERATE_HTMLHELP = NO # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_FILE = +CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, @@ -1291,7 +1291,7 @@ CHM_FILE = # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -HHC_LOCATION = +HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). @@ -1304,7 +1304,7 @@ GENERATE_CHI = NO # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_INDEX_ENCODING = +CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it @@ -1335,7 +1335,7 @@ GENERATE_QHP = NO # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. -QCH_FILE = +QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace @@ -1360,7 +1360,7 @@ QHP_VIRTUAL_FOLDER = doc # filters). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_CUST_FILTER_NAME = +QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom @@ -1368,21 +1368,21 @@ QHP_CUST_FILTER_NAME = # filters). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_CUST_FILTER_ATTRS = +QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_SECT_FILTER_ATTRS = +QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. -QHG_LOCATION = +QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To @@ -1515,7 +1515,7 @@ MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_EXTENSIONS = +MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site @@ -1523,7 +1523,7 @@ MATHJAX_EXTENSIONS = # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_CODEFILE = +MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and @@ -1583,7 +1583,7 @@ EXTERNAL_SEARCH = NO # Searching" for details. # This tag requires that the tag SEARCHENGINE is set to YES. -SEARCHENGINE_URL = +SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the @@ -1599,7 +1599,7 @@ SEARCHDATA_FILE = searchdata.xml # projects and redirect the results back to the right project. # This tag requires that the tag SEARCHENGINE is set to YES. -EXTERNAL_SEARCH_ID = +EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are @@ -1609,7 +1609,7 @@ EXTERNAL_SEARCH_ID = # EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... # This tag requires that the tag SEARCHENGINE is set to YES. -EXTRA_SEARCH_MAPPINGS = +EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # Configuration options related to the LaTeX output @@ -1670,7 +1670,7 @@ PAPER_TYPE = a4wide # If left blank no extra packages will be included. # This tag requires that the tag GENERATE_LATEX is set to YES. -EXTRA_PACKAGES = +EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for the # generated LaTeX document. The header should contain everything until the first @@ -1686,7 +1686,7 @@ EXTRA_PACKAGES = # to HTML_HEADER. # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_HEADER = +LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the # generated LaTeX document. The footer should contain everything after the last @@ -1697,7 +1697,7 @@ LATEX_HEADER = # Note: Only use a user-defined footer if you know what you are doing! # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_FOOTER = +LATEX_FOOTER = # The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined # LaTeX style sheets that are included after the standard style sheets created @@ -1708,7 +1708,7 @@ LATEX_FOOTER = # list). # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_EXTRA_STYLESHEET = +LATEX_EXTRA_STYLESHEET = # The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the LATEX_OUTPUT output @@ -1716,7 +1716,7 @@ LATEX_EXTRA_STYLESHEET = # markers available. # This tag requires that the tag GENERATE_LATEX is set to YES. -LATEX_EXTRA_FILES = +LATEX_EXTRA_FILES = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is # prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will @@ -1816,14 +1816,14 @@ RTF_HYPERLINKS = NO # default style sheet that doxygen normally uses. # This tag requires that the tag GENERATE_RTF is set to YES. -RTF_STYLESHEET_FILE = +RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an RTF document. Syntax is # similar to doxygen's config file. A template extensions file can be generated # using doxygen -e rtf extensionFile. # This tag requires that the tag GENERATE_RTF is set to YES. -RTF_EXTENSIONS_FILE = +RTF_EXTENSIONS_FILE = # If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code # with syntax highlighting in the RTF output. @@ -1868,7 +1868,7 @@ MAN_EXTENSION = .3 # MAN_EXTENSION with the initial . removed. # This tag requires that the tag GENERATE_MAN is set to YES. -MAN_SUBDIR = +MAN_SUBDIR = # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real @@ -1981,7 +1981,7 @@ PERLMOD_PRETTY = YES # overwrite each other's variables. # This tag requires that the tag GENERATE_PERLMOD is set to YES. -PERLMOD_MAKEVAR_PREFIX = +PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor @@ -2022,7 +2022,7 @@ SEARCH_INCLUDES = YES # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. -INCLUDE_PATH = +INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the @@ -2030,7 +2030,7 @@ INCLUDE_PATH = # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -INCLUDE_FILE_PATTERNS = +INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. @@ -2040,7 +2040,7 @@ INCLUDE_FILE_PATTERNS = # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -PREDEFINED = +PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The @@ -2049,7 +2049,7 @@ PREDEFINED = # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_AS_DEFINED = +EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will # remove all references to function-like macros that are alone on a line, have @@ -2078,13 +2078,13 @@ SKIP_FUNCTION_MACROS = YES # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. -TAGFILES = +TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create a # tag file that is based on the input files it reads. See section "Linking to # external documentation" for more information about the usage of tag files. -GENERATE_TAGFILE = +GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES, all external class will be listed in # the class index. If set to NO, only the inherited external classes will be @@ -2133,14 +2133,14 @@ CLASS_DIAGRAMS = YES # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. -MSCGEN_PATH = +MSCGEN_PATH = # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The # DIA_PATH tag allows you to specify the directory where the dia binary resides. # If left empty dia is assumed to be found in the default search path. -DIA_PATH = +DIA_PATH = # If set to YES the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. @@ -2189,7 +2189,7 @@ DOT_FONTSIZE = 10 # the path where dot can find it using this tag. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_FONTPATH = +DOT_FONTPATH = # If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for # each documented class showing the direct and indirect inheritance relations. @@ -2327,26 +2327,26 @@ INTERACTIVE_SVG = NO # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_PATH = +DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile # command). # This tag requires that the tag HAVE_DOT is set to YES. -DOTFILE_DIRS = +DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the \mscfile # command). -MSCFILE_DIRS = +MSCFILE_DIRS = # The DIAFILE_DIRS tag can be used to specify one or more directories that # contain dia files that are included in the documentation (see the \diafile # command). -DIAFILE_DIRS = +DIAFILE_DIRS = # When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the # path where java can find the plantuml.jar file. If left blank, it is assumed @@ -2354,12 +2354,12 @@ DIAFILE_DIRS = # generate a warning when it encounters a \startuml command in this case and # will not generate output for the diagram. -PLANTUML_JAR_PATH = +PLANTUML_JAR_PATH = # When using plantuml, the specified paths are searched for files specified by # the !include statement in a plantuml block. -PLANTUML_INCLUDE_PATH = +PLANTUML_INCLUDE_PATH = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 32da862..5e03600 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -13,9 +13,8 @@ set(PlaYUVer_Lib_SRCS PlaYUVerStream.cpp StreamHandlerRaw.cpp StreamHandlerPortableMap.cpp - # Command Parser + # Options Parser PlaYUVerOptions.cpp -# PlaYUVerCmdParser.cpp ) IF( USE_FFMPEG ) diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index b89e5f2..ef182f7 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -27,6 +27,7 @@ #define __PLAYUVERDEFS_H__ #include +#include #include diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 74f9522..6f26d66 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -19,23 +19,19 @@ /** * \file PlaYUVerFrame.cpp - * \ingroup PlaYUVerLib * \brief Video Frame handling */ #include "config.h" -#include -#include -#include "LibMemory.h" #include "PlaYUVerFrame.h" -#include "PlaYUVerFramePixelFormats.h" -#ifdef USE_FFMPEG -#include "StreamHandlerLibav.h" -#endif + +#include #ifdef USE_OPENCV -#include "StreamHandlerOpenCV.h" +#include #endif +#include "LibMemory.h" +#include "PlaYUVerFramePixelFormats.h" /*! \brief Supported formats * diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 69b62f7..a9a11db 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -19,21 +19,15 @@ /** * \file PlaYUVerFrame.h - * \ingroup PlaYUVerLib * \brief Video Frame handling */ #ifndef __PLAYUVERFRAME_H__ #define __PLAYUVERFRAME_H__ -#include -#include -#include -#include #include "PlaYUVerDefs.h" #include "PlaYUVerPixel.h" - namespace cv { class Mat; @@ -51,7 +45,6 @@ struct PlaYUVerFramePrivate; * \brief Frame handling class */ class PlaYUVerFrame -//: public PlaYUVerFrameStats { public: @@ -133,8 +126,6 @@ public: ~PlaYUVerFrame(); - Void clear(); - Bool haveSameFmt( PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; /** @@ -144,11 +135,13 @@ public: Int getPelFormat() const; /** + * Get pixel format information * @return pixel format name */ String getPelFmtName(); /** + * Get color space information * @return get color space index * @ */ @@ -198,6 +191,11 @@ public: */ static UInt64 getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ); + /** + * Reset frame pixels to zero + */ + Void clear(); + Pel*** getPelBufferYUV() const; Pel*** getPelBufferYUV(); UChar* getRGBBuffer() const; @@ -236,16 +234,13 @@ public: Bool fromMat( cv::Mat& cvMat ); /** - * @defgroup PlaYUVerLib_QualityMetrics Quality Metrics Interface + * \ingroup PlaYUVerLib_Frame + * @defgroup PlaYUVerLib_Frame_QualityMetrics Quality Metrics Interface * @{ - * \ingroup PlaYUVerLib * Quality metrics interface * - * @} */ - //! @ingroup PlaYUVerLib_QualityMetrics - //! @{ enum QualityMetrics { NO_METRIC = -1, @@ -269,7 +264,7 @@ public: Double getPSNR( PlaYUVerFrame* Org, Int component ); Double getSSIM( PlaYUVerFrame* Org, Int component ); - //! @} + /** @} */ private: PlaYUVerFramePrivate* d; diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 3ee8b12..c4f8790 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -19,22 +19,24 @@ /** * \file PlaYUVerFramePixelFormats.cpp - * \ingroup PlaYUVerLib * \brief Handling the pixel formats definition */ #include "config.h" -#include -#include "LibMemory.h" +#include "PlaYUVerFramePixelFormats.h" +// #include + #ifdef USE_SSE #include #include #include #endif + +#include "LibMemory.h" #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" #endif -#include "PlaYUVerFramePixelFormats.h" + /* diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index 5dfe062..ae7c3b8 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -19,7 +19,6 @@ /** * \file PlaYUVerFramePixelFormats.h - * \ingroup PlaYUVerLib * \brief Handling the pixel formats definition */ @@ -27,9 +26,8 @@ #define __PLAYUVERFRAMEPIXELFORMATS_H__ #include "PlaYUVerDefs.h" -#include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" - +#include "PlaYUVerFrame.h" #define CHROMA_RESAMPLING( X ) ( ( ( X + 1 ) >> 1 ) << 1 ) diff --git a/lib/PlaYUVerLib.h b/lib/PlaYUVerLib.h index 4aede6b..e64d719 100644 --- a/lib/PlaYUVerLib.h +++ b/lib/PlaYUVerLib.h @@ -19,7 +19,6 @@ /** * \file PlaYUVerLib.h - * \ingroup PlaYUVerLib * \brief Inlcude all modules of PlaYUVer Lib */ @@ -40,16 +39,16 @@ * This guaratees that the top-level applications does not need to worry * about dealig with different stream formats as well as different pixel formats * - * @defgroup PlaYUVerLib_Stream PlaYUVer Stream - * @{ - * Describe PlaYUVerStream - * @} - * * @defgroup PlaYUVerLib_Frame PlaYUVer Frame * @{ * Describe PlaYUVerFrame * @} * + * @defgroup PlaYUVerLib_Stream PlaYUVer Stream + * @{ + * Describe PlaYUVerStream + * @} + * * @} * */ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index 84bd99e..17e9a76 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -19,12 +19,22 @@ /** * \file PlaYUVerModuleIf.h + * \ingroup PlaYUVerLib_Modules * \brief PlaYUVer modules interface */ #ifndef __PLAYUVERMODULESIF_H__ #define __PLAYUVERMODULESIF_H__ +/** + * \ingroup PlaYUVerLib + * @defgroup PlaYUVerLib_Modules PlaYUVer Modules + * @{ + * PlaYUVerLib supports the creation of independent + * frame processing modules + * @} + */ + #include "PlaYUVerDefs.h" #include "PlaYUVerFrame.h" #include "PlaYUVerOptions.h" @@ -46,31 +56,48 @@ for( UInt i = 0; i < apcFrameList.size(); i++ ) \ if( !apcFrameList[i] ) \ return false; -enum // Module API +/** Module_API_Version Enum + * \ingroup PlaYUVerLib_Modules + * Version of the modules API required + * @see m_iModuleAPI + */ +enum Module_API_Version { MODULE_API_1, MODULE_API_2, }; -enum // Module type +/** Module_Type Enum + * \ingroup PlaYUVerLib_Modules + * Type of module + * @see m_iModuleType + */ +enum Module_Type { FRAME_PROCESSING_MODULE, FRAME_MEASUREMENT_MODULE, }; -#define APPLY_WHILE_PLAYING true #define MAX_NUMBER_FRAMES 3 +/** Module_NumberOfFrames Enum + * \ingroup PlaYUVerLib_Modules + * Number of frames requires by a module + * @see m_uiNumberOfFrames + */ enum Module_NumberOfFrames { MODULE_REQUIRES_ONE_FRAME = 1, MODULE_REQUIRES_TWO_FRAMES, MODULE_REQUIRES_THREE_FRAMES, - MODULE_REQUIRES_FOUR_FRAMES, - MODULE_REQUIRES_FIVE_FRAMES, - MODULE_REQUIRES_SIX_FRAMES, + MODULE_REQUIRES_MAX_FRAMES = 255, }; +/** Module_Features Enum + * \ingroup PlaYUVerLib_Modules + * Features/Requirements of a module + * @see m_uiModuleRequirements + */ enum Module_Features { MODULE_REQUIRES_NOTHING = 0, @@ -89,6 +116,11 @@ enum Module_Key_Supported }; +/** + * \class PlaYUVerModuleIf + * \ingroup PlaYUVerLib PlaYUVerLib_Modules + * \brief Abstract class for modules + */ class PlaYUVerModuleIf { public: @@ -98,7 +130,10 @@ public: const Char* m_pchModuleCategory; const Char* m_pchModuleName; const Char* m_pchModuleTooltip; + + //! Number of frames enum Module_NumberOfFrames m_uiNumberOfFrames; + //! Features/Requirements UInt m_uiModuleRequirements; PlaYUVerOptions m_cModuleOptions; diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index 68c57d3..079174d 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -33,7 +33,7 @@ /** * \file PlaYUVerOptions.cpp - * \brief Input args handler + * \brief Options handler */ #include "config.h" diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index 599e935..d51f31c 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -33,7 +33,7 @@ /** * \file PlaYUVerOptions.h - * \brief Input args handler + * \brief Options handler */ #ifndef __PROGRAMOPTIONS_H__ diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index f4b4e84..54e03c4 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -19,7 +19,6 @@ /** * \file PlaYUVerPixel.cpp - * \ingroup PlaYUVerLib * \brief Pixel handling */ diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 6461377..d6e7262 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -19,7 +19,6 @@ /** * \file PlaYUVerPixel.h - * \ingroup PlaYUVerLib * \brief Pixel handling */ diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index c7b1a3e..09cda71 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -19,19 +19,18 @@ /** * \file PlaYUVerStream.cpp - * \ingroup PlaYUVerLib * \brief Input stream handling */ #include "config.h" -#include -#include -#include "LibMemory.h" #include "PlaYUVerStream.h" + +#include + +#include "LibMemory.h" #include "PlaYUVerStreamHandlerIf.h" #include "StreamHandlerRaw.h" #include "StreamHandlerPortableMap.h" - #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" #endif @@ -43,8 +42,8 @@ std::vector PlaYUVerStream::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "gray" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "yuv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "gray" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); @@ -60,7 +59,7 @@ std::vector PlaYUVerStream::supportedReadFormats() std::vector PlaYUVerStream::supportedWriteFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &PlaYUVerRawHandler::Create, "Raw Video", "yuv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); #ifdef USE_FFMPEG @@ -124,7 +123,7 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo return supportedFmts[i].formatFct; } } - return &PlaYUVerRawHandler::Create; + return &StreamHandlerRaw::Create; } PlaYUVerStream::PlaYUVerStream() diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 690c2dc..f1f3089 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -19,7 +19,6 @@ /** * \file PlaYUVerStream.h - * \ingroup PlaYUVerLib * \brief Input stream handling */ @@ -27,13 +26,8 @@ #define __PLAYUVERSTREAM_H__ #include "PlaYUVerDefs.h" -#include -#include -#include #include "PlaYUVerFrame.h" - -class LibOpenCVHandler; class PlaYUVerStreamHandlerIf; typedef struct @@ -76,6 +70,7 @@ typedef struct /** * \class PlaYUVerStream * \ingroup PlaYUVerLib PlaYUVerLib_Stream + * \brief Stream handling class */ class PlaYUVerStream { diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 939471e..04bbab1 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -37,7 +37,7 @@ /** * \class PlaYUVerStreamHandlerIf - * \ingroup PlaYUVerLib PlaYUVerLib_Stream + * \ingroup PlaYUVerLib_Stream * \brief Abstract class for stream handling */ class PlaYUVerStreamHandlerIf diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index d62216e..55e1ac6 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -19,7 +19,6 @@ /** * \file StreamHandlerLibav.cpp - * \ingroup PlaYUVerLib * \brief Interface with libav libs */ diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 953c97e..9d10861 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -19,7 +19,6 @@ /** * \file StreamHandlerLibav.h - * \ingroup PlaYUVerLib * \brief Interface with libav libs */ @@ -43,7 +42,6 @@ extern "C" #include #include #include -//#include #include } @@ -52,6 +50,14 @@ extern "C" #include "PlaYUVerStreamHandlerIf.h" +struct AVFormatContext; +struct AVCodecContext; +struct AVStream; +struct AVStream; +struct AVPacket; + + + class StreamHandlerLibav: public PlaYUVerStreamHandlerIf { REGISTER_STREAM_HANDLER( StreamHandlerLibav ) @@ -85,7 +91,6 @@ public: UInt64 m_uiFrameBufferSize; private: - AVFormatContext* m_cFmtCtx; AVCodecContext* m_cCodecCtx; AVStream* m_cStream; diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index d5d762f..f424c96 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -19,7 +19,6 @@ /** * \file StreamHandlerOpenCV.cpp - * \ingroup PlaYUVerLib * \brief Interface with opencv lib */ diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index 0a661fe..f1ce3ef 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -19,7 +19,6 @@ /** * \file StreamHandlerOpenCV.h - * \ingroup PlaYUVerLib * \brief Interface with opencv lib */ diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index f866f53..c0f0e88 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -19,8 +19,7 @@ /** * \file StreamHandlerPortableMap.cpp - * \ingroup PlaYUVerLib - * \brief Interface with opencv lib + * \brief Handling portable pixmap formats */ #include diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 4cbd389..aedd582 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -19,8 +19,7 @@ /** * \file StreamHandlerPortableMap.h - * \ingroup PlaYUVerLib - * \brief Interface with opencv lib + * \brief Handling portable pixmap formats */ #ifndef __STREAMHANDLERPORTABLEMAP_H__ diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 6164c46..8af6ce8 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -19,7 +19,6 @@ /** * \file StreamHandlerRaw.cpp - * \ingroup PlaYUVerLib * \brief Interface for raw (yuv) streams */ @@ -30,7 +29,7 @@ #include "LibMemory.h" -Bool PlaYUVerRawHandler::openHandler( String strFilename, Bool bInput ) +Bool StreamHandlerRaw::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; m_pFile = NULL; @@ -44,19 +43,19 @@ Bool PlaYUVerRawHandler::openHandler( String strFilename, Bool bInput ) return true; } -Void PlaYUVerRawHandler::closeHandler() +Void StreamHandlerRaw::closeHandler() { if( m_pFile ) fclose( m_pFile ); } -Bool PlaYUVerRawHandler::configureBuffer( PlaYUVerFrame* pcFrame ) +Bool StreamHandlerRaw::configureBuffer( PlaYUVerFrame* pcFrame ) { return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); } -UInt64 PlaYUVerRawHandler::calculateFrameNumber() +UInt64 StreamHandlerRaw::calculateFrameNumber() { if( !m_pFile || m_uiNBytesPerFrame == 0 ) return 0; @@ -66,7 +65,7 @@ UInt64 PlaYUVerRawHandler::calculateFrameNumber() return ( fileSize / m_uiNBytesPerFrame ); } -Bool PlaYUVerRawHandler::seek( UInt64 iFrameNum ) +Bool StreamHandlerRaw::seek( UInt64 iFrameNum ) { if( m_bIsInput && m_pFile ) { @@ -76,7 +75,7 @@ Bool PlaYUVerRawHandler::seek( UInt64 iFrameNum ) return false; } -Bool PlaYUVerRawHandler::read( PlaYUVerFrame* pcFrame ) +Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) { UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) @@ -85,7 +84,7 @@ Bool PlaYUVerRawHandler::read( PlaYUVerFrame* pcFrame ) return true; } -Bool PlaYUVerRawHandler::write( PlaYUVerFrame* pcFrame ) +Bool StreamHandlerRaw::write( PlaYUVerFrame* pcFrame ) { pcFrame->frameToBuffer( m_pStreamBuffer ); UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index 28c23a5..fe451bb 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -30,20 +30,19 @@ /** - * \class PlaYUVerRawHandler - * \ingroup PlaYUVerLib PlaYUVerLib_Stream + * \class StreamHandlerRaw * \brief Class to handle raw video format */ -class PlaYUVerRawHandler: public PlaYUVerStreamHandlerIf +class StreamHandlerRaw: public PlaYUVerStreamHandlerIf { - REGISTER_STREAM_HANDLER( PlaYUVerRawHandler ) + REGISTER_STREAM_HANDLER( StreamHandlerRaw ) private: FILE* m_pFile; /**< The input file pointer >*/ public: - PlaYUVerRawHandler() {} - ~PlaYUVerRawHandler() {} + StreamHandlerRaw() {} + ~StreamHandlerRaw() {} Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); From 404e58e0cec1eb15fc825ae76b2f1e4f8393811a Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 17:42:15 +0100 Subject: [PATCH 057/127] Format code --- app/AboutDialog.cpp | 55 ++-- app/AboutDialog.h | 7 +- app/ConfigureFormatDialog.cpp | 13 +- app/DialogSubWindowSelector.cpp | 1 - app/DialogSubWindowSelector.h | 1 - app/FramePropertiesDock.cpp | 3 - app/FramePropertiesDock.h | 4 +- app/GridManager.cpp | 11 +- app/GridManager.h | 6 +- app/HistogramWidget.cpp | 26 +- app/HistogramWidget.h | 2 - app/ModuleHandleDock.cpp | 3 - app/ModuleHandleDock.h | 6 +- app/ModulesHandle.cpp | 3 - app/ModulesHandle.h | 5 +- app/ModulesHandleOptDialog.cpp | 2 - app/ModulesHandleOptDialog.h | 3 +- app/PlaYUVerApp.cpp | 17 +- app/PlaYUVerApp.h | 1 - app/PlaYUVerAppAdaptor.cpp | 2 - app/PlaYUVerAppAdaptor.h | 5 +- app/PlaYUVerAppDefs.h | 4 - app/PlaYUVerAppModuleIf.cpp | 5 +- app/PlaYUVerAppModuleIf.h | 7 +- app/PlaYUVerMdiSubWindow.cpp | 2 - app/PlaYUVerMdiSubWindow.h | 2 - app/PlaYUVerSubWindowHandle.cpp | 8 +- app/PlotSubWindow.cpp | 4 +- app/PlotSubWindow.h | 1 - app/ProgressBar.cpp | 1 - app/ProgressBar.h | 1 - app/QualityHandle.cpp | 3 - app/QualityHandle.h | 3 +- app/QualityMeasurementSidebar.cpp | 3 - app/QualityMeasurementSidebar.h | 3 +- app/SeekStreamDialog.cpp | 2 - app/SeekStreamDialog.h | 3 +- app/SubWindowAbstract.cpp | 6 +- app/SubWindowAbstract.h | 8 +- app/VideoHandle.cpp | 3 - app/VideoHandle.h | 3 +- app/VideoSubWindow.cpp | 17 +- app/VideoSubWindow.h | 1 - app/ViewArea.cpp | 19 +- app/ViewArea.h | 3 +- app/WidgetFrameNumber.cpp | 3 - app/WidgetFrameNumber.h | 4 +- app/main.cpp | 39 +-- .../modules/AbsoluteFrameDifference_APIv2.cpp | 3 - .../modules/AbsoluteFrameDifference_APIv2.h | 1 - examples/modules/FrameBinarization_APIv1.cpp | 3 - examples/modules/FrameBinarization_APIv1.h | 3 +- lib/LibMemory.h | 3 - lib/PlaYUVerDefs.h | 18 +- lib/PlaYUVerFrame.cpp | 34 +- lib/PlaYUVerFrame.h | 1 - lib/PlaYUVerFramePixelFormats.cpp | 304 ++++++++++++------ lib/PlaYUVerFramePixelFormats.h | 2 - lib/PlaYUVerModuleIf.h | 2 - lib/PlaYUVerOptions.cpp | 44 ++- lib/PlaYUVerOptions.h | 21 +- lib/PlaYUVerPixel.cpp | 14 +- lib/PlaYUVerPixel.h | 29 +- lib/PlaYUVerStream.cpp | 39 +-- lib/PlaYUVerStream.h | 7 +- lib/PlaYUVerStreamHandlerIf.h | 3 +- lib/StreamHandlerLibav.cpp | 9 +- lib/StreamHandlerLibav.h | 5 +- lib/StreamHandlerOpenCV.cpp | 6 +- lib/StreamHandlerOpenCV.h | 5 +- lib/StreamHandlerPortableMap.cpp | 26 +- lib/StreamHandlerPortableMap.h | 11 +- lib/StreamHandlerRaw.cpp | 7 +- lib/StreamHandlerRaw.h | 12 +- modules/AbsoluteFrameDifference.cpp | 5 +- modules/AbsoluteFrameDifference.h | 1 - modules/DisparityStereoBM.cpp | 3 - modules/DisparityStereoBM.h | 5 +- modules/DisparityStereoSGBM.cpp | 3 - modules/DisparityStereoSGBM.h | 5 +- modules/DisparityStereoVar.cpp | 3 - modules/DisparityStereoVar.h | 5 +- modules/EightBitsSampling.cpp | 3 - modules/EightBitsSampling.h | 3 +- modules/FilterComponent.cpp | 3 - modules/FilterComponent.h | 9 +- modules/FrameBinarization.cpp | 3 - modules/FrameBinarization.h | 3 +- modules/FrameCrop.cpp | 3 - modules/FrameCrop.h | 3 +- modules/FrameDifference.cpp | 3 - modules/FrameDifference.h | 1 - modules/FrameMask.cpp | 10 +- modules/FrameMask.h | 6 +- modules/FrameShift.cpp | 4 - modules/FrameShift.h | 5 +- modules/LumaAverage.h | 4 +- modules/OpticalFlowDualTVL1.cpp | 11 +- modules/OpticalFlowDualTVL1.h | 1 - modules/PlaYUVerModuleFactory.cpp | 4 +- modules/PlaYUVerModuleFactory.h | 3 +- modules/SetChromaHalfScale.cpp | 3 - modules/SetChromaHalfScale.h | 3 +- modules/WeightedPSNR.cpp | 4 - modules/WeightedPSNR.h | 1 - tools/PlaYUVerTools.cpp | 8 +- tools/PlaYUVerTools.h | 3 +- tools/PlaYUVerToolsCmdParser.cpp | 6 +- tools/PlaYUVerToolsCmdParser.h | 1 - 109 files changed, 494 insertions(+), 593 deletions(-) diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index 4774895..e07a6d3 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -17,14 +17,12 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ - /** * \file AboutDialog.cpp * \brief About Dialog * Based on the work of Glad Deschrijver in KTikZ project */ - #include "AboutDialog.h" #include #include @@ -32,27 +30,25 @@ #include #include - -AboutDialog::AboutDialog(QWidget *parent) - : QDialog(parent) +AboutDialog::AboutDialog( QWidget *parent ) : + QDialog( parent ) { - QPixmap logo = QPixmap(":/images/playuver-backgroud-logo.png").scaled( QSize( 350,350), Qt::KeepAspectRatio ); - QLabel *pixmapLabel = new QLabel; - pixmapLabel->setPixmap( logo ); + QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ).scaled( QSize( 350, 350 ), Qt::KeepAspectRatio ); + QLabel *pixmapLabel = new QLabel; + pixmapLabel->setPixmap( logo ); + QLabel *label = new QLabel( QString( "

%1 Version %2

%3

%4

" ) + .arg( QApplication::applicationName() ) + .arg( QApplication::applicationVersion() ) + .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) + .arg( tr( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ) ); + label->setWordWrap( true ); - QLabel *label = new QLabel(QString("

%1 Version %2

%3

%4

") - .arg(QApplication::applicationName()) - .arg(QApplication::applicationVersion()) - .arg(tr("Enhanced open-source Qt-based raw video player")) - .arg(tr("Copyright © 2014–2015 Luis Lucas and Joao Carreira"))); - label->setWordWrap(true); - - QWidget *topWidget = new QWidget; - QVBoxLayout *topLayout = new QVBoxLayout; - topLayout->addWidget(pixmapLabel); - topLayout->addWidget(label); - topWidget->setLayout(topLayout); + QWidget *topWidget = new QWidget; + QVBoxLayout *topLayout = new QVBoxLayout; + topLayout->addWidget( pixmapLabel ); + topLayout->addWidget( label ); + topWidget->setLayout( topLayout ); // QTextEdit *textEdit = new QTextEdit(tr("

This program is free " // "software; you can redistribute it and/or modify it under the " @@ -64,17 +60,16 @@ AboutDialog::AboutDialog(QWidget *parent) // "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. " // "See the GNU General Public License for more details.

")); // textEdit->setReadOnly(true); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok ); + connect( buttonBox, SIGNAL( accepted() ), this, SLOT( accept() ) ); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->addWidget(topWidget); - //mainLayout->addWidget(textEdit); - mainLayout->addWidget(buttonBox); - mainLayout->setSpacing(10); - buttonBox->setFocus(); + QVBoxLayout *mainLayout = new QVBoxLayout( this ); + mainLayout->addWidget( topWidget ); + //mainLayout->addWidget(textEdit); + mainLayout->addWidget( buttonBox ); + mainLayout->setSpacing( 10 ); + buttonBox->setFocus(); - setWindowTitle(tr("About %1").arg(QApplication::applicationName())); + setWindowTitle( tr( "About %1" ).arg( QApplication::applicationName() ) ); } - diff --git a/app/AboutDialog.h b/app/AboutDialog.h index d1a6cf9..f2e1617 100644 --- a/app/AboutDialog.h +++ b/app/AboutDialog.h @@ -28,13 +28,12 @@ #include - -class AboutDialog : public QDialog +class AboutDialog: public QDialog { - Q_OBJECT +Q_OBJECT public: - AboutDialog(QWidget *parent = 0); + AboutDialog( QWidget *parent = 0 ); }; #endif // __ABOUTDIALOG_H__ diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 40f8f74..45a2984 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -181,7 +181,6 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 1, 1 ); pixelGridLayout->addWidget( m_comboBoxPixelFormat, 1, 2 ); - QLabel* bitsPerPelLabel = new QLabel(); bitsPerPelLabel->setFont( normalFont ); bitsPerPelLabel->setText( "Pixel bit depth" ); @@ -205,13 +204,13 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : m_comboBoxEndianness->setFont( normalFont ); m_comboBoxEndianness->setSizePolicy( sizePolicy ); m_comboBoxEndianness->clear(); - m_comboBoxEndianness->addItem( QStringLiteral("Big Endian") ); - m_comboBoxEndianness->addItem( QStringLiteral("Little Endian") ); + m_comboBoxEndianness->addItem( QStringLiteral( "Big Endian" ) ); + m_comboBoxEndianness->addItem( QStringLiteral( "Little Endian" ) ); endiannessLayout->addWidget( endiannessLabel ); endiannessLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); endiannessLayout->addWidget( m_comboBoxEndianness ); m_widgetEndianness = new QWidget(); - m_widgetEndianness->setContentsMargins( 0,0,0,0 ); + m_widgetEndianness->setContentsMargins( 0, 0, 0, 0 ); m_widgetEndianness->setLayout( endiannessLayout ); m_widgetEndianness->setVisible( true ); @@ -231,7 +230,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : framerateFormatLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); framerateFormatLayout->addWidget( m_spinBoxFrameRate ); QWidget* framerateWidget = new QWidget(); - framerateWidget->setContentsMargins( 0,0,0,0 ); + framerateWidget->setContentsMargins( 0, 0, 0, 0 ); framerateWidget->setLayout( framerateFormatLayout ); /* @@ -267,7 +266,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : } -Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ) +Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, + UInt& rFrameRate ) { // Set default values //setWindowTitle( "Configure resolution for " + Filename ); @@ -392,4 +392,3 @@ Void ConfigureFormatDialog::slotBitsChange( Int idx ) } } - diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index ab53ea5..2d7d0dc 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -28,7 +28,6 @@ #include "DialogSubWindowSelector.h" #include "VideoSubWindow.h" - DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWindowHandle *windowManager, UInt uiCategory, Int minWindowsSelected, Int maxWindowsSelected ) : QDialog( parent ), diff --git a/app/DialogSubWindowSelector.h b/app/DialogSubWindowSelector.h index c281b91..9857cba 100644 --- a/app/DialogSubWindowSelector.h +++ b/app/DialogSubWindowSelector.h @@ -41,7 +41,6 @@ class QColor; class QCheckBox; class QGroupBox; - class PlaYUVerSubWindowHandle; class SubWindowAbstract; diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index 8e56ad7..cb67391 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -27,7 +27,6 @@ #include #include "FramePropertiesDock.h" - FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ) : QWidget( parent ), m_pbIsPlaying( pbMainPlaySwitch ) @@ -615,5 +614,3 @@ Void FramePropertiesDock::slotUpdateIntervRange( Int range ) maxInterv->blockSignals( false ); } - - diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index 45caaca..90071ef 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -37,11 +37,10 @@ #include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" - class FramePropertiesDock: public QWidget { Q_OBJECT -public: + public: FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ); ~FramePropertiesDock(); @@ -76,7 +75,6 @@ private: Bool* m_pbIsPlaying; - QComboBox *channelCB; QComboBox *colorsCB; QComboBox *renderingCB; diff --git a/app/GridManager.cpp b/app/GridManager.cpp index 01a5dba..ba4b1a3 100644 --- a/app/GridManager.cpp +++ b/app/GridManager.cpp @@ -34,7 +34,6 @@ #include "GridManager.h" - //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// @@ -67,8 +66,8 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter switch( style ) { case IntersectionDot: - case IntersectionCross: - { + case IntersectionCross: + { painter->setPen( mainPen ); // Draw crosses or dots on intersections for( int x = offsetx; x <= area.right(); x += hSpacing ) @@ -96,7 +95,7 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter break; } case Dashed: - { + { // Change pen to the dashed line mainPen.setStyle( Qt::DashLine ); } @@ -136,12 +135,12 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter //////////////////////////////////////////////////////////////////////////////// QRect GridManager::rectContains( const QPoint &pos ) const -{ + { return rectContains( pos.x(), pos.y() ); } QRect GridManager::rectContains( int x, int y ) const -{ + { QRect rect; QPoint pos; int multiPosX; diff --git a/app/GridManager.h b/app/GridManager.h index ea9d0bb..3291151 100644 --- a/app/GridManager.h +++ b/app/GridManager.h @@ -36,7 +36,6 @@ class QPoint; class QBitmap; class QPainter; - /** * */ @@ -46,7 +45,10 @@ public: enum Style { - IntersectionDot = 0, IntersectionCross, Dashed, Solid + IntersectionDot = 0, + IntersectionCross, + Dashed, + Solid }; GridManager(); diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index e3d57ba..a2a89dc 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -31,7 +31,6 @@ #include #include "HistogramWidget.h" - class HistogramWorker: public QThread { private: @@ -97,17 +96,18 @@ public: }; const QBrush g_eColorPallet[][3] = -{ - { - Qt::darkGray, // Luma - Qt::blue, // Cb - Qt::red, // Cr - }, - { - Qt::red, // Channel Red - Qt::green, // Channel Green - Qt::blue, // Channel Blue - }, }; + { + { + Qt::darkGray, // Luma + Qt::blue, // Cb + Qt::red, // Cr + }, + { + Qt::red, // Channel Red + Qt::green, // Channel Green + Qt::blue, // Channel Blue + }, + }; class HistogramWidgetPrivate { @@ -1099,5 +1099,3 @@ Void HistogramWidget::slotMaxValueChanged( int max ) } } - - diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index f58b3df..a10a0d1 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -34,7 +34,6 @@ class QEvent; - class HistogramWorker; class HistogramWidgetPrivate; @@ -170,7 +169,6 @@ private: HistogramWidgetPrivate* d; }; - Q_DECLARE_OPERATORS_FOR_FLAGS( HistogramWidget::HistogramOptions ) #endif // __HISTOGRAMWIDGET_H__ diff --git a/app/ModuleHandleDock.cpp b/app/ModuleHandleDock.cpp index df6d31f..e39fab2 100644 --- a/app/ModuleHandleDock.cpp +++ b/app/ModuleHandleDock.cpp @@ -27,7 +27,6 @@ #include "PlaYUVerAppModuleIf.h" #include "ModulesHandle.h" - ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ) : QWidget( parent ), m_pcCurrModuleIf( moduleIf ) @@ -88,5 +87,3 @@ QSize ModuleHandleDock::sizeHint() const return currSize; } - - diff --git a/app/ModuleHandleDock.h b/app/ModuleHandleDock.h index a8bfa3a..0103451 100644 --- a/app/ModuleHandleDock.h +++ b/app/ModuleHandleDock.h @@ -34,14 +34,12 @@ #include #endif - - class PlaYUVerAppModuleIf; class ModuleHandleDock: public QWidget { -Q_OBJECT -public: + Q_OBJECT + public: ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ); ~ModuleHandleDock(); diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index 2feee91..f2b8a99 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -32,7 +32,6 @@ #include "ModulesHandleOptDialog.h" #include "modules/PlaYUVerModuleFactory.h" - ModulesHandle::ModulesHandle( QWidget* parent, PlaYUVerSubWindowHandle *windowManager, VideoHandle *moduleVideo ) : QWidget( parent ), m_pcParent( parent ), @@ -593,5 +592,3 @@ Void ModulesHandle::customEvent( QEvent *event ) } } - - diff --git a/app/ModulesHandle.h b/app/ModulesHandle.h index f72892c..9b98540 100644 --- a/app/ModulesHandle.h +++ b/app/ModulesHandle.h @@ -39,7 +39,6 @@ #include "PlaYUVerAppDefs.h" #include "lib/PlaYUVerFrame.h" - class VideoHandle; class PlaYUVerSubWindowHandle; class PlaYUVerAppModuleIf; @@ -48,7 +47,7 @@ class SubWindowHandle; class ModulesHandle: public QWidget { Q_OBJECT -public: + public: ModulesHandle( QWidget*, PlaYUVerSubWindowHandle*, VideoHandle* ); ~ModulesHandle(); @@ -62,7 +61,7 @@ public: Void writeSettings(); static Void destroyModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ); - static Void applyModuleIf( QList pcCurrModuleIfList, Bool isPlaying = false, Bool disableThreads = false ); + static Void applyModuleIf( QList pcCurrModuleIfList, Bool isPlaying = false, Bool disableThreads = false ); private: QWidget* m_pcParent; diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 6e1a61b..94a9530 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -32,7 +32,6 @@ #include "lib/PlaYUVerOptions.h" - class OpionConfiguration: public QWidget { public: @@ -147,4 +146,3 @@ Int ModulesHandleOptDialog::runConfiguration() return QDialog::Accepted; } - diff --git a/app/ModulesHandleOptDialog.h b/app/ModulesHandleOptDialog.h index cfdfda1..e20ca7f 100644 --- a/app/ModulesHandleOptDialog.h +++ b/app/ModulesHandleOptDialog.h @@ -31,7 +31,6 @@ #include #include - class OpionConfiguration; /** @@ -44,7 +43,7 @@ Q_OBJECT public: ModulesHandleOptDialog( QWidget *parent, PlaYUVerAppModuleIf *pcCurrModuleIf ); Int runConfiguration(); -private: + private: PlaYUVerAppModuleIf *m_pcCurrModuleIf; QVector m_apcOptionList; }; diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 798fa98..178f451 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -46,7 +46,6 @@ #define SYNCHRONISED_ZOON 1 - PlaYUVerApp::PlaYUVerApp() : m_pcCurrentSubWindow( NULL ), m_pcCurrentVideoSubWindow( NULL ), @@ -110,13 +109,13 @@ Bool PlaYUVerApp::parseArgs( Int argc, Char *argv[] ) bRet |= true; } - if( pcCmdParser.hasOpt("help") ) + if( pcCmdParser.hasOpt( "help" ) ) { printf( "Usage: %s [options] input_file[s]\n", argv[0] ); pcCmdParser.doHelp( std::cout ); bRet |= true; } - if( pcCmdParser.hasOpt("input") ) + if( pcCmdParser.hasOpt( "input" ) ) { for( UInt i = 1; i < m_apcInputs.size(); i++ ) { @@ -175,7 +174,7 @@ Void PlaYUVerApp::closeEvent( QCloseEvent *event ) } break; case QMessageBox::No: - default: + default: event->ignore(); } } @@ -380,10 +379,11 @@ Void PlaYUVerApp::reload() Void PlaYUVerApp::reloadAll() { UInt windowCategoryOrder[] = - { - SubWindowAbstract::VIDEO_STREAM_SUBWINDOW, - SubWindowAbstract::MODULE_SUBWINDOW, - SubWindowAbstract::MODULE_SUBWINDOW }; + { + SubWindowAbstract::VIDEO_STREAM_SUBWINDOW, + SubWindowAbstract::MODULE_SUBWINDOW, + SubWindowAbstract::MODULE_SUBWINDOW, + }; for( UInt c = 0; c < 3; c++ ) { @@ -919,4 +919,3 @@ Void PlaYUVerApp::writeSettings() m_pcWindowHandle->writeSettings(); } - diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 02826b7..6030c42 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -54,7 +54,6 @@ class QActionGroup; class QAction; class QSignalMapper; - class PlaYUVerOptions; class PlaYUVerStream; class PlaYUVerSubWindowHandle; diff --git a/app/PlaYUVerAppAdaptor.cpp b/app/PlaYUVerAppAdaptor.cpp index 32801d8..dd5b795 100644 --- a/app/PlaYUVerAppAdaptor.cpp +++ b/app/PlaYUVerAppAdaptor.cpp @@ -26,7 +26,6 @@ #include "PlaYUVerAppAdaptor.h" #include "PlaYUVerApp.h" - PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp *app ) : QDBusAbstractAdaptor( app ), m_app( app ) @@ -62,4 +61,3 @@ bool PlaYUVerAppAdaptor::loadFile( const QString& filename ) return true; } - diff --git a/app/PlaYUVerAppAdaptor.h b/app/PlaYUVerAppAdaptor.h index ab1f6c9..a4e9779 100644 --- a/app/PlaYUVerAppAdaptor.h +++ b/app/PlaYUVerAppAdaptor.h @@ -32,7 +32,6 @@ #include #include - #define PLAYUVER_DBUS_SESSION_NAME "org.pixlra.PlaYUVer.application" #define PLAYUVER_DBUS_PATH "/MainApplication" @@ -41,7 +40,7 @@ class PlaYUVerApp; class PlaYUVerAppAdaptor: public QDBusAbstractAdaptor { Q_OBJECT -Q_CLASSINFO("D-Bus Interface", "org.pixlra.PlaYUVer.application") + Q_CLASSINFO("D-Bus Interface", "org.pixlra.PlaYUVer.application") Q_PROPERTY(QString activeSession READ activeSession) public: PlaYUVerAppAdaptor( PlaYUVerApp *app ); @@ -75,7 +74,7 @@ Q_SIGNALS: //void documentClosed(const QString &token); public: QString activeSession(); -private: + private: PlaYUVerApp *m_app; }; diff --git a/app/PlaYUVerAppDefs.h b/app/PlaYUVerAppDefs.h index 7d7f4b8..48a86af 100644 --- a/app/PlaYUVerAppDefs.h +++ b/app/PlaYUVerAppDefs.h @@ -27,7 +27,6 @@ #include "lib/PlaYUVerDefs.h" - // ==================================================================================================================== // Qt compatibility redefinition // ==================================================================================================================== @@ -39,7 +38,4 @@ # define QStringLiteral(str) QString::fromUtf8("" str "", sizeof(str) - 1) #endif - - - #endif // __PLAYUVERAPPDEFS_H__ diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 65f0119..82ddf83 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -26,7 +26,6 @@ #include "VideoSubWindow.h" #include "VideoSubWindow.h" - PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ) : m_bIsRunning( false ), m_pcModuleAction( action ), @@ -141,7 +140,7 @@ Void PlaYUVerAppModuleIf::run() #ifdef PLAYUVER_THREADED_MODULES EventData *eventData = new EventData( true, this ); if( parent() ) - QCoreApplication::postEvent( parent(), eventData ); + QCoreApplication::postEvent( parent(), eventData ); #endif return; } @@ -217,5 +216,3 @@ Void PlaYUVerAppModuleIf::destroy() } - - diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index 58c6cbe..e80c80c 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -37,16 +37,15 @@ class QAction; - //#define PLAYUVER_THREADED_MODULES class VideoSubWindow; class PlaYUVerAppModuleIf -#ifdef PLAYUVER_THREADED_MODULES + #ifdef PLAYUVER_THREADED_MODULES : public QThread #else -: public QObject + : public QObject #endif { friend class ModulesHandle; @@ -113,7 +112,7 @@ public: Bool apply( Bool isPlaying = false, Bool disableThreads = false ); Void show(); Void destroy(); -protected: + protected: virtual void run(); }; diff --git a/app/PlaYUVerMdiSubWindow.cpp b/app/PlaYUVerMdiSubWindow.cpp index 04aef7b..d30c06f 100644 --- a/app/PlaYUVerMdiSubWindow.cpp +++ b/app/PlaYUVerMdiSubWindow.cpp @@ -26,7 +26,6 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" - PlaYUVerMdiSubWindow::PlaYUVerMdiSubWindow( QWidget *parent ) : QMdiSubWindow( parent ) { @@ -49,4 +48,3 @@ Void PlaYUVerMdiSubWindow::closeEvent( QCloseEvent *event ) event->accept(); } - diff --git a/app/PlaYUVerMdiSubWindow.h b/app/PlaYUVerMdiSubWindow.h index e43b759..440225a 100644 --- a/app/PlaYUVerMdiSubWindow.h +++ b/app/PlaYUVerMdiSubWindow.h @@ -29,8 +29,6 @@ #include "PlaYUVerAppDefs.h" #include - - class PlaYUVerMdiSubWindow: public QMdiSubWindow { Q_OBJECT diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index 4eb4768..1a0332f 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -39,7 +39,6 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" - class PlaYUVerMdiArea: public QMdiArea { public: @@ -304,7 +303,7 @@ SubWindowAbstract* PlaYUVerSubWindowHandle::activeSubWindow() const } QList PlaYUVerSubWindowHandle::findSubWindow( const UInt uiCategory ) const -{ + { QList apcSubWindowList; if( uiCategory == 0 ) { @@ -322,7 +321,7 @@ QList PlaYUVerSubWindowHandle::findSubWindow( const UInt uiC } QList PlaYUVerSubWindowHandle::findSubWindow( const QString &windowName, const UInt uiCategory ) const -{ + { QList subWindowList = findSubWindow( uiCategory ); QList apcSubWindowList; if( !windowName.isEmpty() ) @@ -337,7 +336,7 @@ QList PlaYUVerSubWindowHandle::findSubWindow( const QString } SubWindowAbstract* PlaYUVerSubWindowHandle::findSubWindow( const SubWindowAbstract* subWindow ) const -{ + { QList subWindowList = findSubWindow(); for( Int i = 0; i < subWindowList.size(); i++ ) { @@ -588,4 +587,3 @@ Void PlaYUVerSubWindowHandle::writeSettings() appSettings.setValue( "SubWindowManager/SubWindowMode", m_iWindowMode ); } - diff --git a/app/PlotSubWindow.cpp b/app/PlotSubWindow.cpp index 2fe23e9..ddd7411 100644 --- a/app/PlotSubWindow.cpp +++ b/app/PlotSubWindow.cpp @@ -25,7 +25,6 @@ #include "PlotSubWindow.h" #include "qcustomplot.h" - Void PlotSubWindow::definePlotColors() { m_arrayColorList.append( Qt::blue ); @@ -175,7 +174,7 @@ QSize PlotSubWindow::sizeHint() const } QSize PlotSubWindow::sizeHint( const QSize & maxSize ) const -{ + { return maxSize * 2 / 3; } @@ -239,4 +238,3 @@ Void PlotSubWindow::addPlot( const QVector &arrayX, const QVector #include - ProgressBar::ProgressBar( QWidget *parent, UInt maxValue ) : QWidget( parent ), m_uiTotalProgress( maxValue ), diff --git a/app/ProgressBar.h b/app/ProgressBar.h index e13184f..4cbe919 100644 --- a/app/ProgressBar.h +++ b/app/ProgressBar.h @@ -31,7 +31,6 @@ class QProgressBar; - class ProgressBar: public QWidget { Q_OBJECT diff --git a/app/QualityHandle.cpp b/app/QualityHandle.cpp index bb44c07..d9fd426 100644 --- a/app/QualityHandle.cpp +++ b/app/QualityHandle.cpp @@ -34,7 +34,6 @@ #include "QtConcurrent/qtconcurrentrun.h" #endif - QualityHandle::QualityHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : m_pcParet( parent ), m_pcMainWindowManager( windowManager ) @@ -328,5 +327,3 @@ Void QualityHandle::slotPlotQualitySeveral() } } - - diff --git a/app/QualityHandle.h b/app/QualityHandle.h index 328173d..7df0c03 100644 --- a/app/QualityHandle.h +++ b/app/QualityHandle.h @@ -36,14 +36,13 @@ #include "QFuture" #include "QualityMeasurementSidebar.h" - class PlaYUVerSubWindowHandle; class VideoSubWindow; class QualityHandle: public QWidget { Q_OBJECT -public: + public: QualityHandle( QWidget*, PlaYUVerSubWindowHandle * ); ~QualityHandle(); diff --git a/app/QualityMeasurementSidebar.cpp b/app/QualityMeasurementSidebar.cpp index 59fd21b..b96cb4a 100644 --- a/app/QualityMeasurementSidebar.cpp +++ b/app/QualityMeasurementSidebar.cpp @@ -27,7 +27,6 @@ #include "QualityMeasurementSidebar.h" #include "VideoSubWindow.h" - QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerSubWindowHandle *windowManager ) : QWidget( parent ), m_pcMainWindowManager( windowManager ), @@ -258,5 +257,3 @@ Void QualityMeasurementSidebar::slotQualityMetricChanged( Int idx ) //updateQualityMetric( idx ); } - - diff --git a/app/QualityMeasurementSidebar.h b/app/QualityMeasurementSidebar.h index 5d93cd5..8785507 100644 --- a/app/QualityMeasurementSidebar.h +++ b/app/QualityMeasurementSidebar.h @@ -37,14 +37,13 @@ #include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" - class PlaYUVerSubWindowHandle; class VideoSubWindow; class QualityMeasurementSidebar: public QWidget { Q_OBJECT -public: + public: QualityMeasurementSidebar( QWidget*, PlaYUVerSubWindowHandle * ); ~QualityMeasurementSidebar(); diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index 5221b72..31b1f72 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -30,7 +30,6 @@ #include #include - SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *parent ) : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ), m_iSelectedFrameNum() @@ -81,4 +80,3 @@ Int SeekStreamDialog::runDialog() return m_iSelectedFrameNum; } - diff --git a/app/SeekStreamDialog.h b/app/SeekStreamDialog.h index 7eff039..6542605 100644 --- a/app/SeekStreamDialog.h +++ b/app/SeekStreamDialog.h @@ -31,7 +31,6 @@ #include #include - /** * */ @@ -42,7 +41,7 @@ Q_OBJECT public: SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *parent = 0 ); Int runDialog(); -private: + private: QSpinBox* m_spinFrameNum; Int m_iSelectedFrameNum; }; diff --git a/app/SubWindowAbstract.cpp b/app/SubWindowAbstract.cpp index d5197d1..d4832ea 100644 --- a/app/SubWindowAbstract.cpp +++ b/app/SubWindowAbstract.cpp @@ -30,7 +30,6 @@ #include "SubWindowAbstract.h" #include "PlaYUVerMdiSubWindow.h" - SubWindowAbstract::SubWindowAbstract( QWidget * parent, UInt category ) : QWidget( parent ), m_cSubWindow( NULL ) @@ -38,7 +37,7 @@ SubWindowAbstract::SubWindowAbstract( QWidget * parent, UInt category ) : setParent( parent ); setVisible( false ); //setFocusPolicy( Qt::WheelFocus ); - setFocusPolicy(Qt::StrongFocus); + setFocusPolicy( Qt::StrongFocus ); setAttribute( Qt::WA_DeleteOnClose ); setBackgroundRole( QPalette::Background ); @@ -91,7 +90,7 @@ QSize SubWindowAbstract::sizeHint() const } QSize SubWindowAbstract::sizeHint( const QSize & ) const -{ + { return QSize(); } @@ -113,4 +112,3 @@ Void SubWindowAbstract::closeSubWindow() m_cSubWindow->close(); } - diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index c6d7515..3d2ea4f 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -48,7 +48,6 @@ class QHBoxLayout; class QFocusEvent; class QCloseEvent; - class PlaYUVerMdiSubWindow; class SubWindowAbstract: public QWidget @@ -70,10 +69,9 @@ public: VIDEO_STREAM_SUBWINDOW = 2, MODULE_SUBWINDOW = 4, PLOT_SUBWINDOW = 8, - }; Q_DECLARE_FLAGS( SubWindowCategories, SubWindowCategory ) + };Q_DECLARE_FLAGS( SubWindowCategories, SubWindowCategory ) - - SubWindowAbstract( QWidget *, UInt ); +SubWindowAbstract ( QWidget *, UInt ); ~SubWindowAbstract(); /** @@ -152,7 +150,7 @@ protected: Void setWidget( QWidget* widget ); -Q_SIGNALS: + Q_SIGNALS: /** * Notify that zoom factor was changed by internal event (e.g. by mouse wheel) */ diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index 27871eb..9b9738e 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -41,7 +41,6 @@ #include #endif - VideoHandle::VideoHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : m_pcParet( parent ), m_pcMainWindowManager( windowManager ) @@ -774,5 +773,3 @@ Void VideoHandle::toggleGrid( Bool checked ) } } - - diff --git a/app/VideoHandle.h b/app/VideoHandle.h index 5fa5699..81d5285 100644 --- a/app/VideoHandle.h +++ b/app/VideoHandle.h @@ -42,7 +42,6 @@ class QLabel; class QSlider; class QElapsedTimer; - class PlaYUVerSubWindowHandle; class SubWindowAbstract; class VideoSubWindow; @@ -52,7 +51,7 @@ class WidgetFrameNumber; class VideoHandle: public QWidget { Q_OBJECT -public: + public: VideoHandle( QWidget*, PlaYUVerSubWindowHandle * ); ~VideoHandle(); diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 7413d1e..7dc7798 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -32,7 +32,6 @@ #include "QtConcurrent/qtconcurrentrun.h" #endif - /** * \brief Functions to control data stream from stream information */ @@ -96,7 +95,7 @@ private: QFont m_cTopLeftTextFont; QFont m_cCenterTextFont; Bool m_bBusyWindow; -public: + public: VideoInformation( QWidget *parent ) : QWidget( parent ), m_bBusyWindow( false ) @@ -259,7 +258,7 @@ QSize VideoSubWindow::sizeHint() const } QSize VideoSubWindow::sizeHint( const QSize & maxSize ) const -{ + { QSize isize; if( m_pcCurrFrame ) isize = QSize( m_pcCurrFrame->getWidth() + 50, m_pcCurrFrame->getHeight() + 50 ); @@ -320,7 +319,8 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) if( guessFormat( cFilename, Width, Height, InputFormat, FrameRate ) || bForceDialog ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) + == QDialog::Rejected ) { return false; } @@ -332,7 +332,8 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) } catch( const char *msg ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) + == QDialog::Rejected ) { return false; } @@ -367,7 +368,7 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) } if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, streamInfo->m_iPelFormat, - streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate, true) ) + streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate, true ) ) { return false; } @@ -621,7 +622,7 @@ Void VideoSubWindow::refreshFrameOperation() if( m_pcCurrentDisplayModule ) { m_bWindowBusy = true; - m_pcCurrentDisplayModule->apply( m_bIsPlaying, !m_bIsPlaying && m_apcCurrentModule.size() ); + m_pcCurrentDisplayModule->apply( m_bIsPlaying, !m_bIsPlaying && m_apcCurrentModule.size() ); bSetFrame = false; } if( bSetFrame ) @@ -643,7 +644,7 @@ Void VideoSubWindow::refreshFrame( Bool bThreaded ) m_cRefreshResult = QtConcurrent::run( this, &VideoSubWindow::refreshFrameOperation ); } else -#endif + #endif { refreshFrameOperation(); } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index 7de26cb..c448eca 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -38,7 +38,6 @@ class QScrollArea; - class VideoInformation; class VideoSubWindow; class PlaYUVerAppModuleIf; diff --git a/app/ViewArea.cpp b/app/ViewArea.cpp index f5a991c..de6428d 100644 --- a/app/ViewArea.cpp +++ b/app/ViewArea.cpp @@ -39,7 +39,6 @@ #include "ViewArea.h" #include "GridManager.h" - static const QColor selectionColor = Qt::cyan; static const QColor imageMaskColor = Qt::green; static const QColor eraserColor = Qt::red; @@ -686,7 +685,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) switch( tool() ) { case MaskTool: - { + { if( m_maskColor.isValid() ) color = m_maskColor; else @@ -695,7 +694,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) break; } case EraserTool: - { + { color = eraserColor; break; } @@ -999,7 +998,7 @@ Void ViewArea::mouseReleaseEvent( QMouseEvent *event ) //////////////////////////////////////////////////////////////////////////////// Bool ViewArea::isPosValid( const QPoint &pos ) const -{ + { if( pos.x() < 0 || pos.y() < 0 || pos.x() >= m_pixmap.width() || pos.y() >= m_pixmap.height() ) return false; @@ -1010,7 +1009,7 @@ Bool ViewArea::isPosValid( const QPoint &pos ) const //////////////////////////////////////////////////////////////////////////////// QPoint ViewArea::windowToView( const QPoint& pt ) const -{ + { QPoint p; p.setX( static_cast( ( pt.x() - m_xOffset ) / m_dZoomFactor ) ); p.setY( static_cast( ( pt.y() - m_yOffset ) / m_dZoomFactor ) ); @@ -1019,7 +1018,7 @@ QPoint ViewArea::windowToView( const QPoint& pt ) const } QRect ViewArea::windowToView( const QRect& rc ) const -{ + { QRect r; r.setTopLeft( windowToView( rc.topLeft() ) ); @@ -1032,7 +1031,7 @@ QRect ViewArea::windowToView( const QRect& rc ) const } QPoint ViewArea::viewToWindow( const QPoint& pt ) const -{ + { QPoint p; p.setX( static_cast( pt.x() * m_dZoomFactor + m_xOffset ) ); @@ -1042,7 +1041,7 @@ QPoint ViewArea::viewToWindow( const QPoint& pt ) const } QRect ViewArea::viewToWindow( const QRect& rc ) const -{ + { QRect r; r.setTopLeft( viewToWindow( rc.topLeft() ) ); @@ -1066,7 +1065,7 @@ Void ViewArea::updateMask( const QRect &rect ) switch( tool() ) { case MaskTool: - { + { // Add rect to the mask QPainter paInter( &m_mask ); paInter.setBrush( Qt::color1 ); @@ -1076,7 +1075,7 @@ Void ViewArea::updateMask( const QRect &rect ) break; } case EraserTool: - { + { // Clears rect area in the mask QPainter paInter( &m_mask ); paInter.setBrush( Qt::color0 ); diff --git a/app/ViewArea.h b/app/ViewArea.h index 0b61acc..31a5e17 100644 --- a/app/ViewArea.h +++ b/app/ViewArea.h @@ -36,7 +36,6 @@ #include "GridManager.h" #include "lib/PlaYUVerFrame.h" - class PlaYUVerStream; /** @@ -124,7 +123,7 @@ public Q_SLOTS: // Void setNormalSelectionTool(); // Void setBlockSelectionTool(); void setSnapToGrid( bool enable ); -// void setSelectedArea( QRect &rect ); + // void setSelectedArea( QRect &rect ); protected: Void paintEvent( QPaintEvent *event ); diff --git a/app/WidgetFrameNumber.cpp b/app/WidgetFrameNumber.cpp index 4f7f4b0..81d94ca 100644 --- a/app/WidgetFrameNumber.cpp +++ b/app/WidgetFrameNumber.cpp @@ -31,7 +31,6 @@ #endif #include "WidgetFrameNumber.h" - WidgetFrameNumber::WidgetFrameNumber( QWidget *parent ) : QWidget( parent ) { @@ -67,5 +66,3 @@ Void WidgetFrameNumber::clear() m_pcTotalFrameNumLabel->setText( "-" ); } - - diff --git a/app/WidgetFrameNumber.h b/app/WidgetFrameNumber.h index 93619bf..d9af7f9 100644 --- a/app/WidgetFrameNumber.h +++ b/app/WidgetFrameNumber.h @@ -25,7 +25,6 @@ #ifndef __WIDGETFRAMENUMBER_H__ #define __WIDGETFRAMENUMBER_H__ - #include "config.h" #include "PlaYUVerAppDefs.h" #include @@ -35,7 +34,6 @@ #include #endif - class WidgetFrameNumber: public QWidget { public: @@ -43,7 +41,7 @@ public: Void setCurrFrameNum( Int number ); Void setTotalFrameNum( Int number ); Void clear(); -private: + private: QLabel *m_pcCurrFrameNumLabel; QLabel *m_pcTotalFrameNumLabel; diff --git a/app/main.cpp b/app/main.cpp index 6f6cfee..e707bfa 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -45,7 +45,7 @@ int main( int argc, char *argv[] ) QApplication application( argc, argv ); QApplication::setApplicationName( "PlaYUVer" ); - QApplication::setApplicationVersion( PLAYUVER_VERSION_STRING ); + QApplication::setApplicationVersion (PLAYUVER_VERSION_STRING); QApplication::setOrganizationName( "PixLRA" ); #ifdef USE_QTDBUS @@ -90,32 +90,33 @@ int main( int argc, char *argv[] ) QStringList tokens; // open given files... - foreach(const QString & file, filenameList){ - QDBusMessage m = QDBusMessage::createMethodCall(PLAYUVER_DBUS_SESSION_NAME, - QStringLiteral(PLAYUVER_DBUS_PATH), QStringLiteral(PLAYUVER_DBUS_SESSION_NAME), QStringLiteral("loadFile")); - - QList dbusargs; - dbusargs.append( file ); - m.setArguments(dbusargs); - - QDBusMessage res = QDBusConnection::sessionBus().call(m); - if (res.type() == QDBusMessage::ReplyMessage) + foreach(const QString & file, filenameList) { - if (res.arguments().count() == 1) + QDBusMessage m = QDBusMessage::createMethodCall(PLAYUVER_DBUS_SESSION_NAME, + QStringLiteral(PLAYUVER_DBUS_PATH), QStringLiteral(PLAYUVER_DBUS_SESSION_NAME), QStringLiteral("loadFile")); + + QList dbusargs; + dbusargs.append( file ); + m.setArguments(dbusargs); + + QDBusMessage res = QDBusConnection::sessionBus().call(m); + if (res.type() == QDBusMessage::ReplyMessage) { - QVariant v = res.arguments()[0]; - if (v.isValid()) + if (res.arguments().count() == 1) { - QString s = v.toString(); - if ((!s.isEmpty()) && (s != QStringLiteral("ERROR"))) + QVariant v = res.arguments()[0]; + if (v.isValid()) { - tokens << s; + QString s = v.toString(); + if ((!s.isEmpty()) && (s != QStringLiteral("ERROR"))) + { + tokens << s; + } } } } } - } - // this will wait until exiting is emitted by the used instance, if wanted... + // this will wait until exiting is emitted by the used instance, if wanted... return needToBlock ? application.exec() : 0; } } diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.cpp b/examples/modules/AbsoluteFrameDifference_APIv2.cpp index 6b45546..a772410 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.cpp +++ b/examples/modules/AbsoluteFrameDifference_APIv2.cpp @@ -25,7 +25,6 @@ #include "AbsoluteFrameDifference_APIv2.h" #include - REGISTER_CLASS_MAKER( AbsoluteFrameDifference ) AbsoluteFrameDifference::AbsoluteFrameDifference() @@ -78,5 +77,3 @@ Void AbsoluteFrameDifference::destroy() m_pcFrameDifference = NULL; } - - diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.h b/examples/modules/AbsoluteFrameDifference_APIv2.h index a1e987b..40825f5 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.h +++ b/examples/modules/AbsoluteFrameDifference_APIv2.h @@ -29,7 +29,6 @@ #include - class AbsoluteFrameDifference: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( AbsoluteFrameDifference ) diff --git a/examples/modules/FrameBinarization_APIv1.cpp b/examples/modules/FrameBinarization_APIv1.cpp index 6fee1ee..1ce3531 100644 --- a/examples/modules/FrameBinarization_APIv1.cpp +++ b/examples/modules/FrameBinarization_APIv1.cpp @@ -24,7 +24,6 @@ #include "FrameBinarization_APIv1.h" - REGISTER_CLASS_MAKER( FrameBinarization ) FrameBinarization::FrameBinarization() @@ -69,5 +68,3 @@ Void FrameBinarization::destroy() m_pcBinFrame = NULL; } - - diff --git a/examples/modules/FrameBinarization_APIv1.h b/examples/modules/FrameBinarization_APIv1.h index 1de89cf..e3b74e1 100644 --- a/examples/modules/FrameBinarization_APIv1.h +++ b/examples/modules/FrameBinarization_APIv1.h @@ -27,7 +27,6 @@ #include "PlaYUVerModuleIf.h" - class FrameBinarization: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameBinarization ) @@ -35,7 +34,7 @@ REGISTER_CLASS_FACTORY( FrameBinarization ) private: PlaYUVerFrame* m_pcBinFrame; UInt m_uiThreshold; -public: + public: FrameBinarization(); virtual ~FrameBinarization() { diff --git a/lib/LibMemory.h b/lib/LibMemory.h index c3e1076..d212f63 100644 --- a/lib/LibMemory.h +++ b/lib/LibMemory.h @@ -30,7 +30,6 @@ #include #include - typedef void Void; typedef char Char; typedef int Int; @@ -231,6 +230,4 @@ Void freeMem3ImageComponents( T*** array3D ) } } - - #endif // __LIBMEMORY_H__ diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index ef182f7..09a2a44 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -30,7 +30,6 @@ #include #include - // ==================================================================================================================== // Basic type redefinition // ==================================================================================================================== @@ -92,7 +91,6 @@ typedef UChar Byte; // Macro functions // ==================================================================================================================== - // ==================================================================================================================== // PlaYUVer definitions // ==================================================================================================================== @@ -120,7 +118,6 @@ enum RGBcomponent COLOR_A, }; - inline String lowercase( const String& in ) { String out; @@ -140,11 +137,17 @@ struct PlaYUVerFailure: public std::exception String m_class_name; String m_error_msg; PlaYUVerFailure( String error_msg ) throw() : - m_error_msg( error_msg ) { } + m_error_msg( error_msg ) + { + } PlaYUVerFailure( String class_name, String error_msg ) throw() : - m_class_name( class_name ), - m_error_msg( error_msg ) { } - ~PlaYUVerFailure() throw() { } + m_class_name( class_name ), + m_error_msg( error_msg ) + { + } + ~PlaYUVerFailure() throw() + { + } const Char* what() const throw() { String* msg = new String( "[" + m_class_name + "] " + m_error_msg ); @@ -152,5 +155,4 @@ struct PlaYUVerFailure: public std::exception } }; - #endif // __PLAYUVERDEFS_H__ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 6f26d66..bdff173 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -125,23 +125,25 @@ struct PlaYUVerFramePrivate Bool m_bHasHistogram; }; - /*! \brief Constructors * * Constructors and init functions */ -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : + d( new PlaYUVerFramePrivate ) { d->init( width, height, pelFormat, bitsPixel, endianness ); } -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) : d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) : + d( new PlaYUVerFramePrivate ) { d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); copyFrom( other ); } -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : + d( new PlaYUVerFramePrivate ) { PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) @@ -174,10 +176,10 @@ static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2 total_mem_size += getMem2D( array3D, dim0, dim1 ); - if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof( Pel ) ) ) == NULL ) + if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof(Pel) ) ) == NULL ) printf( "getMem3DImageComponents: array1D" ); - total_mem_size += mem_size * sizeof( Pel ); + total_mem_size += mem_size * sizeof(Pel); // Luma for( i = 1; i < dim1; i++ ) @@ -288,7 +290,7 @@ Void PlaYUVerFrame::clear() } Bool PlaYUVerFrame::haveSameFmt( PlaYUVerFrame* other, UInt match ) const -{ + { Bool bRet = true; if( other ) { @@ -331,16 +333,16 @@ UInt PlaYUVerFrame::getNumberChannels() const } UInt PlaYUVerFrame::getWidth( Int channel ) const -{ + { return CHROMASHIFT( d->m_uiWidth, channel > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0 ); } UInt PlaYUVerFrame::getHeight( Int channel ) const -{ + { return CHROMASHIFT( d->m_uiHeight, channel > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0 ); } UInt PlaYUVerFrame::getPixels( Int channel ) const -{ + { return getWidth( channel ) * getWidth( channel ); } @@ -471,7 +473,7 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame ) return; d->m_bHasRGBPel = false; d->m_bHasHistogram = false; - memcpy( *d->m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); + memcpy( *d->m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof(Pel) ); } Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) @@ -485,7 +487,7 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; for( UInt i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ); i++ ) { - memcpy( d->m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( d->m_uiWidth >> ratioW ) * sizeof( Pel ) ); + memcpy( d->m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( d->m_uiWidth >> ratioW ) * sizeof(Pel) ); } } d->m_bHasRGBPel = false; @@ -1086,13 +1088,13 @@ Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) { switch( cvMat.channels() ) { - case 1: + case 1: d->m_iPixelFormat = findPixelFormat( "GRAY" ); break; - case 3: + case 3: d->m_iPixelFormat = findPixelFormat( "BGR24" ); break; - default: + default: return false; } } @@ -1276,5 +1278,3 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) return dSSIM; } - - diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index a9a11db..0e6b784 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -33,7 +33,6 @@ namespace cv class Mat; } - struct PlaYUVerPixFmtDescriptor; struct PlaYUVerFramePrivate; diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index c4f8790..d870a56 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -37,8 +37,6 @@ #include "StreamHandlerLibav.h" #endif - - /* ************************************************************** * Handle different pel formats @@ -202,121 +200,217 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI #endif PlaYUVerPixFmtDescriptor yuv420p = -{ - "YUV420p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 1, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), - { - { 0, 0, 1, 0, 7 }, /* Y */ - { 1, 0, 1, 0, 7 }, /* U */ - { 2, 0, 1, 0, 7 }, /* V */ - }, -}; + { + "YUV420p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 1, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), + { + { + 0, + 0, + 1, + 0, + 7 }, /* Y */ + { + 1, + 0, + 1, + 0, + 7 }, /* U */ + { + 2, + 0, + 1, + 0, + 7 }, /* V */ + }, + }; PlaYUVerPixFmtDescriptor yuv422p = -{ - "YUV422p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), - { - { 0, 0, 1, 0, 7 }, /* Y */ - { 1, 0, 1, 0, 7 }, /* U */ - { 2, 0, 1, 0, 7 }, /* V */ - }, -}; + { + "YUV422p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), + { + { + 0, + 0, + 1, + 0, + 7 }, /* Y */ + { + 1, + 0, + 1, + 0, + 7 }, /* U */ + { + 2, + 0, + 1, + 0, + 7 }, /* V */ + }, + }; PlaYUVerPixFmtDescriptor yuv444p = -{ - "YUV444p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), - { - { 0, 0, 1, 0, 7 }, /* Y */ - { 1, 0, 1, 0, 7 }, /* U */ - { 2, 0, 1, 0, 7 }, /* V */ - }, -}; + { + "YUV444p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), + { + { + 0, + 0, + 1, + 0, + 7 }, /* Y */ + { + 1, + 0, + 1, + 0, + 7 }, /* U */ + { + 2, + 0, + 1, + 0, + 7 }, /* V */ + }, + }; PlaYUVerPixFmtDescriptor yuyv422 = -{ - "YUYV422", - PlaYUVerPixel::COLOR_YUV, - 3, - 1, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), - { - { 0, 1, 1, 0, 7 }, /* Y */ - { 0, 3, 2, 0, 7 }, /* U */ - { 0, 3, 4, 0, 7 }, /* V */ - }, -}; + { + "YUYV422", + PlaYUVerPixel::COLOR_YUV, + 3, + 1, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), + { + { + 0, + 1, + 1, + 0, + 7 }, /* Y */ + { + 0, + 3, + 2, + 0, + 7 }, /* U */ + { + 0, + 3, + 4, + 0, + 7 }, /* V */ + }, + }; PlaYUVerPixFmtDescriptor gray = -{ - "GRAY", - PlaYUVerPixel::COLOR_GRAY, - 1, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), - { { 0, 0, 1, 0, 7 } }, /* Y */ -}; + { + "GRAY", + PlaYUVerPixel::COLOR_GRAY, + 1, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), + { + { + 0, + 0, + 1, + 0, + 7 } }, /* Y */ + }; PlaYUVerPixFmtDescriptor RGB24 = -{ - "RGB24", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), - { - { 0, 2, 1, 0, 7 }, /* R */ - { 0, 2, 2, 0, 7 }, /* G */ - { 0, 2, 3, 0, 7 }, /* B */ - }, -}; + { + "RGB24", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + { + { + 0, + 2, + 1, + 0, + 7 }, /* R */ + { + 0, + 2, + 2, + 0, + 7 }, /* G */ + { + 0, + 2, + 3, + 0, + 7 }, /* B */ + }, + }; PlaYUVerPixFmtDescriptor BGR24 = -{ - "BGR24", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), - { - { 0, 2, 3, 0, 7 }, /* R */ - { 0, 2, 2, 0, 7 }, /* G */ - { 0, 2, 1, 0, 7 }, /* B */ - }, -}; + { + "BGR24", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), + { + { + 0, + 2, + 3, + 0, + 7 }, /* R */ + { + 0, + 2, + 2, + 0, + 7 }, /* G */ + { + 0, + 2, + 1, + 0, + 7 }, /* B */ + }, + }; PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS] = -{ - yuv420p, - yuv444p, - yuv422p, - yuyv422, - gray, - RGB24, - BGR24, -}; + { + yuv420p, + yuv444p, + yuv422p, + yuyv422, + gray, + RGB24, + BGR24, + }; diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index ae7c3b8..2036b44 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -143,6 +143,4 @@ typedef struct PlaYUVerPixFmtDescriptor #define PLAYUVER_NUMBER_FORMATS 7 extern PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS]; - - #endif // __PLAYUVERFRAMEPIXELFORMATS_H__ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index 17e9a76..439fea4 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -40,7 +40,6 @@ #include "PlaYUVerOptions.h" #include - #define REGISTER_CLASS_MAKER(X) \ extern "C" PlaYUVerModuleIf* Maker() { return new X; } @@ -115,7 +114,6 @@ enum Module_Key_Supported MODULE_KEY_DOWN, }; - /** * \class PlaYUVerModuleIf * \ingroup PlaYUVerLib PlaYUVerLib_Modules diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index 079174d..729ca56 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -60,22 +60,25 @@ struct ParseFailure: public std::exception String arg; String val; ParseFailure( String arg0, String val0 ) throw() : - arg( arg0 ), - val( val0 ) { } - ~ParseFailure() throw() { } + arg( arg0 ), + val( val0 ) + { + } + ~ParseFailure() throw() + { + } const Char* what() const throw() { return "Option Parse Failure"; } }; - /** Type specific option storage */ class BoolOption: public OptionBase { public: BoolOption( const String& name, const String& desc ) : - OptionBase( name, desc ) + OptionBase( name, desc ) { is_binary = true; } @@ -92,8 +95,8 @@ class StandardOption: public OptionBase { public: StandardOption( const String& name, T& storage, const String& desc ) : - OptionBase( name, desc ), - opt_storage( storage ) + OptionBase( name, desc ), + opt_storage( storage ) { is_binary = false; } @@ -124,7 +127,7 @@ inline void StandardOption::parse( const String& arg ) } template<> -inline void StandardOption< std::vector >::parse( const String& arg ) +inline void StandardOption >::parse( const String& arg ) { UInt aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -142,7 +145,7 @@ inline void StandardOption< std::vector >::parse( const String& arg ) } template<> -inline void StandardOption< std::vector >::parse( const String& arg ) +inline void StandardOption >::parse( const String& arg ) { Int aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -179,12 +182,12 @@ inline void StandardOption >::parse( const String& arg ) struct FunctionOption: public OptionBase { public: - typedef Void( Func )( PlaYUVerOptions&, const String& ); + typedef Void (Func)( PlaYUVerOptions&, const String& ); FunctionOption( const String& name, PlaYUVerOptions& parent_, Func *func_, const String& desc ) : - OptionBase( name, desc ), - parent( parent_ ), - func( func_ ) + OptionBase( name, desc ), + parent( parent_ ), + func( func_ ) { is_binary = false; } @@ -197,7 +200,7 @@ public: private: PlaYUVerOptions& parent; - void ( *func )( PlaYUVerOptions&, const String& ); + void (*func)( PlaYUVerOptions&, const String& ); }; /* Helper method to initiate adding options to Options */ @@ -247,7 +250,6 @@ template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std:: // addOption( new FunctionOption( name, parent, func, desc ) ); // return *this; // } - PlaYUVerOptions::PlaYUVerOptions( const String& name ) { m_cOptionGroupName = name; @@ -308,7 +310,6 @@ Void PlaYUVerOptions::addDefaultOptions() ( "module_list_full", "detailed list supported modules" ); } - PlaYUVerOptions& PlaYUVerOptions::addOptions() { return *this; @@ -346,8 +347,6 @@ void PlaYUVerOptions::addOption( OptionBase *opt ) opt_list.push_back( names ); } - - static void setOptions( PlaYUVerOptions::OptionsList& opt_list, const string& value ) { /* multiple options may be registered for the same name: @@ -429,7 +428,7 @@ UInt PlaYUVerOptions::parseLONG( UInt argc, Char* argv[] ) * where longopts have to include an =, otherwise they are * booleans */ if( argc == 1 ) - return 0; /* run out of argv for argument */ + return 0; /* run out of argv for argument */ extra_argc_consumed = 1; #endif if( !storePair( true, false, option, "1" ) ) @@ -529,7 +528,6 @@ Bool PlaYUVerOptions::parse( UInt argc, Char *argv[] ) return true; } - list PlaYUVerOptions::scanArgv( UInt argc, Char *argv[] ) { /* a list for anything that didn't get handled as an option */ @@ -725,8 +723,8 @@ Bool PlaYUVerOptions::checkListingOpts() if( hasOpt( "version" ) ) { std::cout << "PlaYUVer version " - << PLAYUVER_VERSION_STRING - << "\n"; + << PLAYUVER_VERSION_STRING + << "\n"; bRet |= true; } if( hasOpt( "pel_fmts" ) ) @@ -810,5 +808,3 @@ Void PlaYUVerOptions::listModules() } } - - diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index d51f31c..795f2b1 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -48,7 +48,6 @@ #include "PlaYUVerDefs.h" - /** OptionBase: Virtual base class for storing information relating to a * specific option This base class describes common elements. * Type specific information should be stored in a derived class. @@ -57,12 +56,15 @@ class OptionBase { public: OptionBase( const String& name, const String& desc ) : - arg_count( 0 ), - opt_string( name ), - opt_desc( desc ) - { } + arg_count( 0 ), + opt_string( name ), + opt_desc( desc ) + { + } - virtual ~OptionBase() {} + virtual ~OptionBase() + { + } /* parse argument arg, to obtain a value for the option */ virtual void parse( const String& arg ) = 0; @@ -81,7 +83,6 @@ public: Bool is_binary; }; - class PlaYUVerOptions { public: @@ -89,7 +90,7 @@ public: struct Option { Option() : - opt( 0 ) + opt( 0 ) { } ~Option() @@ -102,7 +103,6 @@ public: OptionBase* opt; }; - typedef std::list OptionsList; PlaYUVerOptions( const String& name = "" ); @@ -151,7 +151,6 @@ public: PlaYUVerOptions& operator()( const String& name, T& storage, const String& desc ); - /** * Add option described by name to the parent Options list, * with desc as an optional help description @@ -162,7 +161,6 @@ public: // PlaYUVerOptions& // operator()( const String& name, OptionFunc::Func *func, const String& desc ); - Bool checkListingOpts(); Void listModules(); @@ -186,5 +184,4 @@ private: }; - #endif // __PROGRAMOPTIONS_H__ diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index 54e03c4..4f85907 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -28,7 +28,7 @@ #include "PlaYUVerPixel.h" PlaYUVerPixel::PlaYUVerPixel() : - m_iColorSpace( COLOR_INVALID ) + m_iColorSpace( COLOR_INVALID ) { m_iColorSpace = COLOR_INVALID; PixelComponents[0] = 0; @@ -46,7 +46,7 @@ PlaYUVerPixel::PlaYUVerPixel( const Int& ColorSpace ) PixelComponents[3] = 0; } -PlaYUVerPixel::PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ) +PlaYUVerPixel::PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ) { m_iColorSpace = ColorSpace == COLOR_GRAY ? COLOR_YUV : ColorSpace; PixelComponents[0] = c0; @@ -82,7 +82,6 @@ Pel PlaYUVerPixel::Cr() const return PixelComponents[2]; } - Pel& PlaYUVerPixel::Y() { return PixelComponents[0]; @@ -109,7 +108,7 @@ Pel& PlaYUVerPixel::B() } Pel PlaYUVerPixel::operator[]( const Int& channel ) const -{ + { return PixelComponents[channel]; } Pel& PlaYUVerPixel::operator[]( const Int& channel ) @@ -117,19 +116,19 @@ Pel& PlaYUVerPixel::operator[]( const Int& channel ) return PixelComponents[channel]; } -PlaYUVerPixel PlaYUVerPixel::operator+ ( const PlaYUVerPixel& in ) +PlaYUVerPixel PlaYUVerPixel::operator+( const PlaYUVerPixel& in ) { PlaYUVerPixel out( m_iColorSpace, Y() + in.Y(), Cb() + in.Cb(), Cr() + in.Cr() ); return out; } -PlaYUVerPixel PlaYUVerPixel::operator- ( const PlaYUVerPixel& in ) +PlaYUVerPixel PlaYUVerPixel::operator-( const PlaYUVerPixel& in ) { PlaYUVerPixel out( m_iColorSpace, Y() - in.Y(), Cb() - in.Cb(), Cr() - in.Cr() ); return out; } -PlaYUVerPixel PlaYUVerPixel::operator* ( const Double& op ) +PlaYUVerPixel PlaYUVerPixel::operator*( const Double& op ) { PlaYUVerPixel out( m_iColorSpace, Y() * op, Cb() * op, Cr() * op ); return out; @@ -160,4 +159,3 @@ PlaYUVerPixel PlaYUVerPixel::ConvertPixel( ColorSpace eOutputSpace ) return outPixel; } - diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index d6e7262..ca3281a 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -31,10 +31,9 @@ #include #include "PlaYUVerDefs.h" - static inline Void YuvToRgb( const Int &iY, const Int &iU, const Int &iV, Int &iR, Int &iG, Int &iB ) { - iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); + iR = iY + ( ( 1436 * ( iV - 128 ) ) >> 10 ); iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); iR = iR < 0 ? 0 : iR > 255 ? 255 : iR; @@ -50,10 +49,10 @@ static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int &i } /** - * \class PlaYUVerPixel - * \ingroup PlaYUVerLib PlaYUVerLib_Frame - * \brief Pixel handling class - */ + * \class PlaYUVerPixel + * \ingroup PlaYUVerLib PlaYUVerLib_Frame + * \brief Pixel handling class + */ class PlaYUVerPixel { public: @@ -61,11 +60,11 @@ public: static const UInt MAX_NUMBER_COMPONENTS = 5; /** ColorSpace list - * List of supported color spaces - */ + * List of supported color spaces + */ enum ColorSpace { - COLOR_INVALID = -1, //!< Invalid + COLOR_INVALID = -1, //!< Invalid COLOR_YUV = 0, //!< YUV COLOR_RGB = 1, //!< RGB COLOR_GRAY = 2, //!< Grayscale @@ -75,7 +74,7 @@ public: PlaYUVerPixel(); PlaYUVerPixel( const Int& ColorSpace ); - PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ); + PlaYUVerPixel( const Int& ColorSpace, const Pel& c0, const Pel& c1, const Pel& c2 ); ~PlaYUVerPixel(); Int ColorSpaceType(); @@ -96,12 +95,12 @@ public: Pel& G(); Pel& B(); - Pel operator[] ( const Int& channel ) const; - Pel& operator[] ( const Int& channel ); + Pel operator[]( const Int& channel ) const; + Pel& operator[]( const Int& channel ); - PlaYUVerPixel operator+ ( const PlaYUVerPixel& ); - PlaYUVerPixel operator- ( const PlaYUVerPixel& ); - PlaYUVerPixel operator* ( const Double& ); + PlaYUVerPixel operator+( const PlaYUVerPixel& ); + PlaYUVerPixel operator-( const PlaYUVerPixel& ); + PlaYUVerPixel operator*( const Double& ); /** * Convert a Pixel to a new color space diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 09cda71..c8e6f4d 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -38,7 +38,6 @@ #include "StreamHandlerOpenCV.h" #endif - std::vector PlaYUVerStream::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -97,7 +96,6 @@ std::vector PlaYUVerStream::stdResolutionSizes() return stdResList; } - CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, bool bRead ) { String currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 ); @@ -114,7 +112,7 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo } for( UInt i = 0; i < supportedFmts.size(); i++ ) { - if( currExt != "" && supportedFmts[i].formatExt == currExt ) + if( currExt != "" && supportedFmts[i].formatExt == currExt ) { return supportedFmts[i].formatFct; } @@ -195,14 +193,14 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f m_pfctCreateHandler = PlaYUVerStream::findStreamHandler( filename, m_bIsInput ); if( !m_pfctCreateHandler ) { - throw PlaYUVerFailure("PlaYUVerStream", "Invalid handler"); + throw PlaYUVerFailure( "PlaYUVerStream", "Invalid handler" ); } m_pcHandler = m_pfctCreateHandler(); if( !m_pcHandler ) { - throw PlaYUVerFailure("PlaYUVerStream", "Cannot create handler"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot create handler" ); } m_cFilename = filename; @@ -215,19 +213,17 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f m_pcHandler->m_iEndianness = endianness; m_pcHandler->m_dFrameRate = frame_rate; - if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { close(); - throw PlaYUVerFailure("PlaYUVerStream", "Cannot open file " + m_cFilename ); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot open file " + m_cFilename ); return m_bInit; } - if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 ) { close(); - throw PlaYUVerFailure("PlaYUVerStream", "Incorrect configuration"); + throw PlaYUVerFailure( "PlaYUVerStream", "Incorrect configuration" ); return m_bInit; } @@ -238,12 +234,13 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel, m_pcHandler->m_iEndianness ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel, + m_pcHandler->m_iEndianness ); } catch( const char *msg ) { close(); - throw PlaYUVerFailure("PlaYUVerStream", "Cannot allocated frame buffer"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot allocated frame buffer" ); return m_bInit; } } @@ -260,14 +257,14 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f if( m_bIsInput && m_uiTotalFrameNum <= 0 ) { close(); - throw PlaYUVerFailure("PlaYUVerStream", "Incorrect configuration: less than one frame"); + throw PlaYUVerFailure( "PlaYUVerStream", "Incorrect configuration: less than one frame" ); return m_bInit; } if( !m_pcHandler->configureBuffer( m_pcCurrFrame ) ) { close(); - throw PlaYUVerFailure("PlaYUVerStream", "Cannot allocated memory"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot allocated memory" ); return m_bInit; } @@ -285,13 +282,13 @@ Bool PlaYUVerStream::reload() m_pcHandler->closeHandler(); if( !m_pcHandler->openHandler( m_cFilename, m_bIsInput ) ) { - throw PlaYUVerFailure("PlaYUVerStream", "Cannot open file"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot open file" ); } m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 - || m_pcHandler->m_iPixelFormat < 0 || m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) + || m_pcHandler->m_iPixelFormat < 0 || m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) { return false; } @@ -312,8 +309,6 @@ Void PlaYUVerStream::close() m_pcHandler->closeHandler(); - - if( m_ppcFrameBuffer ) { for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) @@ -465,7 +460,7 @@ Void PlaYUVerStream::readFrame() if( !m_pcHandler->read( m_pcNextFrame ) ) { - throw PlaYUVerFailure("PlaYUVerStream", "Cannot read file"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot read file" ); return; } @@ -482,7 +477,7 @@ Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) { if( !m_pcHandler->write( pcFrame ) ) { - throw PlaYUVerFailure("PlaYUVerStream", "Cannot write into the file"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot write into the file" ); } return; } @@ -495,7 +490,8 @@ Bool PlaYUVerStream::saveFrame( const String& filename ) Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame *saveFrame ) { PlaYUVerStream auxSaveStream; - if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), saveFrame->getEndianness(), 1, false ) ) + if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), + saveFrame->getEndianness(), 1, false ) ) { return false; } @@ -587,7 +583,7 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) if( !m_pcHandler->seek( new_frame_num ) ) { - throw PlaYUVerFailure("PlaYUVerStream", "Cannot write into the file"); + throw PlaYUVerFailure( "PlaYUVerStream", "Cannot write into the file" ); } m_uiCurrFrameFileIdx = new_frame_num; @@ -602,4 +598,3 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) return true; } - diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index f1f3089..fbefab8 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -37,7 +37,6 @@ typedef struct UInt uiHeight; } PlaYUVerStdResolution; - typedef PlaYUVerStreamHandlerIf* (*CreateStreamHandlerFn)( void ); typedef struct @@ -54,7 +53,7 @@ typedef struct #define END_REGIST_PLAYUVER_SUPPORTED_FMT \ return formatsList; - #define REGIST_PLAYUVER_SUPPORTED_FMT( handler, name, ext ) \ +#define REGIST_PLAYUVER_SUPPORTED_FMT( handler, name, ext ) \ formatElem.formatName = name; \ formatElem.formatExt = lowercase( ext ); \ formatElem.formatFct = handler; \ @@ -66,7 +65,6 @@ typedef struct formatsList.insert( formatsList.end(), new_fmts.begin(), new_fmts.end() ); \ } - /** * \class PlaYUVerStream * \ingroup PlaYUVerLib PlaYUVerLib_Stream @@ -98,7 +96,7 @@ public: String getFormatName(); String getCodecName(); - Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); + Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); Bool open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); Bool reload(); Void close(); @@ -134,7 +132,6 @@ public: return m_bInit; } - Void getDuration( Int* duration_array ); private: diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 04bbab1..445fff9 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -29,7 +29,6 @@ #include "PlaYUVerStream.h" #include "PlaYUVerFrame.h" - #define REGISTER_STREAM_HANDLER(X) \ public: \ static PlaYUVerStreamHandlerIf* Create() { return new X(); } \ @@ -43,7 +42,7 @@ class PlaYUVerStreamHandlerIf { friend class PlaYUVerStream; -public: + public: PlaYUVerStreamHandlerIf() { m_bIsInput = true; diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 55e1ac6..58b2db5 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -28,7 +28,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" - std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -152,7 +151,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } - m_strFormatName = uppercase (strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); + m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); const char *name = avcodec_get_name( m_cCodecCtx->codec_id ); // sprintf( m_acCodecName, "%s", name ); m_strCodecName = name; @@ -215,7 +214,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) } if( m_iPixelFormat == PlaYUVerFrame::NO_FMT ) { - throw PlaYUVerFailure("Cannot open file using FFmpeg libs - unsupported pixel format"); + throw PlaYUVerFailure( "Cannot open file using FFmpeg libs - unsupported pixel format" ); return false; } @@ -273,7 +272,6 @@ Bool StreamHandlerLibav::configureBuffer( PlaYUVerFrame* pcFrame ) return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); } - UInt64 StreamHandlerLibav::calculateFrameNumber() { UInt64 num_frames; @@ -355,7 +353,7 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) // av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, // m_cCodecCtx->height, 1 ); av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, - m_cCodecCtx->height, 1 ); + m_cCodecCtx->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); @@ -378,4 +376,3 @@ Bool StreamHandlerLibav::seek( UInt64 iFrameNum ) return true; } - diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 9d10861..4e23c94 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -49,18 +49,15 @@ extern "C" #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" - struct AVFormatContext; struct AVCodecContext; struct AVStream; struct AVStream; struct AVPacket; - - class StreamHandlerLibav: public PlaYUVerStreamHandlerIf { - REGISTER_STREAM_HANDLER( StreamHandlerLibav ) +REGISTER_STREAM_HANDLER( StreamHandlerLibav ) public: diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index f424c96..f994b94 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -31,7 +31,6 @@ using cv::Mat; using cv::VideoCapture; - std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -68,13 +67,13 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) m_strFormatName = "DEV"; m_strCodecName = "Raw Video"; pcVideoCapture = new VideoCapture( 0 ); - m_uiWidth = pcVideoCapture->get( CV_CAP_PROP_FRAME_WIDTH ); + m_uiWidth = pcVideoCapture->get( CV_CAP_PROP_FRAME_WIDTH ); m_uiHeight = pcVideoCapture->get( CV_CAP_PROP_FRAME_HEIGHT ); m_dFrameRate = 25; } else { - m_strCodecName = m_strFormatName = uppercase (strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); + m_strCodecName = m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); Mat cvMat = cv::imread( m_cFilename ); m_uiWidth = cvMat.cols; m_uiHeight = cvMat.rows; @@ -146,4 +145,3 @@ Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) return bRet; } - diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index f1ce3ef..aa02b0f 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -34,15 +34,14 @@ namespace cv { - class VideoCapture; +class VideoCapture; } - class PlaYUVerFrame; class StreamHandlerOpenCV: public PlaYUVerStreamHandlerIf { - REGISTER_STREAM_HANDLER( StreamHandlerOpenCV ) +REGISTER_STREAM_HANDLER( StreamHandlerOpenCV ) public: diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index c0f0e88..df8460d 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -29,7 +29,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" - Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; @@ -44,10 +43,12 @@ Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) if( m_bIsInput ) { char line[101]; - while( fgets( line, 100, m_pFile ) && line[0] == '#' ); - sscanf( line,"P%d", &m_iMagicNumber ); - while( fgets( line, 100, m_pFile ) && line[0] == '#' ); - sscanf( line,"%u %u", &m_uiWidth, &m_uiHeight ); + while( fgets( line, 100, m_pFile ) && line[0] == '#' ) + ; + sscanf( line, "P%d", &m_iMagicNumber ); + while( fgets( line, 100, m_pFile ) && line[0] == '#' ) + ; + sscanf( line, "%u %u", &m_uiWidth, &m_uiHeight ); if( m_iMagicNumber == 1 || m_iMagicNumber == 4 ) { @@ -57,10 +58,11 @@ Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) } else { - while( fgets( line, 100, m_pFile ) && line[0] == '#' ); - sscanf( line,"%d", &m_iMaxValue ); - m_uiBitsPerPixel = log( m_iMaxValue + 1 )/log( 2 ); - m_iPixelFormat = m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; + while( fgets( line, 100, m_pFile ) && line[0] == '#' ) + ; + sscanf( line, "%d", &m_iMaxValue ); + m_uiBitsPerPixel = log( m_iMaxValue + 1 ) / log( 2 ); + m_iPixelFormat = m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; } } else @@ -103,7 +105,6 @@ Bool StreamHandlerPortableMap::configureBuffer( PlaYUVerFrame* pcFrame ) return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); } - UInt64 StreamHandlerPortableMap::calculateFrameNumber() { return 1; @@ -116,7 +117,7 @@ Bool StreamHandlerPortableMap::seek( UInt64 iFrameNum ) Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; pcFrame->frameFromBuffer( m_pStreamBuffer ); @@ -132,10 +133,9 @@ Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) fprintf( m_pFile, "%d\n", m_iMaxValue ); } pcFrame->frameToBuffer( m_pStreamBuffer ); - UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; return true; } - diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index aedd582..f762f4c 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -32,16 +32,19 @@ #include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" - class PlaYUVerFrame; class StreamHandlerPortableMap: public PlaYUVerStreamHandlerIf { - REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) +REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) public: - StreamHandlerPortableMap() {} - ~StreamHandlerPortableMap() {} + StreamHandlerPortableMap() + { + } + ~StreamHandlerPortableMap() + { + } Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 8af6ce8..e84d3d6 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -28,7 +28,6 @@ #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" - Bool StreamHandlerRaw::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; @@ -54,7 +53,6 @@ Bool StreamHandlerRaw::configureBuffer( PlaYUVerFrame* pcFrame ) return getMem1D( &m_pStreamBuffer, pcFrame->getBytesPerFrame() ); } - UInt64 StreamHandlerRaw::calculateFrameNumber() { if( !m_pFile || m_uiNBytesPerFrame == 0 ) @@ -77,7 +75,7 @@ Bool StreamHandlerRaw::seek( UInt64 iFrameNum ) Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; pcFrame->frameFromBuffer( m_pStreamBuffer ); @@ -87,10 +85,9 @@ Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) Bool StreamHandlerRaw::write( PlaYUVerFrame* pcFrame ) { pcFrame->frameToBuffer( m_pStreamBuffer ); - UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; return true; } - diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index fe451bb..f51e1d4 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -28,21 +28,24 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerStreamHandlerIf.h" - /** * \class StreamHandlerRaw * \brief Class to handle raw video format */ class StreamHandlerRaw: public PlaYUVerStreamHandlerIf { - REGISTER_STREAM_HANDLER( StreamHandlerRaw ) +REGISTER_STREAM_HANDLER( StreamHandlerRaw ) private: FILE* m_pFile; /**< The input file pointer >*/ public: - StreamHandlerRaw() {} - ~StreamHandlerRaw() {} + StreamHandlerRaw() + { + } + ~StreamHandlerRaw() + { + } Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); @@ -52,7 +55,6 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - }; #endif // __STREAMHANDLERRAW_H__ diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 0792e57..985c7c0 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -25,7 +25,6 @@ #include "AbsoluteFrameDifference.h" #include - AbsoluteFrameDifference::AbsoluteFrameDifference() { /* Module Definition */ @@ -48,7 +47,7 @@ Bool AbsoluteFrameDifference::create( std::vector apcFrameList ) _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) return false; m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); @@ -81,5 +80,3 @@ Void AbsoluteFrameDifference::destroy() m_pcFrameDifference = NULL; } - - diff --git a/modules/AbsoluteFrameDifference.h b/modules/AbsoluteFrameDifference.h index 5f2aa34..e4956e4 100644 --- a/modules/AbsoluteFrameDifference.h +++ b/modules/AbsoluteFrameDifference.h @@ -29,7 +29,6 @@ #include - class AbsoluteFrameDifference: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( AbsoluteFrameDifference ) diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index 2ac0e0a..506eb61 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -26,7 +26,6 @@ #include "DisparityStereoBM.h" - DisparityStereoBM::DisparityStereoBM() { /* Module Definition */ @@ -111,5 +110,3 @@ Void DisparityStereoBM::destroy() m_pcDisparityFrame = NULL; } - - diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index 247d5d8..7f851b4 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -31,7 +31,6 @@ #include - class DisparityStereoBM: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( DisparityStereoBM ) @@ -40,11 +39,11 @@ private: PlaYUVerFrame* m_pcDisparityFrame; Int m_uiNumberOfDisparities; UInt m_uiBlockSize; -#if( CV_MAJOR_VERSION == 2) + #if( CV_MAJOR_VERSION == 2) cv::StereoBM m_cStereoBM; #else cv::Ptr m_cStereoBM; -#endif + #endif public: DisparityStereoBM(); diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index c6065fd..ae2b562 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -26,7 +26,6 @@ #include "DisparityStereoSGBM.h" - DisparityStereoSGBM::DisparityStereoSGBM() { /* Module Definition */ @@ -114,5 +113,3 @@ Void DisparityStereoSGBM::destroy() m_pcDisparityFrame = NULL; } - - diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index 074b816..394208a 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -43,7 +43,6 @@ #include - class DisparityStereoSGBM: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( DisparityStereoSGBM ) @@ -53,9 +52,9 @@ private: Bool m_bUseHH; Int m_uiNumberOfDisparities; UInt m_uiBlockSize; -#if( CV_MAJOR_VERSION == 3) + #if( CV_MAJOR_VERSION == 3) cv::Ptr m_cStereoMatch; -#else + #else cv::StereoSGBM m_cStereoMatch; #endif diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index b1e8764..a6052d5 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -26,7 +26,6 @@ #include "DisparityStereoVar.h" - DisparityStereoVar::DisparityStereoVar() { /* Module Definition */ @@ -83,5 +82,3 @@ Void DisparityStereoVar::destroy() m_pcDisparityFrame = NULL; } - - diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 66c1f85..68cb490 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -31,15 +31,14 @@ #include - class DisparityStereoVar: public PlaYUVerModuleIf { - REGISTER_CLASS_FACTORY( DisparityStereoVar ) +REGISTER_CLASS_FACTORY( DisparityStereoVar ) private: PlaYUVerFrame* m_pcDisparityFrame; cv::StereoVar m_cStereoVar; -public: + public: DisparityStereoVar(); virtual ~DisparityStereoVar() { diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index e77635e..938f81c 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -24,7 +24,6 @@ #include "EightBitsSampling.h" - EightBitsSampling::EightBitsSampling() { /* Module Definition */ @@ -80,5 +79,3 @@ Void EightBitsSampling::destroy() m_pcSubSampledFrame = NULL; } - - diff --git a/modules/EightBitsSampling.h b/modules/EightBitsSampling.h index d643436..8adb69c 100644 --- a/modules/EightBitsSampling.h +++ b/modules/EightBitsSampling.h @@ -27,14 +27,13 @@ #include "lib/PlaYUVerModuleIf.h" - class EightBitsSampling: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( EightBitsSampling ) private: PlaYUVerFrame* m_pcSubSampledFrame; -public: + public: EightBitsSampling(); virtual ~EightBitsSampling() { diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index 0e88faa..05dc32e 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -26,7 +26,6 @@ #include #include "FilterComponent.h" - FilterComponentModule::FilterComponentModule() { m_pcFilteredFrame = NULL; @@ -130,5 +129,3 @@ PlaYUVerFrame* FilterComponentChromaV::process( std::vector apcF return filterComponent( apcFrameList[0], CHROMA_V ); } - - diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index 3f623b9..f9b86a6 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -27,12 +27,11 @@ #include "lib/PlaYUVerModuleIf.h" - class FilterComponentModule: public PlaYUVerModuleIf { private: PlaYUVerFrame* m_pcFilteredFrame; -public: + public: FilterComponentModule(); virtual ~FilterComponentModule() { @@ -48,7 +47,7 @@ public: class FilterComponentLuma: public FilterComponentModule { REGISTER_CLASS_FACTORY( FilterComponentLuma ) -public: + public: FilterComponentLuma(); virtual ~FilterComponentLuma() { @@ -60,7 +59,7 @@ public: class FilterComponentChromaU: public FilterComponentModule { REGISTER_CLASS_FACTORY( FilterComponentChromaU ) -public: + public: FilterComponentChromaU(); virtual ~FilterComponentChromaU() { @@ -72,7 +71,7 @@ public: class FilterComponentChromaV: public FilterComponentModule { REGISTER_CLASS_FACTORY( FilterComponentChromaV ) -public: + public: FilterComponentChromaV(); virtual ~FilterComponentChromaV() { diff --git a/modules/FrameBinarization.cpp b/modules/FrameBinarization.cpp index 5afacac..5ea8d58 100644 --- a/modules/FrameBinarization.cpp +++ b/modules/FrameBinarization.cpp @@ -24,7 +24,6 @@ #include "FrameBinarization.h" - FrameBinarization::FrameBinarization() { /* Module Definition */ @@ -67,5 +66,3 @@ Void FrameBinarization::destroy() m_pcBinFrame = NULL; } - - diff --git a/modules/FrameBinarization.h b/modules/FrameBinarization.h index 3d472ef..4b53a0a 100644 --- a/modules/FrameBinarization.h +++ b/modules/FrameBinarization.h @@ -27,7 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" - class FrameBinarization: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameBinarization ) @@ -35,7 +34,7 @@ REGISTER_CLASS_FACTORY( FrameBinarization ) private: PlaYUVerFrame* m_pcBinFrame; UInt m_uiThreshold; -public: + public: FrameBinarization(); virtual ~FrameBinarization() { diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index 2c57a64..82f8082 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -24,7 +24,6 @@ #include "FrameCrop.h" - FrameCrop::FrameCrop() { /* Module Definition */ @@ -75,5 +74,3 @@ Void FrameCrop::destroy() m_pcCropedFrame = NULL; } - - diff --git a/modules/FrameCrop.h b/modules/FrameCrop.h index df8bf8b..f0d859a 100644 --- a/modules/FrameCrop.h +++ b/modules/FrameCrop.h @@ -27,7 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" - class FrameCrop: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameCrop ) @@ -38,7 +37,7 @@ private: UInt m_uiYPosition; Int m_iXSize; Int m_iYSize; -public: + public: FrameCrop(); virtual ~FrameCrop() { diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index dd4deaa..bbfefde 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -25,7 +25,6 @@ #include "FrameDifference.h" #include - FrameDifference::FrameDifference() { /* Module Definition */ @@ -103,5 +102,3 @@ Void FrameDifference::destroy() m_pcFrameDifference = NULL; } - - diff --git a/modules/FrameDifference.h b/modules/FrameDifference.h index cb497ca..da43c63 100644 --- a/modules/FrameDifference.h +++ b/modules/FrameDifference.h @@ -29,7 +29,6 @@ #include - class FrameDifference: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameDifference ) diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index d29cd7b..f5f6f7e 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -26,7 +26,6 @@ #include class be; - FrameMask::FrameMask() { /* Module Definition */ @@ -53,13 +52,13 @@ Bool FrameMask::create( std::vector apcFrameList ) for( UInt i = 1; i < apcFrameList.size(); i++ ) { if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE_IGNORE_GRAY | - PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) { return false; } } - m_iWeight = m_iWeight > 100 || m_iWeight < 0 ? 5 : m_iWeight; + m_iWeight = m_iWeight > 100 || m_iWeight < 0 ? 5 : m_iWeight; m_iWeight = m_iWeight > 10 ? m_iWeight / 10 : m_iWeight; Int iPelFmt = 0; @@ -109,7 +108,7 @@ PlaYUVerFrame* FrameMask::process( std::vector apcFrameList ) Bool FrameMask::keyPressed( enum Module_Key_Supported value ) { - if( value == MODULE_KEY_UP && m_iWeight < 10) + if( value == MODULE_KEY_UP && m_iWeight < 10 ) { m_iWeight += 1; return true; @@ -122,7 +121,6 @@ Bool FrameMask::keyPressed( enum Module_Key_Supported value ) return false; } - Void FrameMask::destroy() { if( m_pcFrameProcessed ) @@ -132,5 +130,3 @@ Void FrameMask::destroy() m_pcFrameProcessed = NULL; } - - diff --git a/modules/FrameMask.h b/modules/FrameMask.h index 1a2cd56..09d0430 100644 --- a/modules/FrameMask.h +++ b/modules/FrameMask.h @@ -29,10 +29,9 @@ #include - class FrameMask: public PlaYUVerModuleIf { - REGISTER_CLASS_FACTORY( FrameMask ) +REGISTER_CLASS_FACTORY( FrameMask ) private: Int m_iWeight; @@ -52,6 +51,3 @@ public: #endif // __FRAMEMASK_H__ - - - diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index 257d599..04020b6 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -24,7 +24,6 @@ #include "FrameShift.h" - FrameShift::FrameShift() { /* Module Definition */ @@ -93,7 +92,6 @@ PlaYUVerFrame* FrameShift::process( std::vector apcFrameList ) yStartIn = iShiftVerChroma >= 0 ? 0 : -iShiftVerChroma; yEndOut = iShiftVerChroma >= 0 ? m_pcProcessedFrame->getChromaHeight() : m_pcProcessedFrame->getChromaHeight() + iShiftVerChroma; - for( UInt c = 1; c < m_pcProcessedFrame->getNumberChannels(); c++ ) { for( UInt y = yStartOut, yIn = yStartIn; y < yEndOut; y++, yIn++ ) @@ -144,5 +142,3 @@ Void FrameShift::destroy() m_pcProcessedFrame = NULL; } - - diff --git a/modules/FrameShift.h b/modules/FrameShift.h index 4e79c19..758c972 100644 --- a/modules/FrameShift.h +++ b/modules/FrameShift.h @@ -27,7 +27,6 @@ #include "lib/PlaYUVerModuleIf.h" - class FrameShift: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameShift ) @@ -36,12 +35,12 @@ private: PlaYUVerFrame* m_pcProcessedFrame; Int m_iShiftHor; Int m_iShiftVer; -public: + public: FrameShift(); virtual ~FrameShift() { } - Bool create( std::vector apcFrameList); + Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Bool keyPressed( enum Module_Key_Supported value ); Void destroy(); diff --git a/modules/LumaAverage.h b/modules/LumaAverage.h index 6b5889a..4b51482 100644 --- a/modules/LumaAverage.h +++ b/modules/LumaAverage.h @@ -22,16 +22,14 @@ * \brief Luma frame average */ - #ifndef __LUMAAVERAGE_H__ #define __LUMAAVERAGE_H__ #include "lib/PlaYUVerModuleIf.h" - class LumaAverage: public PlaYUVerModuleIf { - REGISTER_CLASS_FACTORY( LumaAverage ) +REGISTER_CLASS_FACTORY( LumaAverage ) private: public: diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index d2a8508..26ec038 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -32,8 +32,6 @@ using cv::Ptr; using cv::Point; using cv::Point2f; - - OpticalFlowDualTVL1::OpticalFlowDualTVL1() { /* Module Definition */ @@ -79,7 +77,6 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram Mat_ flow; m_cTvl1->calc( cvMatPrev, cvMatAfter, flow ); - // determine motion range: Double maxrad = 1; @@ -94,17 +91,17 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram } } - Scalar vectorColor( 255,0,0,0 ); + Scalar vectorColor( 255, 0, 0, 0 ); for( int y = m_iStep / 2; y < flow.rows; y += m_iStep ) { for( int x = m_iStep / 2; x < flow.cols; x += m_iStep ) { - Point p = Point( x,y ); + Point p = Point( x, y ); Point2f u = flow( y, x ); Point ui( u.x, u.y ); if( isFlowCorrect( u ) ) - arrowedLine( cvMatAfter, p, p+ui, vectorColor ); + arrowedLine( cvMatAfter, p, p + ui, vectorColor ); } } @@ -119,5 +116,3 @@ Void OpticalFlowDualTVL1::destroy() m_pcOutputFrame = NULL; } - - diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h index 5c77981..fa723a0 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/OpticalFlowDualTVL1.h @@ -29,7 +29,6 @@ #include "lib/PlaYUVerModuleIf.h" - class OpticalFlowDualTVL1: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index 668aa29..d80827d 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -31,7 +31,6 @@ #include "PlaYUVerModuleFactory.h" #include "ModulesListHeader.h" - PlaYUVerModuleFactory::PlaYUVerModuleFactory() { REGISTER_ALL_MODULES @@ -54,7 +53,7 @@ Bool PlaYUVerModuleFactory::RegisterDl( const char* dlName ) if( pHndl == NULL ) { std::cerr << dlerror() - << std::endl; + << std::endl; return false; } CreateModuleFn pfnCreate = ( CreateModuleFn )dlsym( pHndl, "Maker" ); @@ -83,4 +82,3 @@ PlaYUVerModuleIf *PlaYUVerModuleFactory::CreateModule( const char* moduleName ) return NULL; } - diff --git a/modules/PlaYUVerModuleFactory.h b/modules/PlaYUVerModuleFactory.h index 56bb0a1..83bbe94 100644 --- a/modules/PlaYUVerModuleFactory.h +++ b/modules/PlaYUVerModuleFactory.h @@ -29,7 +29,6 @@ #include #include "lib/PlaYUVerModuleIf.h" - #define REGISTER_MODULE(X) Register( "X", &(X::Create) ); typedef PlaYUVerModuleIf* (*CreateModuleFn)( void ); @@ -46,7 +45,7 @@ private: } PlaYUVerModuleFactoryMap m_FactoryMap; -public: + public: ~PlaYUVerModuleFactory(); static PlaYUVerModuleFactory *Get() diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index 3919a98..ae52b76 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -24,7 +24,6 @@ #include "SetChromaHalfScale.h" - SetChromaHalfScale::SetChromaHalfScale() { /* Module Definition */ @@ -69,5 +68,3 @@ Void SetChromaHalfScale::destroy() m_pcProcessedFrame = NULL; } - - diff --git a/modules/SetChromaHalfScale.h b/modules/SetChromaHalfScale.h index 1b0f69e..bcf16ea 100644 --- a/modules/SetChromaHalfScale.h +++ b/modules/SetChromaHalfScale.h @@ -27,14 +27,13 @@ #include "lib/PlaYUVerModuleIf.h" - class SetChromaHalfScale: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( SetChromaHalfScale ) private: PlaYUVerFrame* m_pcProcessedFrame; -public: + public: SetChromaHalfScale(); virtual ~SetChromaHalfScale() { diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 84cb02d..5c75e9f 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -26,7 +26,6 @@ #include #include - WeightedPSNR::WeightedPSNR() { /* Module Definition */ @@ -103,7 +102,6 @@ Double measureWMSE( Int component, PlaYUVerFrame* Org, PlaYUVerFrame* Rec, PlaYU return ssd / Double( count ); } - Double WeightedPSNR::measure( std::vector apcFrameList ) { Double dPSNR = 100; @@ -119,5 +117,3 @@ Void WeightedPSNR::destroy() } - - diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h index dd91602..c9743ca 100644 --- a/modules/WeightedPSNR.h +++ b/modules/WeightedPSNR.h @@ -29,7 +29,6 @@ #include - class WeightedPSNR: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( WeightedPSNR ) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 5c2c1a1..35703d9 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -28,7 +28,6 @@ #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" - PlaYUVerTools::PlaYUVerTools() { m_bVerbose = true; @@ -54,7 +53,6 @@ PlaYUVerTools::~PlaYUVerTools() #define GET_PARAM( X , i ) X[X.size() > i ? i : X.size() - 1] - Int PlaYUVerTools::openInputs() { /** @@ -86,7 +84,7 @@ Int PlaYUVerTools::openInputs() } if( Opts().hasOpt( "endianness" ) ) { - if( GET_PARAM( m_strEndianness, i ) == "big" ) + if( GET_PARAM( m_strEndianness, i )== "big" ) { uiEndianness = 0; } @@ -279,7 +277,8 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) pcModFrame = applyFrameModule(); } PlaYUVerStream* pcModStream = new PlaYUVerStream; - if( !pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), pcModFrame->getEndianness(), 1, false ) ) + if( !pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), + pcModFrame->getEndianness(), 1, false ) ) { delete pcModStream; pcModStream = NULL; @@ -500,4 +499,3 @@ Int PlaYUVerTools::ModuleOperation() return 0; } - diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 1b8634f..d636f31 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -31,7 +31,6 @@ #include "lib/PlaYUVerStream.h" #include "PlaYUVerToolsCmdParser.h" - class PlaYUVerModuleIf; #define MAX_NUMBER_INPUTS 10 @@ -65,7 +64,7 @@ private: Int openInputs(); - typedef Int (PlaYUVerTools::*FpProcess) (); + typedef Int (PlaYUVerTools::*FpProcess)(); FpProcess m_fpProcess; Int64 m_iFrameNum; diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 012f492..83bd08a 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -30,7 +30,6 @@ #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" - PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() { m_uiLogLevel = 0; @@ -83,12 +82,12 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) m_uiLogLevel = LOG_RESULT; } - if( m_cOptions.hasOpt("module") && m_cOptions.hasOpt("help") ) + if( m_cOptions.hasOpt( "module" ) && m_cOptions.hasOpt( "help" ) ) { listModuleHelp(); iRet = 1; } - else if( m_cOptions.hasOpt("help") ) + else if( m_cOptions.hasOpt( "help" ) ) { printf( "Usage: %s modules/quality/save [options] -input=input_file [--output=output_file]\n", argv[0] ); m_cOptions.doHelp( std::cout ); @@ -119,4 +118,3 @@ Void PlaYUVerToolsCmdParser::listModuleHelp() } } - diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 6aa4e12..e5fb046 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -29,7 +29,6 @@ #include "lib/PlaYUVerDefs.h" #include "lib/PlaYUVerOptions.h" - class PlaYUVerStream; class PlaYUVerToolsCmdParser From f0fc355d737fd74e1c6ecd00bd4238f92ed81aca Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 17:42:54 +0100 Subject: [PATCH 058/127] Minor changes to formatter xml --- playuver-codestyle.xml | 312 ++++++++++++++++++++--------------------- 1 file changed, 156 insertions(+), 156 deletions(-) diff --git a/playuver-codestyle.xml b/playuver-codestyle.xml index 308d6d5..ed59ca6 100644 --- a/playuver-codestyle.xml +++ b/playuver-codestyle.xml @@ -1,167 +1,167 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 9d043d6901c893737511b18358d53cca15287060 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 18:28:02 +0100 Subject: [PATCH 059/127] Minor changes in the variables in order to add return of the module progress --- app/PlaYUVerAppModuleIf.cpp | 5 +++-- app/PlaYUVerAppModuleIf.h | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 82ddf83..6998717 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -103,7 +103,7 @@ Bool PlaYUVerAppModuleIf::apply( Bool isPlaying, Bool disableThreads ) Void PlaYUVerAppModuleIf::run() { m_bIsRunning = true; - + m_bSuccess = false; std::vector apcFrameList; for( UInt i = 0; i < m_pcModule->m_uiNumberOfFrames; i++ ) { @@ -136,9 +136,10 @@ Void PlaYUVerAppModuleIf::run() { return; } + m_bSuccess = true; m_bIsRunning = false; #ifdef PLAYUVER_THREADED_MODULES - EventData *eventData = new EventData( true, this ); + EventData *eventData = new EventData( m_bSuccess, this ); if( parent() ) QCoreApplication::postEvent( parent(), eventData ); #endif diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index e80c80c..36b1980 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -55,6 +55,7 @@ class PlaYUVerAppModuleIf private: Bool m_bIsRunning; + Bool m_bSuccess; QAction* m_pcModuleAction; PlaYUVerModuleIf* m_pcModule; @@ -74,7 +75,7 @@ public: class EventData: public QEvent { public: - EventData( bool success = false, PlaYUVerAppModuleIf* module = NULL ) : + EventData( bool success, PlaYUVerAppModuleIf* module ) : QEvent( QEvent::User ) { m_bSuccess = success; From dff464774246ea53a600de6b9fa42cdac0b01785 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 18:29:08 +0100 Subject: [PATCH 060/127] Add motion compensation with optical flow --- modules/OpticalFlowDualTVL1.cpp | 108 ++++++++++++++++++++------------ modules/OpticalFlowDualTVL1.h | 6 ++ 2 files changed, 74 insertions(+), 40 deletions(-) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index 26ec038..b3e0e16 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -35,13 +35,12 @@ using cv::Point2f; OpticalFlowDualTVL1::OpticalFlowDualTVL1() { /* Module Definition */ - m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). - // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. - m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "OpticalFlowDualTVL1"; // Name - m_pchModuleTooltip = "Measure optical flow"; // Description - m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_iModuleAPI = MODULE_API_2; + m_iModuleType = FRAME_PROCESSING_MODULE; + m_pchModuleCategory = "Measurements"; + m_pchModuleName = "OpticalFlowDualTVL1"; + m_pchModuleTooltip = "Measure optical flow"; + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW; m_pcOutputFrame = NULL; } @@ -66,50 +65,79 @@ static inline bool isFlowCorrect( Point2f u ) return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; } +Void OpticalFlowDualTVL1::drawFlow() +{ + Mat cvMatAfter; + m_pcFrameAfter->toMat( cvMatAfter, true ); + Scalar vectorColor( 255, 0, 0, 0 ); + for( int y = m_iStep / 2; y < m_cvFlow.rows; y += m_iStep ) + { + for( int x = m_iStep / 2; x < m_cvFlow.cols; x += m_iStep ) + { + + Point2f u( 0, 0 ); + Double count = 0; + for( int i = ( -m_iStep / 2 ); i < ( m_iStep / 2 ); i++ ) + { + for( int j = ( -m_iStep / 2 ); j < ( m_iStep / 2 ); j++ ) + { + if( isFlowCorrect( u ) ) + { + u = u + m_cvFlow( y, x ); + count++; + } + } + } + if( count > 0 ) + { + Point p = Point( x, y ); + Point ui( u.x / count, u.y / count ); + arrowedLine( cvMatAfter, p, p + ui, vectorColor ); + } + } + } + m_pcOutputFrame->fromMat( cvMatAfter ); +} + +Void OpticalFlowDualTVL1::compensateFlow() +{ + for( Int c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) + { + Pel** pPelPrev = m_pcFramePrev->getPelBufferYUV()[c]; + Pel* pPelOut = m_pcOutputFrame->getPelBufferYUV()[c][0]; + + for( int y = 0; y < m_pcOutputFrame->getHeight( c ); y++ ) + { + for( int x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) + { + Point2f u = m_cvFlow( y, x ); + Point p( x + u.x, y + u.y); + *pPelOut = pPelPrev[p.y][p.x]; + pPelOut++; + } + } + } +} + PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) { + m_pcFramePrev = apcFrameList[0]; + m_pcFrameAfter = apcFrameList[1]; + Mat cvMatPrev, cvMatAfter; - if( !apcFrameList[0]->toMat( cvMatPrev, true ) || !apcFrameList[1]->toMat( cvMatAfter, true ) ) + if( !m_pcFramePrev->toMat( cvMatPrev, true ) || !m_pcFrameAfter->toMat( cvMatAfter, true ) ) { return m_pcOutputFrame; } - Mat_ flow; - m_cTvl1->calc( cvMatPrev, cvMatAfter, flow ); + m_cTvl1->calc( cvMatPrev, cvMatAfter, m_cvFlow ); + compensateFlow(); - // determine motion range: - Double maxrad = 1; - - for( int y = 0; y < flow.rows; y++ ) - { - for( int x = 0; x < flow.cols; x++ ) - { - Point2f u = flow( y, x ); - if( !isFlowCorrect( u ) ) - continue; - maxrad = cv::max( maxrad, sqrt( u.x * u.x + u.y * u.y ) ); - } - } - - Scalar vectorColor( 255, 0, 0, 0 ); - for( int y = m_iStep / 2; y < flow.rows; y += m_iStep ) - { - for( int x = m_iStep / 2; x < flow.cols; x += m_iStep ) - { - Point p = Point( x, y ); - Point2f u = flow( y, x ); - Point ui( u.x, u.y ); - - if( isFlowCorrect( u ) ) - arrowedLine( cvMatAfter, p, p + ui, vectorColor ); - } - } - - m_pcOutputFrame->fromMat( cvMatAfter ); return m_pcOutputFrame; } -Void OpticalFlowDualTVL1::destroy() +Void +OpticalFlowDualTVL1::destroy() { if( m_pcOutputFrame ) delete m_pcOutputFrame; diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h index fa723a0..0a300e2 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/OpticalFlowDualTVL1.h @@ -36,8 +36,14 @@ REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) private: Int m_iStep; cv::Ptr m_cTvl1; + cv::Mat_ m_cvFlow; + PlaYUVerFrame* m_pcFramePrev; + PlaYUVerFrame* m_pcFrameAfter; PlaYUVerFrame* m_pcOutputFrame; + Void drawFlow(); + Void compensateFlow(); + public: OpticalFlowDualTVL1(); virtual ~OpticalFlowDualTVL1() From 45dc010d56d396c59a20b707d277d1c8080db78d Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 19:35:00 +0100 Subject: [PATCH 061/127] Minor changes in PlaYUVerPixFmtDescriptor init --- lib/PlaYUVerFrame.cpp | 6 +- lib/PlaYUVerFrame.h | 2 +- lib/PlaYUVerFramePixelFormats.cpp | 275 +++++++++--------------------- lib/PlaYUVerFramePixelFormats.h | 14 +- 4 files changed, 85 insertions(+), 212 deletions(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index bdff173..d3dc3a8 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -94,7 +94,7 @@ struct PlaYUVerFramePrivate Bool m_bInit; //! Struct with the pixel format description. - PlaYUVerPixFmtDescriptor* m_pcPelFormat; + const PlaYUVerPixFmtDescriptor* m_pcPelFormat; String m_cPelFmtName; UInt m_uiWidth; //!< Width of the frame @@ -145,7 +145,7 @@ PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) : PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : d( new PlaYUVerFramePrivate ) { - PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); + const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) { if( posX % ( 1 << pcPelFormat->log2ChromaWidth ) ) @@ -391,7 +391,7 @@ UInt64 PlaYUVerFrame::getBytesPerFrame() UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ) { - PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[iPixelFormat] ); + const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[iPixelFormat] ); UInt bytesPerPixel = ( bitsPixel - 1 ) / 8 + 1; UInt64 numberBytes = uiWidth * uiHeight; if( pcPelFormat->numberChannels > 1 ) diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 0e6b784..bdfd3ea 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -59,7 +59,7 @@ public: YUYV422, GRAY, RGB24, - BRG24, + BGR24, NUMBER_FORMATS }; diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index d870a56..219eeda 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -24,7 +24,6 @@ #include "config.h" #include "PlaYUVerFramePixelFormats.h" -// #include #ifdef USE_SSE #include @@ -33,6 +32,7 @@ #endif #include "LibMemory.h" +#include "PlaYUVerFrame.h" #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" #endif @@ -199,218 +199,101 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI } #endif -PlaYUVerPixFmtDescriptor yuv420p = +const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_FORMATS] = +{ { - "YUV420p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 1, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), + name: "YUV420p", + colorSpace: PlaYUVerPixel::COLOR_YUV, + numberChannels: 3, + numberPlanes: 3, + log2ChromaWidth: 1, + log2ChromaHeight: 1, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), { - { - 0, - 0, - 1, - 0, - 7 }, /* Y */ - { - 1, - 0, - 1, - 0, - 7 }, /* U */ - { - 2, - 0, - 1, - 0, - 7 }, /* V */ + { 0, 0, 1 }, /* Y */ + { 1, 0, 1 }, /* U */ + { 2, 0, 1 }, /* V */ }, - }; - -PlaYUVerPixFmtDescriptor yuv422p = + }, { - "YUV422p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), + name: "YUV422p", + colorSpace: PlaYUVerPixel::COLOR_YUV, + numberChannels: 3, + numberPlanes: 3, + log2ChromaWidth: 1, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), { - { - 0, - 0, - 1, - 0, - 7 }, /* Y */ - { - 1, - 0, - 1, - 0, - 7 }, /* U */ - { - 2, - 0, - 1, - 0, - 7 }, /* V */ + { 0, 0, 1 }, /* Y */ + { 1, 0, 1 }, /* U */ + { 2, 0, 1 }, /* V */ }, - }; - -PlaYUVerPixFmtDescriptor yuv444p = + }, { - "YUV444p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), + name: "YUV444p", + colorSpace: PlaYUVerPixel::COLOR_YUV, + numberChannels: 3, + numberPlanes: 3, + log2ChromaWidth: 0, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), { - { - 0, - 0, - 1, - 0, - 7 }, /* Y */ - { - 1, - 0, - 1, - 0, - 7 }, /* U */ - { - 2, - 0, - 1, - 0, - 7 }, /* V */ + { 0, 0, 1 }, /* Y */ + { 1, 0, 1 }, /* U */ + { 2, 0, 1 }, /* V */ }, - }; - -PlaYUVerPixFmtDescriptor yuyv422 = + }, { - "YUYV422", - PlaYUVerPixel::COLOR_YUV, - 3, - 1, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), + name: "YUYV422", + colorSpace: PlaYUVerPixel::COLOR_YUV, + numberChannels: 3, + numberPlanes: 1, + log2ChromaWidth: 1, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), { - { - 0, - 1, - 1, - 0, - 7 }, /* Y */ - { - 0, - 3, - 2, - 0, - 7 }, /* U */ - { - 0, - 3, - 4, - 0, - 7 }, /* V */ + { 0, 1, 1 }, /* Y */ + { 0, 3, 2 }, /* U */ + { 0, 3, 4 }, /* V */ }, - }; - -PlaYUVerPixFmtDescriptor gray = + }, { - "GRAY", - PlaYUVerPixel::COLOR_GRAY, - 1, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), - { - { - 0, - 0, - 1, - 0, - 7 } }, /* Y */ - }; - -PlaYUVerPixFmtDescriptor RGB24 = + name: "GRAY", + colorSpace: PlaYUVerPixel::COLOR_GRAY, + numberChannels: 1, + numberPlanes: 1, + log2ChromaWidth: 0, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), + { { 0, 0, 1 } }, /* Y */ + }, { - "RGB24", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + name: "RGB24", + colorSpace: PlaYUVerPixel::COLOR_RGB, + numberChannels: 3, + numberPlanes: 1, + log2ChromaWidth: 0, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), { - { - 0, - 2, - 1, - 0, - 7 }, /* R */ - { - 0, - 2, - 2, - 0, - 7 }, /* G */ - { - 0, - 2, - 3, - 0, - 7 }, /* B */ + { 0, 2, 1 }, /* R */ + { 0, 2, 2 }, /* G */ + { 0, 2, 3 }, /* B */ }, - }; - -PlaYUVerPixFmtDescriptor BGR24 = + }, { - "BGR24", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), + name: "BGR24", + colorSpace: PlaYUVerPixel::COLOR_RGB, + numberChannels: 3, + numberPlanes: 1, + log2ChromaWidth: 0, + log2ChromaHeight: 0, + ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), { - { - 0, - 2, - 3, - 0, - 7 }, /* R */ - { - 0, - 2, - 2, - 0, - 7 }, /* G */ - { - 0, - 2, - 1, - 0, - 7 }, /* B */ + { 0, 2, 3}, /* R */ + { 0, 2, 2}, /* G */ + { 0, 2, 1}, /* B */ }, - }; - -PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS] = - { - yuv420p, - yuv444p, - yuv422p, - yuyv422, - gray, - RGB24, - BGR24, - }; + } +}; diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index 2036b44..dbb2bec 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -75,16 +75,6 @@ typedef struct PlaYUVerComponentDescriptor */ UInt16 offset_plus1; - /** - * Number of least significant bits that must be shifted away - * to get the value. - */ - UInt16 shift; - - /** - * Number of bits in the component minus 1. - */ - UInt16 depth_minus1; } PlaYUVerComponentDescriptor; /** @@ -140,7 +130,7 @@ typedef struct PlaYUVerPixFmtDescriptor #define MAX_NUMBER_PLANES 3 -#define PLAYUVER_NUMBER_FORMATS 7 -extern PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PLAYUVER_NUMBER_FORMATS]; +#define PLAYUVER_NUMBER_FORMATS 3 +extern const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[]; #endif // __PLAYUVERFRAMEPIXELFORMATS_H__ From 3adb6e659c719914151f603fbd78172eeb1819bc Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 4 May 2016 23:28:48 +0100 Subject: [PATCH 062/127] Roll-back changes to pixel formats --- lib/PlaYUVerFramePixelFormats.cpp | 98 +++++++++++++++---------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 219eeda..2e67c8b 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -202,13 +202,13 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_FORMATS] = { { - name: "YUV420p", - colorSpace: PlaYUVerPixel::COLOR_YUV, - numberChannels: 3, - numberPlanes: 3, - log2ChromaWidth: 1, - log2ChromaHeight: 1, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), + "YUV420p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 1, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), { { 0, 0, 1 }, /* Y */ { 1, 0, 1 }, /* U */ @@ -216,13 +216,13 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - name: "YUV422p", - colorSpace: PlaYUVerPixel::COLOR_YUV, - numberChannels: 3, - numberPlanes: 3, - log2ChromaWidth: 1, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), + "YUV422p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), { { 0, 0, 1 }, /* Y */ { 1, 0, 1 }, /* U */ @@ -230,13 +230,13 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - name: "YUV444p", - colorSpace: PlaYUVerPixel::COLOR_YUV, - numberChannels: 3, - numberPlanes: 3, - log2ChromaWidth: 0, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), + "YUV444p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), { { 0, 0, 1 }, /* Y */ { 1, 0, 1 }, /* U */ @@ -244,13 +244,13 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - name: "YUYV422", - colorSpace: PlaYUVerPixel::COLOR_YUV, - numberChannels: 3, - numberPlanes: 1, - log2ChromaWidth: 1, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), + "YUYV422", + PlaYUVerPixel::COLOR_YUV, + 3, + 1, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), { { 0, 1, 1 }, /* Y */ { 0, 3, 2 }, /* U */ @@ -258,23 +258,23 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - name: "GRAY", - colorSpace: PlaYUVerPixel::COLOR_GRAY, - numberChannels: 1, - numberPlanes: 1, - log2ChromaWidth: 0, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), + "GRAY", + PlaYUVerPixel::COLOR_GRAY, + 1, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), { { 0, 0, 1 } }, /* Y */ }, { - name: "RGB24", - colorSpace: PlaYUVerPixel::COLOR_RGB, - numberChannels: 3, - numberPlanes: 1, - log2ChromaWidth: 0, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + "RGB24", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), { { 0, 2, 1 }, /* R */ { 0, 2, 2 }, /* G */ @@ -282,13 +282,13 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - name: "BGR24", - colorSpace: PlaYUVerPixel::COLOR_RGB, - numberChannels: 3, - numberPlanes: 1, - log2ChromaWidth: 0, - log2ChromaHeight: 0, - ffmpegPelFormat: ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), + "BGR24", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), { { 0, 2, 3}, /* R */ { 0, 2, 2}, /* G */ From 52643ff30608094c11cbc5155d94ec36e962ef2a Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 5 May 2016 00:08:10 +0100 Subject: [PATCH 063/127] Change some initialization to port to C++11 --- CMakeLists.txt | 7 ++++++- lib/PlaYUVerFrame.cpp | 27 +++++++++++++++++---------- lib/PlaYUVerFrame.h | 14 +++----------- lib/PlaYUVerFramePixelFormats.cpp | 2 +- lib/PlaYUVerFramePixelFormats.h | 21 --------------------- lib/StreamHandlerLibav.cpp | 2 +- 6 files changed, 28 insertions(+), 45 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 07f5e04..1779dac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -117,8 +117,13 @@ IF( WIN32 ) ENDIF() ###################################################################################### -# Target App +# Configure targets ###################################################################################### + +if(CMAKE_COMPILER_IS_GNUCXX) + ADD_DEFINITIONS(-std=gnu++0x) +endif() + IF (NOT CMAKE_BUILD_TYPE ) MESSAGE(STATUS "No build type selected, default to Release") SET(CMAKE_BUILD_TYPE "Release") diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index d3dc3a8..78afef7 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -39,18 +39,17 @@ */ std::vector PlaYUVerFrame::supportedColorSpacesListNames() { - std::vector colorSpaceList; - colorSpaceList.push_back( "YUV" ); - colorSpaceList.push_back( "RGB" ); - colorSpaceList.push_back( "GRAY" ); - return colorSpaceList; + return std::vector{ + "YUV", + "RGB", + "GRAY", + }; } std::vector PlaYUVerFrame::supportedPixelFormatListNames() { std::vector formatsList; - Int numberFormats = PLAYUVER_NUMBER_FORMATS; - for( Int i = 0; i < numberFormats; i++ ) + for( Int i = 0; i < NUMBER_PEL_FORMATS; i++ ) { formatsList.push_back( g_PlaYUVerPixFmtDescriptorsList[i].name ); } @@ -60,8 +59,7 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames() std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int colorSpace ) { std::vector formatsList; - Int numberFormats = PLAYUVER_NUMBER_FORMATS; - for( Int i = 0; i < numberFormats; i++ ) + for( Int i = 0; i < NUMBER_PEL_FORMATS; i++ ) { if( g_PlaYUVerPixFmtDescriptorsList[i].colorSpace == colorSpace ) formatsList.push_back( g_PlaYUVerPixFmtDescriptorsList[i].name ); @@ -71,7 +69,7 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int colorSpace Int PlaYUVerFrame::findPixelFormat( String name ) { - for( Int i = 0; i < PLAYUVER_NUMBER_FORMATS; i++ ) + for( Int i = 0; i < NUMBER_PEL_FORMATS; i++ ) { if( g_PlaYUVerPixFmtDescriptorsList[i].name == name ) return i; @@ -1137,6 +1135,15 @@ Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) ************************************************************** */ +std::vector PlaYUVerFrame::supportedQualityMetricsList() +{ + return std::vector { + "PSNR", + "MSE", + "SSIM", + }; +} + Double PlaYUVerFrame::getQuality( Int Metric, PlaYUVerFrame* Org, Int component ) { switch( Metric ) diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index bdfd3ea..4541f3e 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -47,7 +47,7 @@ class PlaYUVerFrame { public: - /** ColorSpace Enum (deprecated) + /** ColorSpace Enum * List of supported pixel formats - do not change order */ enum PixelFormats @@ -60,7 +60,7 @@ public: GRAY, RGB24, BGR24, - NUMBER_FORMATS + NUMBER_PEL_FORMATS }; /** Format match opts @@ -249,15 +249,7 @@ public: NUMBER_METRICS, }; - static std::vector supportedQualityMetricsList() - { - std::vector metrics; - metrics.push_back( "PSNR" ); - metrics.push_back( "MSE" ); - metrics.push_back( "SSIM" ); - return metrics; - } - + static std::vector supportedQualityMetricsList(); Double getQuality( Int Metric, PlaYUVerFrame* Org, Int component ); Double getMSE( PlaYUVerFrame* Org, Int component ); Double getPSNR( PlaYUVerFrame* Org, Int component ); diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 2e67c8b..2bd4374 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -199,7 +199,7 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI } #endif -const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_FORMATS] = +const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_PEL_FORMATS] = { { "YUV420p", diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index dbb2bec..fa8426b 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -33,26 +33,6 @@ #define CHROMARATIO( SIZE, RATIO ) ( RATIO > 1 ? ( ( SIZE + 1 ) / RATIO ) : SIZE ) -inline Int pelRed( UInt rgb ) // get red part of RGB -{ - return ( ( rgb >> 16 ) & 0xff ); -} - -inline Int pelGreen( UInt rgb ) // get green part of RGB -{ - return ( ( rgb >> 8 ) & 0xff ); -} - -inline Int pelBlue( UInt rgb ) // get blue part of RGB -{ - return ( rgb & 0xff ); -} - -inline Int pelAlpha( UInt rgb ) // get alpha part of RGBA -{ - return rgb >> 24; -} - #define PEL_RGB( r, g, b ) \ ( 0xffu << 24 ) | ( ( r & 0xff ) << 16 ) | ( ( g & 0xff ) << 8 ) | ( b & 0xff ) @@ -130,7 +110,6 @@ typedef struct PlaYUVerPixFmtDescriptor #define MAX_NUMBER_PLANES 3 -#define PLAYUVER_NUMBER_FORMATS 3 extern const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[]; #endif // __PLAYUVERFRAMEPIXELFORMATS_H__ diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 58b2db5..accfec4 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -204,7 +204,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) m_uiHeight = m_cCodecCtx->height; m_iPixelFormat = PlaYUVerFrame::NO_FMT; - for( Int i = 0; i < PLAYUVER_NUMBER_FORMATS; i++ ) + for( Int i = 0; i < PlaYUVerFrame::NUMBER_PEL_FORMATS; i++ ) { if( g_PlaYUVerPixFmtDescriptorsList[i].ffmpegPelFormat == pix_fmt ) { From a72ba2f7b1faa1e401b1ca4f6849e97afbf9e66b Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 5 May 2016 00:22:21 +0100 Subject: [PATCH 064/127] Fix signed/unsigned warning --- modules/OpticalFlowDualTVL1.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index b3e0e16..fdd412e 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -101,14 +101,14 @@ Void OpticalFlowDualTVL1::drawFlow() Void OpticalFlowDualTVL1::compensateFlow() { - for( Int c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) + for( UInt c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) { Pel** pPelPrev = m_pcFramePrev->getPelBufferYUV()[c]; Pel* pPelOut = m_pcOutputFrame->getPelBufferYUV()[c][0]; - for( int y = 0; y < m_pcOutputFrame->getHeight( c ); y++ ) + for( UInt y = 0; y < m_pcOutputFrame->getHeight( c ); y++ ) { - for( int x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) + for( UInt x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) { Point2f u = m_cvFlow( y, x ); Point p( x + u.x, y + u.y); From 617c42563d7c69245696c77b09ea6609e0fac64c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 9 May 2016 01:20:06 +0100 Subject: [PATCH 065/127] Add options --- modules/OpticalFlowDualTVL1.cpp | 13 ++++++++++--- modules/OpticalFlowDualTVL1.h | 1 + 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp index fdd412e..bd619b8 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlowDualTVL1.cpp @@ -41,8 +41,14 @@ OpticalFlowDualTVL1::OpticalFlowDualTVL1() m_pchModuleName = "OpticalFlowDualTVL1"; m_pchModuleTooltip = "Measure optical flow"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW; + m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + + m_cModuleOptions.addOptions()/**/ + ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + + m_bShowReconstruction = false; m_pcOutputFrame = NULL; + } Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) @@ -121,8 +127,8 @@ Void OpticalFlowDualTVL1::compensateFlow() PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) { - m_pcFramePrev = apcFrameList[0]; - m_pcFrameAfter = apcFrameList[1]; + m_pcFrameAfter = apcFrameList[0]; + m_pcFramePrev = apcFrameList[1]; Mat cvMatPrev, cvMatAfter; if( !m_pcFramePrev->toMat( cvMatPrev, true ) || !m_pcFrameAfter->toMat( cvMatAfter, true ) ) @@ -131,6 +137,7 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram } m_cTvl1->calc( cvMatPrev, cvMatAfter, m_cvFlow ); +// drawFlow(); compensateFlow(); return m_pcOutputFrame; diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h index 0a300e2..eb7c012 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/OpticalFlowDualTVL1.h @@ -34,6 +34,7 @@ class OpticalFlowDualTVL1: public PlaYUVerModuleIf REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) private: + Bool m_bShowReconstruction; Int m_iStep; cv::Ptr m_cTvl1; cv::Mat_ m_cvFlow; From d7d3e9f4ea5e8aa8101cc28a66c8fbd63928b218 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 9 May 2016 01:20:33 +0100 Subject: [PATCH 066/127] Change exceptions handle to the PlaYUVerExcpetions --- app/PlaYUVerApp.cpp | 12 ++++++------ app/VideoSubWindow.cpp | 2 +- lib/PlaYUVerStream.cpp | 3 ++- lib/PlaYUVerStreamHandlerIf.h | 2 ++ 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 178f451..93c84ca 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -239,10 +239,10 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) videoSubWindow->close(); } } - catch( const char *msg ) + catch( PlaYUVerFailure& e ) { videoSubWindow->close(); - QString warningMsg = "Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + msg; + QString warningMsg = "Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); } @@ -329,10 +329,10 @@ Void PlaYUVerApp::save() { saveWindow->save( fileName ); } - catch( const char *msg ) + catch( PlaYUVerFailure& e ) { QApplication::restoreOverrideCursor(); - QString warningMsg = "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + msg; + QString warningMsg = "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); return; @@ -353,9 +353,9 @@ Void PlaYUVerApp::format() addStreamInfoToRecentList( pcVideoSubWindow->getStreamInfo() ); } } - catch( const char *msg ) + catch( PlaYUVerFailure& e ) { - QString warningMsg = "Cannot change format of " + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + " with the following error: \n" + msg; + QString warningMsg = "Cannot change format of " + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); qDebug( ) << warningMsg; diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 7dc7798..04a46a1 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -330,7 +330,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) { m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate, true ); } - catch( const char *msg ) + catch( ... ) { if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index c8e6f4d..2a14846 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -237,7 +237,7 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel, m_pcHandler->m_iEndianness ); } - catch( const char *msg ) + catch( PlaYUVerFailure& e ) { close(); throw PlaYUVerFailure( "PlaYUVerStream", "Cannot allocated frame buffer" ); @@ -308,6 +308,7 @@ Void PlaYUVerStream::close() return; m_pcHandler->closeHandler(); + m_pcHandler->Delete(); if( m_ppcFrameBuffer ) { diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 445fff9..0f4ae59 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -57,6 +57,8 @@ class PlaYUVerStreamHandlerIf { } + virtual void Delete() = 0; + virtual Bool openHandler( String strFilename, Bool bInput ) = 0; virtual Void closeHandler() = 0; virtual Bool configureBuffer( PlaYUVerFrame* pcFrame ) = 0; From e3e55b880afebba32f119d6847063929527a1186 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 10 May 2016 22:37:31 +0100 Subject: [PATCH 067/127] ../tools/PlaYUVerTools.cpp Use constant for variable declarations --- tools/PlaYUVerTools.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 35703d9..a71dfcc 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -22,9 +22,13 @@ * \brief Main definition of the PlaYUVerTools APp */ +#include "PlaYUVerTools.h" + #include #include -#include "PlaYUVerTools.h" + +#include "lib/PlaYUVerPixel.h" +#include "lib/PlaYUVerFrame.h" #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" @@ -337,7 +341,7 @@ Int PlaYUVerTools::QualityOperation() const char *pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); PlaYUVerFrame* apcCurrFrame[MAX_NUMBER_INPUTS]; Bool abEOF[MAX_NUMBER_INPUTS]; - Double adAverageQuality[MAX_NUMBER_INPUTS - 1][m_uiNumberOfComponents]; + Double adAverageQuality[MAX_NUMBER_INPUTS - 1][PlaYUVerPixel::MAX_NUMBER_COMPONENTS]; Double dQuality; String metric_fmt = " "; From 8b71f023edaae45f86fd558c99112c6ed034e3e6 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 10 May 2016 22:39:41 +0100 Subject: [PATCH 068/127] Add missing include --- app/PlaYUVerSubWindowHandle.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index 1a0332f..78850ce 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include From 155257fe41e09f35b507164e20491a094ed7a4d4 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 11 May 2016 00:15:56 +0100 Subject: [PATCH 069/127] Fix cmake errors in windows installation --- CMakeLists.txt | 1 - cmake/Win32.cmake | 7 ++++--- modules/CMakeLists.txt | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1779dac..bc46035 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -176,5 +176,4 @@ MESSAGE( STATUS " Static libs: " "${USE_STATIC}" ) MESSAGE( STATUS " Build type: " "${CMAKE_BUILD_TYPE}" ) MESSAGE( STATUS " Build flags: " "${CMAKE_CXX_FLAGS}" ) - FEATURE_SUMMARY(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/cmake/Win32.cmake b/cmake/Win32.cmake index 833bbce..9030f69 100644 --- a/cmake/Win32.cmake +++ b/cmake/Win32.cmake @@ -14,6 +14,7 @@ INSTALL(FILES ${MSVC_DLL_DIR}/msvcr120.dll DESTINATION bin ) INSTALL(FILES ${MSVC_DLL_DIR}/msvcp120.dll DESTINATION bin ) SET(QT_DIR "QT-Dir" CACHE PATH "Where to find QT Lib on Windows") +SET(QT_ICU_VERSION "" CACHE STRING "Qt ICU version of dll's" ) SET(QT_DLL_POSTFIX "" CACHE STRING "Postfix to dll's name for debug" ) SET(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH} ${QT_DIR}" ) @@ -26,9 +27,9 @@ IF( NOT USE_QT4 ) INSTALL(FILES ${QT_DIR}/bin/Qt5Widgets${QT_DLL_POSTFIX}.dll DESTINATION bin ) INSTALL(FILES ${QT_DIR}/bin/libGLESv2${QT_DLL_POSTFIX}.dll DESTINATION bin ) INSTALL(FILES ${QT_DIR}/bin/libEGL${QT_DLL_POSTFIX}.dll DESTINATION bin ) - INSTALL(FILES ${QT_DIR}/bin/icudt52.dll DESTINATION bin ) - INSTALL(FILES ${QT_DIR}/bin/icuin52.dll DESTINATION bin ) - INSTALL(FILES ${QT_DIR}/bin/icuuc52.dll DESTINATION bin ) + INSTALL(FILES ${QT_DIR}/bin/icudt${QT_ICU_VERSION}.dll DESTINATION bin ) + INSTALL(FILES ${QT_DIR}/bin/icuin${QT_ICU_VERSION}.dll DESTINATION bin ) + INSTALL(FILES ${QT_DIR}/bin/icuuc${QT_ICU_VERSION}.dll DESTINATION bin ) INSTALL(FILES ${QT_DIR}/plugins/platforms/qminimal.dll DESTINATION bin/platforms ) INSTALL(FILES ${QT_DIR}/plugins/platforms/qoffscreen.dll DESTINATION bin/platforms ) INSTALL(FILES ${QT_DIR}/plugins/platforms/qwindows.dll DESTINATION bin/platforms ) diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 1971450..ed2b6ca 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -54,13 +54,13 @@ ENDIF() file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "// This files add the header files of each module\n" "#ifndef __MODULESLISTHEADER_H__\n#define __MODULESLISTHEADER_H__\n" ) -foreach(module ${MODULES_LIST_FILES} ) +foreach(module ${MODULES_LIST_FILES}) file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${module}.h\"\n") -endforeach(module_Name) +endforeach(module ${MODULES_LIST_FILES}) file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#define REGISTER_ALL_MODULES \\\n" ) -foreach(module ${MODULES_LIST_NAME} ) +foreach(module ${MODULES_LIST_NAME}) file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "Register( \"${module}\", &(${module}::Create) ); \\\n") -endforeach(module_Name) +endforeach(module ${MODULES_LIST_NAME}) file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "\n#endif // __MODULESLISTHEADER_H__\n" ) INCLUDE_DIRECTORIES( ${OpenCV_INCLUDE_DIRS} ) From 6cfa9e776c49af0d822fd150232c26d61395d2da Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 13 May 2016 00:12:08 +0100 Subject: [PATCH 070/127] Add optical flow module based on the optflow module of OpenCV --- CMakeLists.txt | 3 + modules/CMakeLists.txt | 8 +- ...pticalFlowDualTVL1.cpp => OpticalFlow.cpp} | 98 +++++++++++++++---- .../{OpticalFlowDualTVL1.h => OpticalFlow.h} | 58 ++++++++--- 4 files changed, 135 insertions(+), 32 deletions(-) rename modules/{OpticalFlowDualTVL1.cpp => OpticalFlow.cpp} (67%) rename modules/{OpticalFlowDualTVL1.h => OpticalFlow.h} (59%) diff --git a/CMakeLists.txt b/CMakeLists.txt index bc46035..5520cc8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -94,9 +94,12 @@ ENDIF(DOXYGEN_FOUND) SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) OPTION( USE_OPENCV "Add OpenCV support" ON ) +SET( OPENCV_OPTFLOW_FOUND OFF ) IF( USE_OPENCV ) FIND_PACKAGE( OpenCV ) SET(USE_OPENCV ${OpenCV_FOUND}) + ## Check + LIST(FIND OpenCV_LIB_COMPONENTS opencv_optflow OpenCV_optflow_FOUND) ENDIF() SET_PACKAGE_PROPERTIES(OpenCV PROPERTIES URL "http://opencv.willowgarage.com" DESCRIPTION "OpenCV library support in PlaYUVerFrame" TYPE OPTIONAL) diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index ed2b6ca..ccdfdcf 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -40,8 +40,12 @@ ADD_MODULE( EightBitsSampling "EightBitsSampling" ) ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) ADD_MODULE( WeightedPSNR "WeightedPSNR" ) -IF( USE_OPENCV ) - ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" ) +IF( OpenCV_FOUND ) + IF( OPENCV_OPTFLOW_FOUND ) + ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlow" ) + ADD_MODULE( OpticalFlowSparseToDense "OpticalFlow" ) + ADD_MODULE( OpticalFlowFarneback "OpticalFlow" ) + ENDIF() ADD_MODULE( DisparityStereoBM "DisparityStereoBM" ) ADD_MODULE( DisparityStereoSGBM "DisparityStereoSGBM" ) #ADD_MODULE( DisparityStereoVar "DisparityStereoVar" ) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlow.cpp similarity index 67% rename from modules/OpticalFlowDualTVL1.cpp rename to modules/OpticalFlow.cpp index bd619b8..76d2f5d 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/OpticalFlow.cpp @@ -18,13 +18,22 @@ */ /** - * \file OpticalFlowDualTVL1.cpp - * \brief Absolute Frame Difference module + * \file OpticalFlow.cpp + * \brief Modules to measure optical flow */ -#include "OpticalFlowDualTVL1.h" +// Own +#include "OpticalFlow.h" + +// System #include +// Opencv +#include +#include +#include +#include + using cv::Scalar; using cv::Mat; using cv::Mat_; @@ -32,14 +41,13 @@ using cv::Ptr; using cv::Point; using cv::Point2f; -OpticalFlowDualTVL1::OpticalFlowDualTVL1() + +OpticalFlowModule::OpticalFlowModule() { /* Module Definition */ m_iModuleAPI = MODULE_API_2; m_iModuleType = FRAME_PROCESSING_MODULE; - m_pchModuleCategory = "Measurements"; - m_pchModuleName = "OpticalFlowDualTVL1"; - m_pchModuleTooltip = "Measure optical flow"; + m_pchModuleCategory = "OpticalFlow"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; @@ -51,7 +59,7 @@ OpticalFlowDualTVL1::OpticalFlowDualTVL1() } -Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) +Bool OpticalFlowModule::commonCreate( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ @@ -60,7 +68,6 @@ Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) return false; m_iStep = 16; - m_cTvl1 = cv::createOptFlow_DualTVL1(); m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); return true; @@ -71,7 +78,7 @@ static inline bool isFlowCorrect( Point2f u ) return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; } -Void OpticalFlowDualTVL1::drawFlow() +Void OpticalFlowModule::drawFlow() { Mat cvMatAfter; m_pcFrameAfter->toMat( cvMatAfter, true ); @@ -105,7 +112,7 @@ Void OpticalFlowDualTVL1::drawFlow() m_pcOutputFrame->fromMat( cvMatAfter ); } -Void OpticalFlowDualTVL1::compensateFlow() +Void OpticalFlowModule::compensateFlow() { for( UInt c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) { @@ -125,7 +132,7 @@ Void OpticalFlowDualTVL1::compensateFlow() } } -PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) +PlaYUVerFrame* OpticalFlowModule::process( std::vector apcFrameList ) { m_pcFrameAfter = apcFrameList[0]; m_pcFramePrev = apcFrameList[1]; @@ -136,18 +143,75 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram return m_pcOutputFrame; } - m_cTvl1->calc( cvMatPrev, cvMatAfter, m_cvFlow ); -// drawFlow(); - compensateFlow(); + m_cOpticalFlow->calc( cvMatAfter, cvMatPrev, m_cvFlow ); + if( m_bShowReconstruction ) + compensateFlow(); + else + drawFlow(); return m_pcOutputFrame; } -Void -OpticalFlowDualTVL1::destroy() +Void OpticalFlowModule::destroy() { if( m_pcOutputFrame ) delete m_pcOutputFrame; m_pcOutputFrame = NULL; +// if( m_cOpticalFlow ) +// delete m_cOpticalFlow; + } +OpticalFlowDualTVL1::OpticalFlowDualTVL1() +{ + /* Module Definition */ + m_pchModuleName = "OpticalFlowDualTVL1"; + m_pchModuleTooltip = "Measure optical flow using DualTVL1 method"; + +} + +Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) +{ + Bool bRet = commonCreate( apcFrameList ); + if( !bRet ) + return bRet; + m_cOpticalFlow = cv::createOptFlow_DualTVL1(); + return bRet; +} + +OpticalFlowSparseToDense::OpticalFlowSparseToDense() +{ + /* Module Definition */ + m_pchModuleName = "OpticalFlowSparseToDense"; + m_pchModuleTooltip = "Measure optical flow using SparseToDense method"; + +} + +Bool OpticalFlowSparseToDense::create( std::vector apcFrameList ) +{ + Bool bRet = commonCreate( apcFrameList ); + if( !bRet ) + return bRet; + m_cOpticalFlow = cv::optflow::createOptFlow_SparseToDense(); + return bRet; +} + +OpticalFlowFarneback::OpticalFlowFarneback() +{ + /* Module Definition */ + m_pchModuleName = "OpticalFlowFarneback"; + m_pchModuleTooltip = "Measure optical flow using Farneback method"; + +} + +Bool OpticalFlowFarneback::create( std::vector apcFrameList ) +{ + Bool bRet = commonCreate( apcFrameList ); + if( !bRet ) + return bRet; + m_cOpticalFlow = cv::optflow::createOptFlow_Farneback(); + return bRet; +} + + + diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlow.h similarity index 59% rename from modules/OpticalFlowDualTVL1.h rename to modules/OpticalFlow.h index eb7c012..c008419 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/OpticalFlow.h @@ -18,43 +18,75 @@ */ /** - * \file OpticalFlowDualTVL1.h - * \brief Absolute Frame Difference module + * \file OpticalFlow.h + * \brief Modules to measure optical flow */ #ifndef __OPTICALFLOWDUALTVL1_H__ #define __OPTICALFLOWDUALTVL1_H__ -#include +// OpenCV +#include +#include +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -class OpticalFlowDualTVL1: public PlaYUVerModuleIf +class OpticalFlowModule: public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) - -private: +protected: Bool m_bShowReconstruction; Int m_iStep; - cv::Ptr m_cTvl1; + cv::Ptr m_cOpticalFlow; cv::Mat_ m_cvFlow; PlaYUVerFrame* m_pcFramePrev; PlaYUVerFrame* m_pcFrameAfter; PlaYUVerFrame* m_pcOutputFrame; - Void drawFlow(); Void compensateFlow(); + Bool commonCreate( std::vector apcFrameList ); +public: + OpticalFlowModule(); + virtual ~OpticalFlowModule() + { + } + PlaYUVerFrame* process( std::vector apcFrameList ); + Void destroy(); +}; + +class OpticalFlowDualTVL1: public OpticalFlowModule +{ + REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) public: OpticalFlowDualTVL1(); virtual ~OpticalFlowDualTVL1() { } Bool create( std::vector apcFrameList ); - PlaYUVerFrame* process( std::vector apcFrameList ); - Void destroy(); - }; -#endif // __OPTICALFLOWDUALTVL1_H__ +class OpticalFlowSparseToDense: public OpticalFlowModule +{ + REGISTER_CLASS_FACTORY( OpticalFlowSparseToDense ) +public: + OpticalFlowSparseToDense(); + virtual ~OpticalFlowSparseToDense() + { + } + Bool create( std::vector apcFrameList ); +}; + +class OpticalFlowFarneback: public OpticalFlowModule +{ + REGISTER_CLASS_FACTORY( OpticalFlowFarneback ) +public: + OpticalFlowFarneback(); + virtual ~OpticalFlowFarneback() + { + } + Bool create( std::vector apcFrameList ); +}; + +#endif // __OPTICALFLOW_H__ From d31fcc5290f1b07e22976c21494fbee82e99aa96 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 13 May 2016 00:16:19 +0100 Subject: [PATCH 071/127] Add OpticalFlowDualTVL1 when extra OpenCV optflow module is not available --- modules/CMakeLists.txt | 2 + modules/OpticalFlowDualTVL1.cpp | 155 ++++++++++++++++++++++++++++++++ modules/OpticalFlowDualTVL1.h | 60 +++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 modules/OpticalFlowDualTVL1.cpp create mode 100644 modules/OpticalFlowDualTVL1.h diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index ccdfdcf..4349c19 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -45,6 +45,8 @@ IF( OpenCV_FOUND ) ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlow" ) ADD_MODULE( OpticalFlowSparseToDense "OpticalFlow" ) ADD_MODULE( OpticalFlowFarneback "OpticalFlow" ) + ELSE() + ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" ) ENDIF() ADD_MODULE( DisparityStereoBM "DisparityStereoBM" ) ADD_MODULE( DisparityStereoSGBM "DisparityStereoSGBM" ) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/OpticalFlowDualTVL1.cpp new file mode 100644 index 0000000..0e99a63 --- /dev/null +++ b/modules/OpticalFlowDualTVL1.cpp @@ -0,0 +1,155 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file OpticalFlowDualTVL1.cpp + * \brief Absolute Frame Difference module + */ + +#include "OpticalFlowDualTVL1.h" +#include + +using cv::Scalar; +using cv::Mat; +using cv::Mat_; +using cv::Ptr; +using cv::Point; +using cv::Point2f; + +OpticalFlowDualTVL1::OpticalFlowDualTVL1() +{ + /* Module Definition */ + m_iModuleAPI = MODULE_API_2; + m_iModuleType = FRAME_PROCESSING_MODULE; + m_pchModuleCategory = "Measurements"; + m_pchModuleName = "OpticalFlowDualTVL1"; + m_pchModuleTooltip = "Measure optical flow"; + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; + m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + + m_cModuleOptions.addOptions()/**/ + ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + + m_bShowReconstruction = false; + m_pcOutputFrame = NULL; + +} + +Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) +{ + _BASIC_MODULE_API_2_CHECK_ + + for( UInt i = 1; i < apcFrameList.size(); i++ ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + return false; + + m_iStep = 16; + m_cTvl1 = cv::createOptFlow_DualTVL1(); + m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + + return true; +} + +static inline bool isFlowCorrect( Point2f u ) +{ + return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; +} + +Void OpticalFlowDualTVL1::drawFlow() +{ + Mat cvMatAfter; + m_pcFrameAfter->toMat( cvMatAfter, true ); + Scalar vectorColor( 255, 0, 0, 0 ); + for( int y = m_iStep / 2; y < m_cvFlow.rows; y += m_iStep ) + { + for( int x = m_iStep / 2; x < m_cvFlow.cols; x += m_iStep ) + { + + Point2f u( 0, 0 ); + Double count = 0; + for( int i = ( -m_iStep / 2 ); i < ( m_iStep / 2 ); i++ ) + { + for( int j = ( -m_iStep / 2 ); j < ( m_iStep / 2 ); j++ ) + { + if( isFlowCorrect( u ) ) + { + u = u + m_cvFlow( y, x ); + count++; + } + } + } + if( count > 0 ) + { + Point p = Point( x, y ); + Point ui( u.x / count, u.y / count ); + arrowedLine( cvMatAfter, p, p + ui, vectorColor ); + } + } + } + m_pcOutputFrame->fromMat( cvMatAfter ); +} + +Void OpticalFlowDualTVL1::compensateFlow() +{ + for( UInt c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) + { + Pel** pPelPrev = m_pcFramePrev->getPelBufferYUV()[c]; + Pel* pPelOut = m_pcOutputFrame->getPelBufferYUV()[c][0]; + + for( UInt y = 0; y < m_pcOutputFrame->getHeight( c ); y++ ) + { + for( UInt x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) + { + Point2f u = m_cvFlow( y, x ); + Point p( x + u.x, y + u.y); + *pPelOut = pPelPrev[p.y][p.x]; + pPelOut++; + } + } + } +} + +PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) +{ + m_pcFrameAfter = apcFrameList[0]; + m_pcFramePrev = apcFrameList[1]; + + Mat cvMatPrev, cvMatAfter; + if( !m_pcFramePrev->toMat( cvMatPrev, true ) || !m_pcFrameAfter->toMat( cvMatAfter, true ) ) + { + return m_pcOutputFrame; + } + + m_cTvl1->calc( cvMatPrev, cvMatAfter, m_cvFlow ); + if( m_bShowReconstruction ) + compensateFlow(); + else + drawFlow(); + + return m_pcOutputFrame; +} + +Void +OpticalFlowDualTVL1::destroy() +{ + if( m_pcOutputFrame ) + delete m_pcOutputFrame; + m_pcOutputFrame = NULL; +} + diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h new file mode 100644 index 0000000..eb7c012 --- /dev/null +++ b/modules/OpticalFlowDualTVL1.h @@ -0,0 +1,60 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file OpticalFlowDualTVL1.h + * \brief Absolute Frame Difference module + */ + +#ifndef __OPTICALFLOWDUALTVL1_H__ +#define __OPTICALFLOWDUALTVL1_H__ + +#include + +#include "lib/PlaYUVerModuleIf.h" + +class OpticalFlowDualTVL1: public PlaYUVerModuleIf +{ +REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) + +private: + Bool m_bShowReconstruction; + Int m_iStep; + cv::Ptr m_cTvl1; + cv::Mat_ m_cvFlow; + PlaYUVerFrame* m_pcFramePrev; + PlaYUVerFrame* m_pcFrameAfter; + PlaYUVerFrame* m_pcOutputFrame; + + Void drawFlow(); + Void compensateFlow(); + +public: + OpticalFlowDualTVL1(); + virtual ~OpticalFlowDualTVL1() + { + } + Bool create( std::vector apcFrameList ); + PlaYUVerFrame* process( std::vector apcFrameList ); + Void destroy(); + +}; + +#endif // __OPTICALFLOWDUALTVL1_H__ + From c2a75fd21773c4d8c64e9d01c653408e59a8264a Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 13 May 2016 15:58:38 +0100 Subject: [PATCH 072/127] Disable doxygen --- CMakeLists.txt | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5520cc8..dab6c1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -85,13 +85,11 @@ SET( CMAKE_CXX_FLAGS "" ) # Dependencies ###################################################################################### - -OPTION( USE_OPENCV "Add OpenCV support" ON ) -find_package(Doxygen) -IF(DOXYGEN_FOUND) - SET( PLAYUVER_BUILD_DOC ON ) -ENDIF(DOXYGEN_FOUND) -SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) +# find_package(Doxygen) +# IF(DOXYGEN_FOUND) +# SET( PLAYUVER_BUILD_DOC ON ) +# ENDIF(DOXYGEN_FOUND) +# SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) OPTION( USE_OPENCV "Add OpenCV support" ON ) SET( OPENCV_OPTFLOW_FOUND OFF ) From bb10282b6e1ecb57e5b201e2cd157a4263eb45a6 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 13 May 2016 22:44:57 +0100 Subject: [PATCH 073/127] Fix errors with opencv includes --- lib/PlaYUVerFrame.cpp | 2 +- modules/OpticalFlow.cpp | 4 +--- modules/OpticalFlow.h | 4 ++-- modules/OpticalFlowDualTVL1.h | 3 ++- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 78afef7..3a5098d 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -27,7 +27,7 @@ #include #ifdef USE_OPENCV -#include +#include #endif #include "LibMemory.h" diff --git a/modules/OpticalFlow.cpp b/modules/OpticalFlow.cpp index 76d2f5d..95648bc 100644 --- a/modules/OpticalFlow.cpp +++ b/modules/OpticalFlow.cpp @@ -29,9 +29,7 @@ #include // Opencv -#include -#include -#include +// #include #include using cv::Scalar; diff --git a/modules/OpticalFlow.h b/modules/OpticalFlow.h index c008419..de739a6 100644 --- a/modules/OpticalFlow.h +++ b/modules/OpticalFlow.h @@ -26,8 +26,8 @@ #define __OPTICALFLOWDUALTVL1_H__ // OpenCV -#include -#include +#include +#include // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" diff --git a/modules/OpticalFlowDualTVL1.h b/modules/OpticalFlowDualTVL1.h index eb7c012..0623577 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/OpticalFlowDualTVL1.h @@ -25,7 +25,8 @@ #ifndef __OPTICALFLOWDUALTVL1_H__ #define __OPTICALFLOWDUALTVL1_H__ -#include +#include +#include #include "lib/PlaYUVerModuleIf.h" From a5f0a74bff2961a640238e45b16901085cbef268 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 13 May 2016 23:07:29 +0100 Subject: [PATCH 074/127] Add functions for adding modules and specify opencv module --- CMakeLists.txt | 1 + cmake/ModulesFct.cmake | 45 +++++++++++++++++++++++++++++++++++++ modules/CMakeLists.txt | 50 +++++++++--------------------------------- 3 files changed, 56 insertions(+), 40 deletions(-) create mode 100644 cmake/ModulesFct.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index dab6c1b..6620773 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,6 +116,7 @@ IF( WIN32 ) SET( USE_STATIC ON ) INCLUDE( cmake/Win32.cmake ) ENDIF() +INCLUDE( cmake/ModulesFct.cmake ) ###################################################################################### # Configure targets diff --git a/cmake/ModulesFct.cmake b/cmake/ModulesFct.cmake new file mode 100644 index 0000000..cc99ac5 --- /dev/null +++ b/cmake/ModulesFct.cmake @@ -0,0 +1,45 @@ + + +MACRO(ADD_MODULE name file ) + set(__modulename "Module${name}") + OPTION(MODULE_${name} "Use module ${name}" ON ) + ADD_FEATURE_INFO(${name} MODULE_${name} "Module ${name}" ) + if( MODULE_${name} ) + list(APPEND plaYUver_Mod_SRCS ${file} ) + LIST(APPEND MODULES_LIST_NAME ${name} ) + LIST(APPEND MODULES_LIST_FILES ${file} ) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${file}.h\"\n") + endif() + unset(__modulename) +ENDMACRO() + + +MACRO(ADD_MODULE_OPENCV name file version ) + IF( ${OpenCV_FOUND} AND ( NOT ( ${OpenCV_VERSION} VERSION_LESS ${version} ) ) ) + ADD_MODULE( ${name} ${file} ) + ENDIF() +ENDMACRO() + + +# +# Create header +# + +MACRO(CREATE_MODULE_MACROS ) + + file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "// This files add the header files of each module\n" + + "#ifndef __MODULESLISTHEADER_H__\n#define __MODULESLISTHEADER_H__\n" ) + + foreach(module ${MODULES_LIST_FILES}) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${module}.h\"\n") + endforeach(module ${MODULES_LIST_FILES}) + + file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#define REGISTER_ALL_MODULES \\\n" ) + foreach(module ${MODULES_LIST_NAME}) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "Register( \"${module}\", &(${module}::Create) ); \\\n") + endforeach(module ${MODULES_LIST_NAME}) + + file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "\n#endif // __MODULESLISTHEADER_H__\n" ) + +ENDMACRO() diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 4349c19..55d5f82 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -10,20 +10,6 @@ set(plaYUver_Mod_SRCS PlaYUVerModuleFactory.cpp ) -MACRO(ADD_MODULE name file ) - set(__modulename "Module${name}") - OPTION(MODULE_${name} "Use module ${name}" ON ) - ADD_FEATURE_INFO(${name} MODULE_${name} "Module ${name}" ) - if( MODULE_${name} ) - list(APPEND plaYUver_Mod_SRCS ${file} ) - LIST(APPEND MODULES_LIST_NAME ${name} ) - LIST(APPEND MODULES_LIST_FILES ${file} ) - file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${file}.h\"\n") - endif() - unset(__modulename) -ENDMACRO() - - # # Modules List # @@ -40,35 +26,19 @@ ADD_MODULE( EightBitsSampling "EightBitsSampling" ) ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) ADD_MODULE( WeightedPSNR "WeightedPSNR" ) -IF( OpenCV_FOUND ) - IF( OPENCV_OPTFLOW_FOUND ) - ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlow" ) - ADD_MODULE( OpticalFlowSparseToDense "OpticalFlow" ) - ADD_MODULE( OpticalFlowFarneback "OpticalFlow" ) - ELSE() - ADD_MODULE( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" ) - ENDIF() - ADD_MODULE( DisparityStereoBM "DisparityStereoBM" ) - ADD_MODULE( DisparityStereoSGBM "DisparityStereoSGBM" ) - #ADD_MODULE( DisparityStereoVar "DisparityStereoVar" ) +IF( OPENCV_OPTFLOW_FOUND ) + ADD_MODULE_OPENCV( OpticalFlowDualTVL1 "OpticalFlow" 3.1.0 ) + ADD_MODULE_OPENCV( OpticalFlowSparseToDense "OpticalFlow" 3.1.0 ) + ADD_MODULE_OPENCV( OpticalFlowFarneback "OpticalFlow" 3.1.0 ) +ELSE() + ADD_MODULE_OPENCV( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" 2.4.13.0 ) ENDIF() +ADD_MODULE_OPENCV( DisparityStereoBM "DisparityStereoBM" 2.4.8 ) +ADD_MODULE_OPENCV( DisparityStereoSGBM "DisparityStereoSGBM" 2.4.8 ) +# ADD_MODULE_OPENCV( DisparityStereoVar "DisparityStereoVar" ) -# -# Create header -# -file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "// This files add the header files of each module\n" - - "#ifndef __MODULESLISTHEADER_H__\n#define __MODULESLISTHEADER_H__\n" ) -foreach(module ${MODULES_LIST_FILES}) - file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#include \"${module}.h\"\n") -endforeach(module ${MODULES_LIST_FILES}) -file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "#define REGISTER_ALL_MODULES \\\n" ) -foreach(module ${MODULES_LIST_NAME}) - file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "Register( \"${module}\", &(${module}::Create) ); \\\n") -endforeach(module ${MODULES_LIST_NAME}) -file( APPEND ${CMAKE_CURRENT_BINARY_DIR}/ModulesListHeader.h "\n#endif // __MODULESLISTHEADER_H__\n" ) - +CREATE_MODULE_MACROS() INCLUDE_DIRECTORIES( ${OpenCV_INCLUDE_DIRS} ) ADD_LIBRARY( PlaYUVerModules ${plaYUver_Mod_SRCS} ) TARGET_LINK_LIBRARIES( PlaYUVerModules PlaYUVerLib ${OpenCV_LIBRARIES} -ldl ) From 77c1a78157928cb1d2343626d1f5f21094ce9a17 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 14 May 2016 00:05:51 +0100 Subject: [PATCH 075/127] Fix wrong variable name --- modules/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 55d5f82..a69dcaa 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -26,7 +26,7 @@ ADD_MODULE( EightBitsSampling "EightBitsSampling" ) ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) ADD_MODULE( WeightedPSNR "WeightedPSNR" ) -IF( OPENCV_OPTFLOW_FOUND ) +IF( OpenCV_optflow_FOUND ) ADD_MODULE_OPENCV( OpticalFlowDualTVL1 "OpticalFlow" 3.1.0 ) ADD_MODULE_OPENCV( OpticalFlowSparseToDense "OpticalFlow" 3.1.0 ) ADD_MODULE_OPENCV( OpticalFlowFarneback "OpticalFlow" 3.1.0 ) From e18558eb4679299b730166b9046ab05e3a7a441c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 14 May 2016 02:30:42 +0100 Subject: [PATCH 076/127] Add new function to control opencv based modules --- CMakeLists.txt | 121 ++++++++++-------- app/CMakeLists.txt | 8 +- cmake/ModulesFct.cmake | 23 +++- modules/CMakeLists.txt | 21 +-- ...VL1.cpp => MeasureOpticalFlowDualTVL1.cpp} | 18 +-- ...ualTVL1.h => MeasureOpticalFlowDualTVL1.h} | 16 +-- modules/OpticalFlow.cpp | 1 - 7 files changed, 119 insertions(+), 89 deletions(-) rename modules/{OpticalFlowDualTVL1.cpp => MeasureOpticalFlowDualTVL1.cpp} (88%) rename modules/{OpticalFlowDualTVL1.h => MeasureOpticalFlowDualTVL1.h} (81%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6620773..6998e51 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,6 +4,13 @@ cmake_minimum_required( VERSION 2.8.9 ) +###################################################################################### +# CMake functions +###################################################################################### +SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ) +INCLUDE( cmake/ModulesFct.cmake ) +INCLUDE(FeatureSummary) + ###################################################################################### # Project Definition ###################################################################################### @@ -20,27 +27,31 @@ set( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLA # Variables ###################################################################################### -OPTION( PLAYUVER_BUILD_APP "Build GUI Application" ON ) -OPTION( PLAYUVER_BUILD_TOOLS "Build Command Line Application" ON ) -OPTION( PLAYUVER_BUILD_EXAMPLES "Build Examples" OFF ) -OPTION( PLAYUVER_BUILD_DOC "Build Documentation" OFF ) -OPTION( USE_SSE "Build with SSE support" OFF ) +OPTION( BUILD_APP "Build GUI Application" ON ) +OPTION( BUILD_TOOLS "Build Command Line Application" ON ) +OPTION( BUILD_EXAMPLES "Build Examples" OFF ) +OPTION( BUILD_DOC "Build Documentation" OFF ) + OPTION( USE_FERVOR "Add Fervor support" OFF ) + +OPTION( USE_DYNLOAD "Use dynamic load of modules" ON ) +OPTION( USE_SSE "Build with SSE support" OFF ) OPTION( USE_WERROR "Warnings as errors" OFF ) OPTION( USE_STATIC "Use static libs" OFF ) -OPTION( USE_QT4 "Build with Qt4" OFF ) -OPTION( USE_QTDBUS "Build with QtDBus" ON ) -OPTION( USE_DYNLOAD "Use dynamic load of modules" ON ) + + +###################################################################################### +# Release configuration +###################################################################################### + # To be switched on when releasing. OPTION(RELEASE_BUILD "Remove Git revision from program version (use for stable releases)" ON) - - # Get current version. set(PLAYUVER_VERSION_STRING "${PLAYUVER_VERSION}") if(NOT RELEASE_BUILD AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git) # Probably a Git workspace; determine the revision. - find_package(Git QUIET) + FIND_PACKAGE(Git QUIET) if(GIT_FOUND) exec_program(${GIT_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR} @@ -67,6 +78,45 @@ SET(UPDATE_CHANNEL "stable" CACHE STRING "Update channel" ) CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/PlaYUVerUpdate.xml.in ${CMAKE_CURRENT_BINARY_DIR}/PlaYUVerUpdate-${UPDATE_CHANNEL}.xml ) +###################################################################################### +# Dependencies +###################################################################################### + +IF( BUILD_DOC ) + FIND_PACKAGE(Doxygen) + SET( BUILD_DOC ${Doxygen_FOUND} ) +ENDIF() +SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) + +OPTION( USE_OPENCV "Add OpenCV support" ON ) +SET( OPENCV_OPTFLOW_FOUND OFF ) +IF( USE_OPENCV ) + FIND_PACKAGE( OpenCV REQUIRED core highgui video ) + LIST(APPEND OPENCV_MODULES core highgui video ) + SET(USE_OPENCV ${OpenCV_FOUND}) + ## Check +# LIST(FIND OpenCV_LIB_COMPONENTS opencv_optflow OpenCV_optflow_FOUND) +ENDIF() +SET_PACKAGE_PROPERTIES(OpenCV PROPERTIES URL "http://opencv.willowgarage.com" DESCRIPTION "OpenCV library support in PlaYUVerFrame" TYPE OPTIONAL) + +OPTION( USE_FFMPEG "Add FFMPEG support" ON ) +IF( USE_FFMPEG ) + FIND_PACKAGE( FFmpeg ) + SET(USE_FFMPEG ${FFMPEG_FOUND}) +ENDIF() +SET_PACKAGE_PROPERTIES(FFmpeg PROPERTIES URL "http://ffmpeg.org/" DESCRIPTION "Libav library support in PlaYUVerStream" TYPE OPTIONAL) + +ADD_FEATURE_INFO(DynLoad USE_DYNLOAD "Support for dynamic module load" ) +ADD_FEATURE_INFO(SSE USE_SSE "SSE instructions support" ) +ADD_FEATURE_INFO(WErrors USE_WERROR "Warnings as errors" ) + + +IF( WIN32 ) + SET( USE_STATIC ON ) + INCLUDE( cmake/Win32.cmake ) +ENDIF() + + ###################################################################################### # CMake Defin1itions ###################################################################################### @@ -81,43 +131,6 @@ IF(DEFINED CMAKE_BUILD_TYPE AND CMAKE_VERSION VERSION_GREATER "2.8") ENDIF() SET( CMAKE_CXX_FLAGS "" ) -###################################################################################### -# Dependencies -###################################################################################### - -# find_package(Doxygen) -# IF(DOXYGEN_FOUND) -# SET( PLAYUVER_BUILD_DOC ON ) -# ENDIF(DOXYGEN_FOUND) -# SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPTION "Doxygen" TYPE OPTIONAL) - -OPTION( USE_OPENCV "Add OpenCV support" ON ) -SET( OPENCV_OPTFLOW_FOUND OFF ) -IF( USE_OPENCV ) - FIND_PACKAGE( OpenCV ) - SET(USE_OPENCV ${OpenCV_FOUND}) - ## Check - LIST(FIND OpenCV_LIB_COMPONENTS opencv_optflow OpenCV_optflow_FOUND) -ENDIF() -SET_PACKAGE_PROPERTIES(OpenCV PROPERTIES URL "http://opencv.willowgarage.com" DESCRIPTION "OpenCV library support in PlaYUVerFrame" TYPE OPTIONAL) - -OPTION( USE_FFMPEG "Add FFMPEG support" ON ) -IF( USE_FFMPEG ) - FIND_PACKAGE( FFmpeg ) - SET(USE_FFMPEG ${FFMPEG_FOUND}) -ENDIF() -SET_PACKAGE_PROPERTIES(FFmpeg PROPERTIES URL "http://ffmpeg.org/" DESCRIPTION "Libav library support in PlaYUVerStream" TYPE OPTIONAL) - -ADD_FEATURE_INFO(SSE USE_SSE "SSE instructions support" ) -ADD_FEATURE_INFO(WErrors USE_WERROR "Warnings as errors" ) - - -IF( WIN32 ) - SET( USE_STATIC ON ) - INCLUDE( cmake/Win32.cmake ) -ENDIF() -INCLUDE( cmake/ModulesFct.cmake ) - ###################################################################################### # Configure targets ###################################################################################### @@ -141,8 +154,8 @@ SET( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g" ) SET( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2" ) -ADD_FEATURE_INFO(PlaYUVerApp PLAYUVER_BUILD_APP "Build Graphical Interface") -ADD_FEATURE_INFO(PlaYUVerTools PLAYUVER_BUILD_TOOLS "Build Command line tool" ) +ADD_FEATURE_INFO(PlaYUVerApp BUILD_APP "Build Graphical Interface") +ADD_FEATURE_INFO(PlaYUVerTools BUILD_TOOLS "Build Command line tool" ) INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h ) @@ -150,21 +163,21 @@ CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_D ADD_SUBDIRECTORY( lib ) ADD_SUBDIRECTORY( modules ) -IF( ${PLAYUVER_BUILD_TOOLS} ) +IF( ${BUILD_TOOLS} ) ADD_SUBDIRECTORY( tools ) ENDIF() -IF( ${PLAYUVER_BUILD_APP} ) +IF( ${BUILD_APP} ) ADD_SUBDIRECTORY( app ) ENDIF() # add a target to generate API documentation with Doxygen -# IF(PLAYUVER_BUILD_DOC) +# IF(BUILD_DOC) # configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) # add_custom_target(doc ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile # WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} # COMMENT "Generating API documentation with Doxygen" VERBATIM ) -# ENDIF(PLAYUVER_BUILD_DOC) +# ENDIF(BUILD_DOC) ###################################################################################### diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 9553aff..801e71e 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -2,11 +2,11 @@ ### CMakeLists for playuver app component ### -# This is hard way - please fix INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/external ) -# ${CMAKE_CURRENT_SOURCE_DIR}/../modules -# ${CMAKE_CURRENT_BINARY_DIR}/../modules +OPTION( USE_QT4 "Build with Qt4" OFF ) +OPTION( USE_QTDBUS "Build with QtDBus" ON ) +OPTION( USE_FERVOR "Add Fervor support" OFF ) ##################################################################################### # Qt library @@ -86,7 +86,7 @@ set(PlaYUVer_App_RCC resources/playuver.qrc ) -OPTION( USE_FERVOR "Add Fervor support" OFF ) + IF( USE_FERVOR ) diff --git a/cmake/ModulesFct.cmake b/cmake/ModulesFct.cmake index cc99ac5..2299661 100644 --- a/cmake/ModulesFct.cmake +++ b/cmake/ModulesFct.cmake @@ -14,9 +14,26 @@ MACRO(ADD_MODULE name file ) ENDMACRO() -MACRO(ADD_MODULE_OPENCV name file version ) - IF( ${OpenCV_FOUND} AND ( NOT ( ${OpenCV_VERSION} VERSION_LESS ${version} ) ) ) - ADD_MODULE( ${name} ${file} ) +MACRO(ADD_MODULE_USE_OPENCV name file ) + IF( USE_OPENCV ) + SET( ADD_MODULE_OPENCV_VERSION "2.4" ) + CMAKE_PARSE_ARGUMENTS(ADD_MODULE_OPENCV "" "VERSION" "MODULES" ${ARGN} ) + IF( NOT ( ${OpenCV_VERSION} LESS ${ADD_MODULE_OPENCV_VERSION} ) ) + SET( _HAS_MODULES TRUE ) + FOREACH(opencv_module IN LISTS ADD_MODULE_OPENCV_MODULES ) + string(TOUPPER "${opencv_module}" opencv_moduleUP) + FIND_PACKAGE( OpenCV QUIET COMPONENTS ${opencv_module} ) + IF( NOT ${OPENCV_${opencv_moduleUP}_FOUND} EQUAL "1" ) + SET( _HAS_MODULES FALSE ) + ENDIF() + ENDFOREACH() + IF( _HAS_MODULES ) + ADD_MODULE( ${name} ${file} ) + ENDIF() + UNSET( OPENCV_${opencv_moduleUP}_FOUND ) + UNSET( _HAS_MODULES ) + ENDIF() + UNSET( ADD_MODULE_OPENCV_VERSION ) ENDIF() ENDMACRO() diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index a69dcaa..4ffaf88 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -26,19 +26,20 @@ ADD_MODULE( EightBitsSampling "EightBitsSampling" ) ADD_MODULE( FrameCrop "FrameCrop" ) ADD_MODULE( LumaAverage "LumaAverage" ) ADD_MODULE( WeightedPSNR "WeightedPSNR" ) -IF( OpenCV_optflow_FOUND ) - ADD_MODULE_OPENCV( OpticalFlowDualTVL1 "OpticalFlow" 3.1.0 ) - ADD_MODULE_OPENCV( OpticalFlowSparseToDense "OpticalFlow" 3.1.0 ) - ADD_MODULE_OPENCV( OpticalFlowFarneback "OpticalFlow" 3.1.0 ) -ELSE() - ADD_MODULE_OPENCV( OpticalFlowDualTVL1 "OpticalFlowDualTVL1" 2.4.13.0 ) -ENDIF() -ADD_MODULE_OPENCV( DisparityStereoBM "DisparityStereoBM" 2.4.8 ) -ADD_MODULE_OPENCV( DisparityStereoSGBM "DisparityStereoSGBM" 2.4.8 ) -# ADD_MODULE_OPENCV( DisparityStereoVar "DisparityStereoVar" ) + +ADD_MODULE_USE_OPENCV( MeasureOpticalFlowDualTVL1 "MeasureOpticalFlowDualTVL1" VERSION 2.4.13.0 MODULES video ) + +ADD_MODULE_USE_OPENCV( OpticalFlowDualTVL1 "OpticalFlow" VERSION 3.1.0 MODULES optflow ) +ADD_MODULE_USE_OPENCV( OpticalFlowSparseToDense "OpticalFlow" VERSION 3.1.0 MODULES optflow ) +ADD_MODULE_USE_OPENCV( OpticalFlowFarneback "OpticalFlow" VERSION 3.1.0 MODULES video optflow ) + +ADD_MODULE_USE_OPENCV( DisparityStereoBM "DisparityStereoBM" VERSION 2.4.13.0 MODULES calib3d ) +ADD_MODULE_USE_OPENCV( DisparityStereoSGBM "DisparityStereoSGBM" VERSION 2.4.13.0 MODULES calib3d ) + CREATE_MODULE_MACROS() INCLUDE_DIRECTORIES( ${OpenCV_INCLUDE_DIRS} ) ADD_LIBRARY( PlaYUVerModules ${plaYUver_Mod_SRCS} ) +FIND_PACKAGE( OpenCV COMPONENTS ${OPENCV_MODULES} ) TARGET_LINK_LIBRARIES( PlaYUVerModules PlaYUVerLib ${OpenCV_LIBRARIES} -ldl ) diff --git a/modules/OpticalFlowDualTVL1.cpp b/modules/MeasureOpticalFlowDualTVL1.cpp similarity index 88% rename from modules/OpticalFlowDualTVL1.cpp rename to modules/MeasureOpticalFlowDualTVL1.cpp index 0e99a63..139aa4b 100644 --- a/modules/OpticalFlowDualTVL1.cpp +++ b/modules/MeasureOpticalFlowDualTVL1.cpp @@ -18,11 +18,11 @@ */ /** - * \file OpticalFlowDualTVL1.cpp + * \file MeasureOpticalFlowDualTVL1.cpp * \brief Absolute Frame Difference module */ -#include "OpticalFlowDualTVL1.h" +#include "MeasureOpticalFlowDualTVL1.h" #include using cv::Scalar; @@ -32,13 +32,13 @@ using cv::Ptr; using cv::Point; using cv::Point2f; -OpticalFlowDualTVL1::OpticalFlowDualTVL1() +MeasureOpticalFlowDualTVL1::MeasureOpticalFlowDualTVL1() { /* Module Definition */ m_iModuleAPI = MODULE_API_2; m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "Measurements"; - m_pchModuleName = "OpticalFlowDualTVL1"; + m_pchModuleName = "MeasureOpticalFlowDualTVL1"; m_pchModuleTooltip = "Measure optical flow"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; @@ -51,7 +51,7 @@ OpticalFlowDualTVL1::OpticalFlowDualTVL1() } -Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) +Bool MeasureOpticalFlowDualTVL1::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ @@ -71,7 +71,7 @@ static inline bool isFlowCorrect( Point2f u ) return !cvIsNaN( u.x ) && !cvIsNaN( u.y ) && fabs( u.x ) < 1e9 && fabs( u.y ) < 1e9; } -Void OpticalFlowDualTVL1::drawFlow() +Void MeasureOpticalFlowDualTVL1::drawFlow() { Mat cvMatAfter; m_pcFrameAfter->toMat( cvMatAfter, true ); @@ -105,7 +105,7 @@ Void OpticalFlowDualTVL1::drawFlow() m_pcOutputFrame->fromMat( cvMatAfter ); } -Void OpticalFlowDualTVL1::compensateFlow() +Void MeasureOpticalFlowDualTVL1::compensateFlow() { for( UInt c = 0; c < m_pcOutputFrame->getNumberChannels(); c++ ) { @@ -125,7 +125,7 @@ Void OpticalFlowDualTVL1::compensateFlow() } } -PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFrameList ) +PlaYUVerFrame* MeasureOpticalFlowDualTVL1::process( std::vector apcFrameList ) { m_pcFrameAfter = apcFrameList[0]; m_pcFramePrev = apcFrameList[1]; @@ -146,7 +146,7 @@ PlaYUVerFrame* OpticalFlowDualTVL1::process( std::vector apcFram } Void -OpticalFlowDualTVL1::destroy() +MeasureOpticalFlowDualTVL1::destroy() { if( m_pcOutputFrame ) delete m_pcOutputFrame; diff --git a/modules/OpticalFlowDualTVL1.h b/modules/MeasureOpticalFlowDualTVL1.h similarity index 81% rename from modules/OpticalFlowDualTVL1.h rename to modules/MeasureOpticalFlowDualTVL1.h index 0623577..3692b0f 100644 --- a/modules/OpticalFlowDualTVL1.h +++ b/modules/MeasureOpticalFlowDualTVL1.h @@ -18,21 +18,21 @@ */ /** - * \file OpticalFlowDualTVL1.h + * \file MeasureOpticalFlowDualTVL1.h * \brief Absolute Frame Difference module */ -#ifndef __OPTICALFLOWDUALTVL1_H__ -#define __OPTICALFLOWDUALTVL1_H__ +#ifndef __MeasureOpticalFlowDualTVL1_H__ +#define __MeasureOpticalFlowDualTVL1_H__ #include #include #include "lib/PlaYUVerModuleIf.h" -class OpticalFlowDualTVL1: public PlaYUVerModuleIf +class MeasureOpticalFlowDualTVL1: public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) +REGISTER_CLASS_FACTORY( MeasureOpticalFlowDualTVL1 ) private: Bool m_bShowReconstruction; @@ -47,8 +47,8 @@ private: Void compensateFlow(); public: - OpticalFlowDualTVL1(); - virtual ~OpticalFlowDualTVL1() + MeasureOpticalFlowDualTVL1(); + virtual ~MeasureOpticalFlowDualTVL1() { } Bool create( std::vector apcFrameList ); @@ -57,5 +57,5 @@ public: }; -#endif // __OPTICALFLOWDUALTVL1_H__ +#endif // __MeasureOpticalFlowDualTVL1_H__ diff --git a/modules/OpticalFlow.cpp b/modules/OpticalFlow.cpp index 95648bc..ba3e24d 100644 --- a/modules/OpticalFlow.cpp +++ b/modules/OpticalFlow.cpp @@ -29,7 +29,6 @@ #include // Opencv -// #include #include using cv::Scalar; From 8db32e32c54954bf575aefc82c65a6fb1882843e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 14 May 2016 02:41:52 +0100 Subject: [PATCH 077/127] Fix opencv version verification --- CMakeLists.txt | 4 +--- cmake/ModulesFct.cmake | 10 +++++----- modules/CMakeLists.txt | 1 - 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6998e51..60300dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -91,11 +91,9 @@ SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPT OPTION( USE_OPENCV "Add OpenCV support" ON ) SET( OPENCV_OPTFLOW_FOUND OFF ) IF( USE_OPENCV ) - FIND_PACKAGE( OpenCV REQUIRED core highgui video ) + FIND_PACKAGE( OpenCV COMPONENTS core highgui video ) LIST(APPEND OPENCV_MODULES core highgui video ) SET(USE_OPENCV ${OpenCV_FOUND}) - ## Check -# LIST(FIND OpenCV_LIB_COMPONENTS opencv_optflow OpenCV_optflow_FOUND) ENDIF() SET_PACKAGE_PROPERTIES(OpenCV PROPERTIES URL "http://opencv.willowgarage.com" DESCRIPTION "OpenCV library support in PlaYUVerFrame" TYPE OPTIONAL) diff --git a/cmake/ModulesFct.cmake b/cmake/ModulesFct.cmake index 2299661..e5e7c53 100644 --- a/cmake/ModulesFct.cmake +++ b/cmake/ModulesFct.cmake @@ -16,11 +16,11 @@ ENDMACRO() MACRO(ADD_MODULE_USE_OPENCV name file ) IF( USE_OPENCV ) - SET( ADD_MODULE_OPENCV_VERSION "2.4" ) - CMAKE_PARSE_ARGUMENTS(ADD_MODULE_OPENCV "" "VERSION" "MODULES" ${ARGN} ) - IF( NOT ( ${OpenCV_VERSION} LESS ${ADD_MODULE_OPENCV_VERSION} ) ) + SET( ADD_MODULE_USE_OPENCV_VERSION "2.4" ) + CMAKE_PARSE_ARGUMENTS(ADD_MODULE_USE_OPENCV "" "VERSION" "MODULES" ${ARGN} ) + IF( NOT ( ${OpenCV_VERSION} VERSION_LESS ${ADD_MODULE_USE_OPENCV_VERSION} ) ) SET( _HAS_MODULES TRUE ) - FOREACH(opencv_module IN LISTS ADD_MODULE_OPENCV_MODULES ) + FOREACH(opencv_module IN LISTS ADD_MODULE_USE_OPENCV_MODULES ) string(TOUPPER "${opencv_module}" opencv_moduleUP) FIND_PACKAGE( OpenCV QUIET COMPONENTS ${opencv_module} ) IF( NOT ${OPENCV_${opencv_moduleUP}_FOUND} EQUAL "1" ) @@ -33,7 +33,7 @@ MACRO(ADD_MODULE_USE_OPENCV name file ) UNSET( OPENCV_${opencv_moduleUP}_FOUND ) UNSET( _HAS_MODULES ) ENDIF() - UNSET( ADD_MODULE_OPENCV_VERSION ) + UNSET( ADD_MODULE_USE_OPENCV_VERSION ) ENDIF() ENDMACRO() diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 4ffaf88..8796b5c 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -41,5 +41,4 @@ ADD_MODULE_USE_OPENCV( DisparityStereoSGBM "DisparityStereoSGBM" VERSION 2.4.13. CREATE_MODULE_MACROS() INCLUDE_DIRECTORIES( ${OpenCV_INCLUDE_DIRS} ) ADD_LIBRARY( PlaYUVerModules ${plaYUver_Mod_SRCS} ) -FIND_PACKAGE( OpenCV COMPONENTS ${OPENCV_MODULES} ) TARGET_LINK_LIBRARIES( PlaYUVerModules PlaYUVerLib ${OpenCV_LIBRARIES} -ldl ) From c2f2af7584a7f9ecc19b6c8e852e26efc3185d99 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 14 May 2016 03:08:22 +0100 Subject: [PATCH 078/127] Minor fixes with windows build and opencv dlls --- CMakeLists.txt | 4 ++-- cmake/ModulesFct.cmake | 2 ++ cmake/Win32.cmake | 23 ++++------------------- 3 files changed, 8 insertions(+), 21 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 60300dc..6d75564 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -91,8 +91,8 @@ SET_PACKAGE_PROPERTIES(Doxygen PROPERTIES URL "http://www.doxygen.org/" DESCRIPT OPTION( USE_OPENCV "Add OpenCV support" ON ) SET( OPENCV_OPTFLOW_FOUND OFF ) IF( USE_OPENCV ) - FIND_PACKAGE( OpenCV COMPONENTS core highgui video ) - LIST(APPEND OPENCV_MODULES core highgui video ) + LIST(APPEND OPENCV_MODULES core highgui imgproc video ) + FIND_PACKAGE( OpenCV COMPONENTS ${OPENCV_MODULES} ) SET(USE_OPENCV ${OpenCV_FOUND}) ENDIF() SET_PACKAGE_PROPERTIES(OpenCV PROPERTIES URL "http://opencv.willowgarage.com" DESCRIPTION "OpenCV library support in PlaYUVerFrame" TYPE OPTIONAL) diff --git a/cmake/ModulesFct.cmake b/cmake/ModulesFct.cmake index e5e7c53..5dd24a8 100644 --- a/cmake/ModulesFct.cmake +++ b/cmake/ModulesFct.cmake @@ -25,6 +25,8 @@ MACRO(ADD_MODULE_USE_OPENCV name file ) FIND_PACKAGE( OpenCV QUIET COMPONENTS ${opencv_module} ) IF( NOT ${OPENCV_${opencv_moduleUP}_FOUND} EQUAL "1" ) SET( _HAS_MODULES FALSE ) + ELSE() + LIST(APPEND OPENCV_MODULES ${opencv_module} ) ENDIF() ENDFOREACH() IF( _HAS_MODULES ) diff --git a/cmake/Win32.cmake b/cmake/Win32.cmake index 9030f69..b9bb01d 100644 --- a/cmake/Win32.cmake +++ b/cmake/Win32.cmake @@ -36,25 +36,10 @@ IF( NOT USE_QT4 ) ENDIF() IF( USE_OPENCV ) - SET( DEPENDENCIES_STRING "${DEPENDENCIES_STRING}OPENCV" ) - IF( WIN32 ) - SET(OpenCV_DLL_DIR "${OpenCV_DIR}/bin" CACHE PATH "Where to find OpenCV dlls") - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_core${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_highgui${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_imgproc${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_calib3d${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_features2d${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_flann${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_ml${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_video${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_videostab${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_superres${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_stitching${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_photo${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_objdetect${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) - ENDIF() - LIST(APPEND CPACK_DEBIAN_PACKAGE_DEPENDS ",") - LIST(APPEND CPACK_DEBIAN_PACKAGE_DEPENDS "libopencv-dev (>= 2.4.8)") + SET(OpenCV_DLL_DIR "${OpenCV_DIR}/bin" CACHE PATH "Where to find OpenCV dlls") + FOREACH(opencv_module IN LISTS OPENCV_MODULES ) + INSTALL(FILES ${OpenCV_DLL_DIR}/opencv_${opencv_module}${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll DESTINATION bin ) + ENDFOREACH() ENDIF() IF( USE_FFMPEG ) From 9e7838ad27549f08e703bfdce852ee82412fa4d0 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 01:50:42 +0100 Subject: [PATCH 079/127] Fix cmake and desktop files --- CMakeLists.txt | 4 +++ app/PlaYUVerApp.cpp | 2 +- app/resources/playuver.desktop | 2 +- ...cpp => AbsoluteFrameDifferenceExample.cpp} | 27 +++++++++++-------- ...Iv2.h => AbsoluteFrameDifferenceExample.h} | 16 +++++------ examples/modules/CMakeLists.txt | 4 +-- lib/CMakeLists.txt | 2 +- lib/PlaYUVerConfig.cmake.in | 11 ++------ 8 files changed, 35 insertions(+), 33 deletions(-) rename examples/modules/{AbsoluteFrameDifference_APIv2.cpp => AbsoluteFrameDifferenceExample.cpp} (73%) rename examples/modules/{AbsoluteFrameDifference_APIv2.h => AbsoluteFrameDifferenceExample.h} (76%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d75564..efb8a14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -169,6 +169,10 @@ IF( ${BUILD_APP} ) ADD_SUBDIRECTORY( app ) ENDIF() +IF( ${BUILD_EXAMPLES} ) + ADD_SUBDIRECTORY( examples ) +ENDIF() + # add a target to generate API documentation with Doxygen # IF(BUILD_DOC) # configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 93c84ca..ad25214 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -320,7 +320,7 @@ Void PlaYUVerApp::save() << formatsList << tr( "All Files (*)" ); - QString fileName = QFileDialog::getSaveFileName( this, tr( "Open File" ), QString(), filter.join( ";;" ) ); + QString fileName = QFileDialog::getSaveFileName( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); if( !fileName.isEmpty() ) { diff --git a/app/resources/playuver.desktop b/app/resources/playuver.desktop index 95c6e2b..c0f9a90 100755 --- a/app/resources/playuver.desktop +++ b/app/resources/playuver.desktop @@ -1,7 +1,7 @@ #!/usr/bin/env xdg-open [Desktop Entry] Type=Application -Name=plaYUVer +Name=PlaYUVer Exec=playuver %U Icon=playuver Terminal=false diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.cpp b/examples/modules/AbsoluteFrameDifferenceExample.cpp similarity index 73% rename from examples/modules/AbsoluteFrameDifference_APIv2.cpp rename to examples/modules/AbsoluteFrameDifferenceExample.cpp index a772410..033f221 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.cpp +++ b/examples/modules/AbsoluteFrameDifferenceExample.cpp @@ -18,23 +18,23 @@ */ /** - * \file AbsoluteFrameDifference_APIv2.cpp - * \brief Absolute Frame Difference module + * \file AbsoluteFrameDifferenceExample.cpp + * \brief Absolute Frame Difference module example */ -#include "AbsoluteFrameDifference_APIv2.h" +#include "AbsoluteFrameDifferenceExample.h" #include -REGISTER_CLASS_MAKER( AbsoluteFrameDifference ) +REGISTER_CLASS_MAKER( AbsoluteFrameDifferenceExample ) -AbsoluteFrameDifference::AbsoluteFrameDifference() +AbsoluteFrameDifferenceExample::AbsoluteFrameDifferenceExample() { /* Module Definition */ m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). // See this example for details on the functions prototype m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "AbsoluteFrameDifference"; // Name + m_pchModuleName = "AbsoluteFrameDifferenceExampleExample"; // Name m_pchModuleTooltip = "Measure the absolute difference " // Description "between two images (Y plane), e. g., abs( Y1 - Y2 )"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) @@ -44,14 +44,19 @@ AbsoluteFrameDifference::AbsoluteFrameDifference() } -Bool AbsoluteFrameDifference::create( std::vector apcFrameList ) +Bool AbsoluteFrameDifferenceExample::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + + for( UInt i = 1; i < apcFrameList.size(); i++ ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + return false; + + m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); return true; } -PlaYUVerFrame* AbsoluteFrameDifference::process( std::vector apcFrameList ) +PlaYUVerFrame* AbsoluteFrameDifferenceExample::process( std::vector apcFrameList ) { PlaYUVerFrame* Input1 = apcFrameList[0]; PlaYUVerFrame* Input2 = apcFrameList[1]; @@ -67,10 +72,10 @@ PlaYUVerFrame* AbsoluteFrameDifference::process( std::vector apc aux_pel_2 = *pInput2PelYUV++; *pOutputPelYUV++ = abs( aux_pel_1 - aux_pel_2 ); } - return m_pcFrameDifference; + return m_pcFrameDifference; } -Void AbsoluteFrameDifference::destroy() +Void AbsoluteFrameDifferenceExample::destroy() { if( m_pcFrameDifference ) delete m_pcFrameDifference; diff --git a/examples/modules/AbsoluteFrameDifference_APIv2.h b/examples/modules/AbsoluteFrameDifferenceExample.h similarity index 76% rename from examples/modules/AbsoluteFrameDifference_APIv2.h rename to examples/modules/AbsoluteFrameDifferenceExample.h index 40825f5..01951a7 100644 --- a/examples/modules/AbsoluteFrameDifference_APIv2.h +++ b/examples/modules/AbsoluteFrameDifferenceExample.h @@ -18,27 +18,27 @@ */ /** - * \file AbsoluteFrameDifference_APIv2.h + * \file AbsoluteFrameDifferenceExampleExample.h * \brief Absolute Frame Difference module */ -#ifndef __ABSOLUTEFRAMEDIFFERENCE_H__ -#define __ABSOLUTEFRAMEDIFFERENCE_H__ +#ifndef __ABSOLUTEFRAMEDIFFERENCEEXAMPLE_H__ +#define __ABSOLUTEFRAMEDIFFERENCEEXAMPLE_H__ #include "PlaYUVerModuleIf.h" #include -class AbsoluteFrameDifference: public PlaYUVerModuleIf +class AbsoluteFrameDifferenceExample: public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( AbsoluteFrameDifference ) +REGISTER_CLASS_FACTORY( AbsoluteFrameDifferenceExample ) private: PlaYUVerFrame* m_pcFrameDifference; public: - AbsoluteFrameDifference(); - virtual ~AbsoluteFrameDifference() + AbsoluteFrameDifferenceExample(); + virtual ~AbsoluteFrameDifferenceExample() { } Bool create( std::vector apcFrameList ); @@ -47,5 +47,5 @@ public: }; -#endif // __FRAMEDIFFERENCE_H__ +#endif // __ABSOLUTEFRAMEDIFFERENCEEXAMPLE_H__ diff --git a/examples/modules/CMakeLists.txt b/examples/modules/CMakeLists.txt index a01e7ee..3a0aff7 100644 --- a/examples/modules/CMakeLists.txt +++ b/examples/modules/CMakeLists.txt @@ -14,6 +14,6 @@ INCLUDE_DIRECTORIES( ${PLAYUVER_INCLUDE_DIRS} ) ADD_LIBRARY(FrameBinarization SHARED FrameBinarization_APIv1.cpp) TARGET_LINK_LIBRARIES( FrameBinarization ${PLAYUVER_LINKER_LIBS} ) -ADD_LIBRARY(AbsoluteFrameDifference SHARED AbsoluteFrameDifference_APIv2.cpp) -TARGET_LINK_LIBRARIES( AbsoluteFrameDifference ${PLAYUVER_LINKER_LIBS} ) +ADD_LIBRARY(AbsoluteFrameDifferenceExample SHARED AbsoluteFrameDifferenceExample.cpp) +TARGET_LINK_LIBRARIES( AbsoluteFrameDifferenceExample ${PLAYUVER_LINKER_LIBS} ) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 5e03600..21d32b0 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -49,6 +49,6 @@ TARGET_LINK_LIBRARIES( PlaYUVerLib ${FFMPEG_LIBRARIES} ${OpenCV_LIBRARIES} ) IF( NOT USE_STATIC ) INSTALL(FILES ${PlaYUVer_Lib_HEADERS} DESTINATION include ) - INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/PlaYUVerConfig.cmake DESTINATION share/PlaYUVer ) + INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/PlaYUVerConfig.cmake DESTINATION share/playuver ) INSTALL(TARGETS PlaYUVerLib DESTINATION lib ) ENDIF() diff --git a/lib/PlaYUVerConfig.cmake.in b/lib/PlaYUVerConfig.cmake.in index 1c8fb93..2e6417a 100644 --- a/lib/PlaYUVerConfig.cmake.in +++ b/lib/PlaYUVerConfig.cmake.in @@ -10,10 +10,6 @@ # include_directories(${PLAYUVER_INCLUDE_DIRS}) # target_link_libraries(MY_TARGET_NAME ${PLAYUVER_LINKER_LIBS}) # -# Or you can search for specific PlaYUVer modules: -# -# find_package(PlaYUVer REQUIRED Frame Stream) -# # If the module is found then PLAYUVER__FOUND is set to TRUE. # # This file will define the following variables: @@ -47,16 +43,13 @@ LIST(APPEND PLAYUVER_INCLUDE_DIRS @CMAKE_INSTALL_PREFIX@/include ) # PlaYUVer dependencies: # ====================================================== -SET( PLAYUVER_HAS_OPENCV @USE_OPENCV@ ) -SET( PLAYUVER_HAS_FFMPEG @USE_FFMPEG@ ) - -IF( PLAYUVER_HAS_FFMPEG ) +IF( @USE_OPENCV@ ) LIST(APPEND PLAYUVER_INCLUDE_DIRS ${FFMPEG_INCLUDE_DIRS} ) LIST(APPEND PLAYUVER_LINKER_LIBS @OpenCV_LIBRARIES@ ) ENDIF() -IF( PLAYUVER_HAS_OPENCV ) +IF( @USE_FFMPEG@ ) LIST(APPEND PLAYUVER_INCLUDE_DIRS ${OpenCV_INCLUDE_DIRS} ) LIST(APPEND PLAYUVER_LINKER_LIBS @OpenCV_LIBRARIES@ ) ENDIF() From fdba958f3fe3c690d7ea2797717d49223bfe06ae Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 16:59:54 +0100 Subject: [PATCH 080/127] Fix error matching the stream handler based on extension --- lib/PlaYUVerStream.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 2a14846..73abf94 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -116,10 +116,10 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo { return supportedFmts[i].formatFct; } - else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) - { - return supportedFmts[i].formatFct; - } +// else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) +// { +// return supportedFmts[i].formatFct; +// } } return &StreamHandlerRaw::Create; } From 7e9b9f8415b897f832acd05db4a56bcb6abece52 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 17:02:43 +0100 Subject: [PATCH 081/127] Remove support for video streams based on ffmpeg --- lib/StreamHandlerLibav.cpp | 14 +++++++------- lib/StreamHandlerOpenCV.cpp | 1 - 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index accfec4..add5e60 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -31,15 +31,15 @@ std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); +// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index f994b94..5195971 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -34,7 +34,6 @@ using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } From 13b45b0e677ae08aa68bab2922b7f3519c19ea96 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 17:03:17 +0100 Subject: [PATCH 082/127] Fix functions name in PlaYUVerFrame --- lib/LibMemory.h | 12 --------- lib/PlaYUVerFrame.cpp | 59 ++++++++++++++++++++++++++----------------- lib/PlaYUVerFrame.h | 1 + 3 files changed, 37 insertions(+), 35 deletions(-) diff --git a/lib/LibMemory.h b/lib/LibMemory.h index d212f63..00523dc 100644 --- a/lib/LibMemory.h +++ b/lib/LibMemory.h @@ -218,16 +218,4 @@ Void freeMem5D( T***** array5D ) } } -template -Void freeMem3ImageComponents( T*** array3D ) -{ - if( array3D ) - { - if( **array3D ) - xFreeMem( **array3D ); - - freeMem2D( array3D ); - } -} - #endif // __LIBMEMORY_H__ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 3a5098d..ddbb979 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -165,7 +165,7 @@ PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt a copyFrom( other, posX, posY ); } -static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) +static Int getImgMemory( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) { Int dim0 = 3; Int i; @@ -199,6 +199,18 @@ static Int getMem3ImageComponents( Pel**** array3D, Int dim1, Int dim2, Int log2 return total_mem_size; } +Void freeImgMemory( Pel*** array3D ) +{ + if( array3D ) + { + if( **array3D ) + xFreeMem( **array3D ); + + freeMem2D( array3D ); + } +} + + Void PlaYUVerFramePrivate::init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) { m_bInit = false; @@ -226,11 +238,11 @@ Void PlaYUVerFramePrivate::init( UInt width, UInt height, Int pel_format, Int bi m_bHasRGBPel = false; if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) { - getMem3ImageComponents( &m_pppcInputPel, m_uiHeight, m_uiWidth, 1, 1 ); + getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, 1, 1 ); } else { - getMem3ImageComponents( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, m_pcPelFormat->log2ChromaWidth ); + getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, m_pcPelFormat->log2ChromaWidth ); } getMem1D( &m_pcARGB32, m_uiHeight * m_uiWidth * 4 ); @@ -259,7 +271,7 @@ PlaYUVerFrame::~PlaYUVerFrame() d->m_bHasHistogram = false; if( d->m_pppcInputPel ) - freeMem3ImageComponents( d->m_pppcInputPel ); + freeImgMemory( d->m_pppcInputPel ); d->m_pppcInputPel = NULL; if( d->m_pcARGB32 ) @@ -269,24 +281,6 @@ PlaYUVerFrame::~PlaYUVerFrame() delete d; } -Void PlaYUVerFrame::clear() -{ - Pel* pPel; - Pel uiValue = 128; - Int ratioH, ratioW; - UInt i; - for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) - { - ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; - ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; - pPel = d->m_pppcInputPel[ch][0]; - for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) - { - *pPel++ = uiValue; - } - } -} - Bool PlaYUVerFrame::haveSameFmt( PlaYUVerFrame* other, UInt match ) const { Bool bRet = true; @@ -400,6 +394,24 @@ UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelF return numberBytes * bytesPerPixel; } +Void PlaYUVerFrame::clear() +{ + Pel* pPel; + Pel uiValue = 128; + Int ratioH, ratioW; + UInt i; + for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) + { + ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; + ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; + pPel = d->m_pppcInputPel[ch][0]; + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) + { + *pPel++ = uiValue; + } + } +} + Pel*** PlaYUVerFrame::getPelBufferYUV() const { return d->m_pppcInputPel; @@ -467,7 +479,8 @@ Void PlaYUVerFrame::setPixelValue( Int xPos, Int yPos, PlaYUVerPixel pixel ) Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame ) { - if( d->m_iPixelFormat != input_frame->getPelFormat() && d->m_uiWidth == input_frame->getWidth() && d->m_uiHeight == input_frame->getHeight() ) + if( haveSameFmt( input_frame, MATCH_ALL ) ) +// if( d->m_iPixelFormat != input_frame->getPelFormat() && d->m_uiWidth == input_frame->getWidth() && d->m_uiHeight == input_frame->getHeight() ) return; d->m_bHasRGBPel = false; d->m_bHasHistogram = false; diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 4541f3e..9710430 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -190,6 +190,7 @@ public: */ static UInt64 getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ); + /** * Reset frame pixels to zero */ From 2d1f9aa47110e80ca09c4c4898ed0ded46d48108 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 19:22:44 +0100 Subject: [PATCH 083/127] Port some functions of PlaYUVerFrame to const reference --- lib/PlaYUVerFrame.cpp | 351 +++++++++++++++++++++++------------------ lib/PlaYUVerFrame.h | 22 +-- modules/FrameShift.cpp | 5 +- 3 files changed, 215 insertions(+), 163 deletions(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index ddbb979..4ddd1af 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -67,7 +67,7 @@ std::vector PlaYUVerFrame::supportedPixelFormatListNames( Int colorSpace return formatsList; } -Int PlaYUVerFrame::findPixelFormat( String name ) +Int PlaYUVerFrame::findPixelFormat( const String& name ) { for( Int i = 0; i < NUMBER_PEL_FORMATS; i++ ) { @@ -77,94 +77,6 @@ Int PlaYUVerFrame::findPixelFormat( String name ) return -1; } -struct PlaYUVerFramePrivate -{ - /** - * Common constructor function of a frame - * - * @param width width of the frame - * @param height height of the frame - * @param pel_format pixel format index (always use PixelFormats enum) - * - */ - Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ); - - Bool m_bInit; - - //! Struct with the pixel format description. - const PlaYUVerPixFmtDescriptor* m_pcPelFormat; - String m_cPelFmtName; - - UInt m_uiWidth; //!< Width of the frame - UInt m_uiHeight; //!< Height of the frame - Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) - Int m_iNumberChannels; //!< Number of channels - UInt m_uiBitsPel; //!< Bits per pixel/channel - Int m_iEndianness; //!< Endiannes of bytes - UInt m_uiHalfPelValue; //!< Bits per pixel/channel - - Pel*** m_pppcInputPel; - - Bool m_bHasRGBPel; //!< Flag indicating that the ARGB buffer was computed - UChar* m_pcARGB32; //!< Buffer with the ARGB pixels used in Qt libs - - /** The histogram data.*/ - UInt* m_puiHistogram; - - /** If the image is RGB and calcLuma is true, we have 1 more channel */ - UInt m_uiHistoChannels; - - /** Numbers of histogram segments depending of image bytes depth*/ - UInt m_uiHistoSegments; - - /** Used to stop thread during calculations.*/ - Bool m_bRunningFlag; - - Bool m_bHasHistogram; -}; - -/*! \brief Constructors - * - * Constructors and init functions - */ -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : - d( new PlaYUVerFramePrivate ) -{ - d->init( width, height, pelFormat, bitsPixel, endianness ); -} - -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, Bool bCopy ) : - d( new PlaYUVerFramePrivate ) -{ - d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); - copyFrom( other ); -} - -PlaYUVerFrame::PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : - d( new PlaYUVerFramePrivate ) -{ - const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); - if( pcPelFormat->log2ChromaWidth ) - { - if( posX % ( 1 << pcPelFormat->log2ChromaWidth ) ) - posX--; - if( ( posX + areaWidth ) % ( 1 << pcPelFormat->log2ChromaWidth ) ) - areaWidth++; - } - - if( pcPelFormat->log2ChromaHeight ) - { - if( posY % ( 1 << pcPelFormat->log2ChromaHeight ) ) - posY--; - - if( ( posY + areaHeight ) % ( 1 << pcPelFormat->log2ChromaHeight ) ) - areaHeight++; - } - - d->init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); - copyFrom( other, posX, posY ); -} - static Int getImgMemory( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) { Int dim0 = 3; @@ -175,7 +87,7 @@ static Int getImgMemory( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeig total_mem_size += getMem2D( array3D, dim0, dim1 ); if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof(Pel) ) ) == NULL ) - printf( "getMem3DImageComponents: array1D" ); + printf( "getImgMemory: array1D" ); total_mem_size += mem_size * sizeof(Pel); @@ -210,55 +122,179 @@ Void freeImgMemory( Pel*** array3D ) } } - -Void PlaYUVerFramePrivate::init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) +struct PlaYUVerFramePrivate { - m_bInit = false; - m_pppcInputPel = NULL; - m_pcARGB32 = NULL; - m_uiWidth = width; - m_uiHeight = height; - m_iPixelFormat = pel_format; - m_iNumberChannels = 3; - m_uiBitsPel = bitsPixel > 8 ? bitsPixel : 8; - m_iEndianness = endianness; - if( m_uiBitsPel > 8 && m_iEndianness == -1 ) - { - throw PlaYUVerFailure( "PlaYUVerFrame", "Invalid endianness type for Bits per Pixel greater than 8" ); - } - m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); + Bool m_bInit; - if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) + //! Struct with the pixel format description. + const PlaYUVerPixFmtDescriptor* m_pcPelFormat; + String m_cPelFmtName; + + UInt m_uiWidth; //!< Width of the frame + UInt m_uiHeight; //!< Height of the frame + Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) + Int m_iNumberChannels; //!< Number of channels + UInt m_uiBitsPel; //!< Bits per pixel/channel + Int m_iEndianness; //!< Endiannes of bytes + UInt m_uiHalfPelValue; //!< Bits per pixel/channel + + Pel*** m_pppcInputPel; + + Bool m_bHasRGBPel; //!< Flag indicating that the ARGB buffer was computed + UChar* m_pcARGB32; //!< Buffer with the ARGB pixels used in Qt libs + + /** The histogram data.*/ + UInt* m_puiHistogram; + + /** If the image is RGB and calcLuma is true, we have 1 more channel */ + UInt m_uiHistoChannels; + + /** Numbers of histogram segments depending of image bytes depth*/ + UInt m_uiHistoSegments; + + /** Used to stop thread during calculations.*/ + Bool m_bRunningFlag; + + Bool m_bHasHistogram; + + /** + * Common constructor function of a frame + * + * @param width width of the frame + * @param height height of the frame + * @param pel_format pixel format index (always use PixelFormats enum) + * + */ + Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) { - throw PlaYUVerFailure( "PlaYUVerFrame", "Cannot create a PlYUVerFrame of this type" ); + m_bInit = false; + m_pppcInputPel = NULL; + m_pcARGB32 = NULL; + m_uiWidth = width; + m_uiHeight = height; + m_iPixelFormat = pel_format; + m_iNumberChannels = 3; + m_uiBitsPel = bitsPixel > 8 ? bitsPixel : 8; + m_iEndianness = endianness; + if( m_uiBitsPel > 8 && m_iEndianness == -1 ) + { + throw PlaYUVerFailure( "PlaYUVerFrame", "Invalid endianness type for Bits per Pixel greater than 8" ); + } + m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); + + if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) + { + throw PlaYUVerFailure( "PlaYUVerFrame", "Cannot create a PlYUVerFrame of this type" ); + } + + m_pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[pel_format] ); + + m_bHasRGBPel = false; + if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) + { + getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, 1, 1 ); + } + else + { + getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, m_pcPelFormat->log2ChromaWidth ); + } + getMem1D( &m_pcARGB32, m_uiHeight * m_uiWidth * 4 ); + + m_puiHistogram = NULL; + m_bHasHistogram = false; + + m_uiHistoSegments = 1 << m_uiBitsPel; + + if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_ARGB ) + m_uiHistoChannels = m_pcPelFormat->numberChannels + 1; + else + m_uiHistoChannels = m_pcPelFormat->numberChannels; + + m_cPelFmtName = PlaYUVerFrame::supportedPixelFormatListNames()[m_iPixelFormat].c_str(); + + m_bInit = true; + } +}; + +/*! + * \brief Constructors + */ + +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : + d( new PlaYUVerFramePrivate ) +{ + d->init( width, height, pelFormat, bitsPixel, endianness ); +} + +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other ) : +d( new PlaYUVerFramePrivate ) +{ + d->init( other.getWidth(), other.getHeight(), other.getPelFormat(), other.getBitsPel(), other.getEndianness() ); + copyFrom( &other ); +} + + +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other ) : + d( new PlaYUVerFramePrivate ) +{ + if( other ) + { + d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + copyFrom( other ); + } +} + +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt width, UInt height ) : + d( new PlaYUVerFramePrivate ) +{ + const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other.getPelFormat()] ); + if( pcPelFormat->log2ChromaWidth ) + { + if( x % ( 1 << pcPelFormat->log2ChromaWidth ) ) + x--; + if( ( x + width ) % ( 1 << pcPelFormat->log2ChromaWidth ) ) + width++; } - m_pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[pel_format] ); - - m_bHasRGBPel = false; - if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) + if( pcPelFormat->log2ChromaHeight ) { - getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, 1, 1 ); + if( y % ( 1 << pcPelFormat->log2ChromaHeight ) ) + y--; + + if( ( y + height ) % ( 1 << pcPelFormat->log2ChromaHeight ) ) + height++; } - else + + d->init( width, height, other.getPelFormat(), other.getBitsPel(), other.getEndianness() ); + copyFrom( other, x, y ); +} + +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : + d( new PlaYUVerFramePrivate ) +{ + if( !other ) + return; + + const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); + if( pcPelFormat->log2ChromaWidth ) { - getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, m_pcPelFormat->log2ChromaWidth ); + if( posX % ( 1 << pcPelFormat->log2ChromaWidth ) ) + posX--; + if( ( posX + areaWidth ) % ( 1 << pcPelFormat->log2ChromaWidth ) ) + areaWidth++; } - getMem1D( &m_pcARGB32, m_uiHeight * m_uiWidth * 4 ); - m_puiHistogram = NULL; - m_bHasHistogram = false; + if( pcPelFormat->log2ChromaHeight ) + { + if( posY % ( 1 << pcPelFormat->log2ChromaHeight ) ) + posY--; - m_uiHistoSegments = 1 << m_uiBitsPel; + if( ( posY + areaHeight ) % ( 1 << pcPelFormat->log2ChromaHeight ) ) + areaHeight++; + } - if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_ARGB ) - m_uiHistoChannels = m_pcPelFormat->numberChannels + 1; - else - m_uiHistoChannels = m_pcPelFormat->numberChannels; - - m_cPelFmtName = PlaYUVerFrame::supportedPixelFormatListNames()[m_iPixelFormat].c_str(); - - m_bInit = true; + d->init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + copyFrom( other, posX, posY ); } PlaYUVerFrame::~PlaYUVerFrame() @@ -281,25 +317,28 @@ PlaYUVerFrame::~PlaYUVerFrame() delete d; } -Bool PlaYUVerFrame::haveSameFmt( PlaYUVerFrame* other, UInt match ) const - { +Bool PlaYUVerFrame::haveSameFmt( const PlaYUVerFrame& other, UInt match ) const +{ Bool bRet = true; + if( match & MATCH_COLOR_SPACE ) + bRet &= ( getColorSpace() == other.getColorSpace() ); + if( match & MATCH_RESOLUTION ) + bRet &= ( getWidth() == other.getWidth() ) && ( getHeight() == other.getHeight() ); + if( match & MATCH_PEL_FMT ) + bRet &= ( getPelFormat() == other.getPelFormat() ); + if( match & MATCH_BITS ) + bRet &= ( getBitsPel() == other.getBitsPel() ); + if( match & MATCH_COLOR_SPACE_IGNORE_GRAY ) + bRet &= ( getColorSpace() == PlaYUVerPixel::COLOR_GRAY || getColorSpace() == other.getColorSpace() ); + return bRet; +} + +Bool PlaYUVerFrame::haveSameFmt( const PlaYUVerFrame* other, UInt match ) const + { + Bool bRet = false; if( other ) { - if( match & MATCH_COLOR_SPACE ) - bRet &= ( getColorSpace() == other->getColorSpace() ); - if( match & MATCH_RESOLUTION ) - bRet &= ( getWidth() == other->getWidth() ) && ( getHeight() == other->getHeight() ); - if( match & MATCH_PEL_FMT ) - bRet &= ( getPelFormat() == other->getPelFormat() ); - if( match & MATCH_BITS ) - bRet &= ( getBitsPel() == other->getBitsPel() ); - if( match & MATCH_COLOR_SPACE_IGNORE_GRAY ) - bRet &= ( getColorSpace() == PlaYUVerPixel::COLOR_GRAY || getColorSpace() == other->getColorSpace() ); - } - else - { - bRet = false; + bRet = haveSameFmt( *other, match ); } return bRet; } @@ -477,21 +516,26 @@ Void PlaYUVerFrame::setPixelValue( Int xPos, Int yPos, PlaYUVerPixel pixel ) d->m_bHasRGBPel = false; } -Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame ) +Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame& other ) { - if( haveSameFmt( input_frame, MATCH_ALL ) ) -// if( d->m_iPixelFormat != input_frame->getPelFormat() && d->m_uiWidth == input_frame->getWidth() && d->m_uiHeight == input_frame->getHeight() ) + if( haveSameFmt( other, MATCH_ALL ) ) return; d->m_bHasRGBPel = false; d->m_bHasHistogram = false; - memcpy( *d->m_pppcInputPel[LUMA], input_frame->getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof(Pel) ); + memcpy( *d->m_pppcInputPel[LUMA], other.getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof(Pel) ); } -Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) +Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other ) { - if( d->m_iPixelFormat != input_frame->getPelFormat() ) + if( other ) + copyFrom( *other ); +} + +Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame& other, UInt xPos, UInt yPos ) +{ + if( haveSameFmt( other, MATCH_ALL ) ) return; - Pel ***pInput = input_frame->getPelBufferYUV(); + Pel ***pInput = other.getPelBufferYUV(); for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; @@ -505,6 +549,13 @@ Void PlaYUVerFrame::copyFrom( PlaYUVerFrame* input_frame, UInt xPos, UInt yPos ) d->m_bHasHistogram = false; } + +Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other, UInt x, UInt y ) +{ + if( other ) + copyFrom( *other, x, y ); +} + Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) { if( uiBuffSize != getBytesPerFrame() ) diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 9710430..0343632 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -89,7 +89,7 @@ public: */ static std::vector supportedPixelFormatListNames(); static std::vector supportedPixelFormatListNames( Int colorSpace ); - static Int findPixelFormat( String name ); + static Int findPixelFormat( const String& name ); /** * Creates a new frame using the following configuration @@ -100,15 +100,15 @@ public: * * @note this function might misbehave if the pixel format enum is not correct */ - PlaYUVerFrame( UInt width, UInt height, Int pelFormat = 0, Int bitsPixel = 8, Int endianness = -1 ); + PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel = 8, Int endianness = -1 ); /** - * Creates and new frame with the configuration of an - * existing one and copy its contents + * Copy contructor * * @param other existing frame to copy from */ - PlaYUVerFrame( PlaYUVerFrame *other, Bool copy = true ); + PlaYUVerFrame( const PlaYUVerFrame& other ); + PlaYUVerFrame( const PlaYUVerFrame *other ); /** * Creates and new frame with the configuration of an @@ -121,11 +121,13 @@ public: * @param areaWidth crop width * @param areaHeight crop height */ - PlaYUVerFrame( PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ); + PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt width, UInt height ); + PlaYUVerFrame( const PlaYUVerFrame* other, UInt x, UInt y, UInt width, UInt height ); ~PlaYUVerFrame(); - Bool haveSameFmt( PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; + Bool haveSameFmt( const PlaYUVerFrame& other, UInt match = MATCH_ALL ) const; + Bool haveSameFmt( const PlaYUVerFrame* other, UInt match = MATCH_ALL ) const; /** * Get pixel format information @@ -205,8 +207,10 @@ public: PlaYUVerPixel getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::ColorSpace eColorSpace ); Void setPixelValue( Int xPos, Int yPos, PlaYUVerPixel pixel ); - Void copyFrom( PlaYUVerFrame* ); - Void copyFrom( PlaYUVerFrame*, UInt, UInt ); + Void copyFrom( const PlaYUVerFrame& ); + Void copyFrom( const PlaYUVerFrame* ); + Void copyFrom( const PlaYUVerFrame&, UInt, UInt ); + Void copyFrom( const PlaYUVerFrame*, UInt, UInt ); Void frameFromBuffer( Byte*, UInt64 ); Void frameFromBuffer( Byte* ); diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index 04020b6..ea7b495 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -47,10 +47,7 @@ FrameShift::FrameShift() Bool FrameShift::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcProcessedFrame = new PlaYUVerFrame( apcFrameList[0], false ); - -// m_iShiftHor = ( ( m_iShiftHor + 1 ) >> 1 ) << 1; -// m_iShiftVer = ( ( m_iShiftVer + 1 ) >> 1 ) << 1; + m_pcProcessedFrame = new PlaYUVerFrame( apcFrameList[0] ); return true; } From 2f382341024fd6c559784dc84677bead5f9c84fd Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sun, 15 May 2016 19:26:14 +0100 Subject: [PATCH 084/127] Change header in ConfigureFormatDialog --- app/ConfigureFormatDialog.cpp | 3 ++- app/ConfigureFormatDialog.h | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 45a2984..5ddcce7 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include "lib/PlaYUVerFrame.h" @@ -266,7 +267,7 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : } -Int ConfigureFormatDialog::runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, +Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ) { // Set default values diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index 3eefb8d..fc78f3b 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -27,7 +27,6 @@ #include #include -#include #include "PlaYUVerAppDefs.h" @@ -35,6 +34,7 @@ class QComboBox; class QHBoxLayout; class QLabel; class QSpinBox; +class QString; class QWidget; /** @@ -47,7 +47,7 @@ Q_OBJECT public: ConfigureFormatDialog( QWidget *parent = 0 ); - Int runConfigureFormatDialog( QString Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ); + Int runConfigureFormatDialog( const QString& Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ); private Q_SLOTS: void slotStandardResolutionSelected( int ); From ca92a35bf23e0177382314c8dd403d4c6dc1c776 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 17 May 2016 21:23:16 +0100 Subject: [PATCH 085/127] Clean includes in lib and modules --- lib/PlaYUVerDefs.h | 5 ----- lib/PlaYUVerModuleIf.h | 1 - lib/PlaYUVerOptions.cpp | 8 -------- lib/PlaYUVerOptions.h | 4 ---- lib/PlaYUVerStream.cpp | 5 +++++ lib/PlaYUVerStream.h | 2 +- lib/PlaYUVerStreamHandlerIf.h | 3 ++- lib/StreamHandlerOpenCV.cpp | 8 +++++++- lib/StreamHandlerOpenCV.h | 5 +---- lib/StreamHandlerPortableMap.h | 4 ---- lib/StreamHandlerRaw.cpp | 7 +++++-- modules/AbsoluteFrameDifference.cpp | 2 +- modules/AbsoluteFrameDifference.h | 2 +- modules/DisparityStereoBM.cpp | 2 -- modules/DisparityStereoBM.h | 7 ++++--- modules/DisparityStereoSGBM.cpp | 2 -- modules/DisparityStereoSGBM.h | 7 ++++--- modules/DisparityStereoVar.cpp | 2 -- modules/DisparityStereoVar.h | 7 ++++--- modules/EightBitsSampling.cpp | 1 + modules/EightBitsSampling.h | 2 ++ modules/FilterComponent.cpp | 4 ++-- modules/FilterComponent.h | 2 ++ modules/FrameBinarization.cpp | 1 + modules/FrameBinarization.h | 2 ++ modules/FrameCrop.cpp | 1 + modules/FrameCrop.h | 2 ++ modules/FrameDifference.cpp | 2 +- modules/FrameDifference.h | 2 +- modules/FrameMask.cpp | 3 +-- modules/FrameMask.h | 2 +- modules/FrameShift.cpp | 1 + modules/FrameShift.h | 2 ++ modules/LumaAverage.cpp | 1 + modules/LumaAverage.h | 2 ++ modules/MeasureOpticalFlowDualTVL1.cpp | 1 - modules/MeasureOpticalFlowDualTVL1.h | 2 ++ modules/OpticalFlow.h | 2 ++ modules/PlaYUVerModuleFactory.cpp | 6 +++++- modules/PlaYUVerModuleFactory.h | 3 ++- modules/SetChromaHalfScale.cpp | 2 +- modules/SetChromaHalfScale.h | 9 +++++---- modules/WeightedPSNR.cpp | 2 -- modules/WeightedPSNR.h | 3 +-- 44 files changed, 76 insertions(+), 67 deletions(-) diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 09a2a44..0639be6 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -26,8 +26,6 @@ #ifndef __PLAYUVERDEFS_H__ #define __PLAYUVERDEFS_H__ -#include -#include #include // ==================================================================================================================== @@ -87,9 +85,6 @@ typedef UChar Byte; #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of signed 64-bit integer #define MAX_DOUBLE 1.7e+308 ///< max. value of double-type value -// ==================================================================================================================== -// Macro functions -// ==================================================================================================================== // ==================================================================================================================== // PlaYUVer definitions diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index 439fea4..725054c 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -38,7 +38,6 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerFrame.h" #include "PlaYUVerOptions.h" -#include #define REGISTER_CLASS_MAKER(X) \ extern "C" PlaYUVerModuleIf* Maker() { return new X; } diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index 729ca56..550fa6b 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -39,16 +39,8 @@ #include "config.h" #include "PlaYUVerOptions.h" -#include -#include -#include #include -#include #include -#include -#include -#include -#include #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index 795f2b1..c6118d7 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -39,12 +39,8 @@ #ifndef __PROGRAMOPTIONS_H__ #define __PROGRAMOPTIONS_H__ -#include -#include -#include #include #include -#include #include "PlaYUVerDefs.h" diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 73abf94..efcb150 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -22,12 +22,16 @@ * \brief Input stream handling */ +// Self #include "config.h" #include "PlaYUVerStream.h" +// System #include +// Own #include "LibMemory.h" +#include "PlaYUVerFrame.h" #include "PlaYUVerStreamHandlerIf.h" #include "StreamHandlerRaw.h" #include "StreamHandlerPortableMap.h" @@ -38,6 +42,7 @@ #include "StreamHandlerOpenCV.h" #endif + std::vector PlaYUVerStream::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index fbefab8..32fc8c5 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -26,8 +26,8 @@ #define __PLAYUVERSTREAM_H__ #include "PlaYUVerDefs.h" -#include "PlaYUVerFrame.h" +class PlaYUVerFrame; class PlaYUVerStreamHandlerIf; typedef struct diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 0f4ae59..e886c12 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -27,7 +27,8 @@ #include "PlaYUVerDefs.h" #include "PlaYUVerStream.h" -#include "PlaYUVerFrame.h" + +class PlaYUVerFrame; #define REGISTER_STREAM_HANDLER(X) \ public: \ diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 5195971..126da05 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -22,8 +22,14 @@ * \brief Interface with opencv lib */ -#include +// Self #include "StreamHandlerOpenCV.h" + +// System +#include +#include + +// Own #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" #include "LibMemory.h" diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index aa02b0f..022ae8d 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -25,10 +25,7 @@ #ifndef __STREAMHANDLEROPENCV_H__ #define __STREAMHANDLEROPENCV_H__ -#include -#include -#include -#include + #include "PlaYUVerDefs.h" #include "PlaYUVerStreamHandlerIf.h" diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index f762f4c..7434f69 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -25,11 +25,7 @@ #ifndef __STREAMHANDLERPORTABLEMAP_H__ #define __STREAMHANDLERPORTABLEMAP_H__ -#include -#include -#include #include "PlaYUVerDefs.h" -#include "PlaYUVerStream.h" #include "PlaYUVerStreamHandlerIf.h" class PlaYUVerFrame; diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index e84d3d6..02f5d87 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -22,11 +22,14 @@ * \brief Interface for raw (yuv) streams */ -#include #include "StreamHandlerRaw.h" + +#include + +#include "LibMemory.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" -#include "LibMemory.h" + Bool StreamHandlerRaw::openHandler( String strFilename, Bool bInput ) { diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 985c7c0..7ccd587 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -23,7 +23,7 @@ */ #include "AbsoluteFrameDifference.h" -#include + AbsoluteFrameDifference::AbsoluteFrameDifference() { diff --git a/modules/AbsoluteFrameDifference.h b/modules/AbsoluteFrameDifference.h index e4956e4..e13202a 100644 --- a/modules/AbsoluteFrameDifference.h +++ b/modules/AbsoluteFrameDifference.h @@ -25,9 +25,9 @@ #ifndef __ABSOLUTEFRAMEDIFFERENCE_H__ #define __ABSOLUTEFRAMEDIFFERENCE_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -#include class AbsoluteFrameDifference: public PlaYUVerModuleIf { diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index 506eb61..3b6f5e0 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -22,8 +22,6 @@ * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) */ -#include - #include "DisparityStereoBM.h" DisparityStereoBM::DisparityStereoBM() diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index 7f851b4..fd6fb91 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -25,11 +25,12 @@ #ifndef __DISPARITYSTEREOBM_H__ #define __DISPARITYSTEREOBM_H__ -#include -#include "lib/PlaYUVerModuleIf.h" +// OpenCV #include -#include +// PlaYUVerLib +#include "lib/PlaYUVerModuleIf.h" + class DisparityStereoBM: public PlaYUVerModuleIf { diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index ae2b562..a6aa542 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -22,8 +22,6 @@ * \brief Measure the disparity between two images using the SGBM method (OpenCV) */ -#include - #include "DisparityStereoSGBM.h" DisparityStereoSGBM::DisparityStereoSGBM() diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index 394208a..51cd170 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -37,11 +37,12 @@ #ifndef __DISPARITYSTEREOSGBM_H__ #define __DISPARITYSTEREOSGBM_H__ -#include -#include "lib/PlaYUVerModuleIf.h" +// OpenCV #include -#include +// PlaYUVerLib +#include "lib/PlaYUVerModuleIf.h" + class DisparityStereoSGBM: public PlaYUVerModuleIf { diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index a6052d5..15144d5 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -22,8 +22,6 @@ * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) */ -#include - #include "DisparityStereoVar.h" DisparityStereoVar::DisparityStereoVar() diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 68cb490..0bd9bce 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -25,11 +25,12 @@ #ifndef __DISPARITYSTEREOVAR_H__ #define __DISPARITYSTEREOVAR_H__ -#include -#include "PlaYUVerModuleIf.h" +// OpenCV #include -#include +// PlaYUVerLib +#include "PlaYUVerModuleIf.h" + class DisparityStereoVar: public PlaYUVerModuleIf { diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index 938f81c..ce6d766 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -24,6 +24,7 @@ #include "EightBitsSampling.h" + EightBitsSampling::EightBitsSampling() { /* Module Definition */ diff --git a/modules/EightBitsSampling.h b/modules/EightBitsSampling.h index 8adb69c..4402a1c 100644 --- a/modules/EightBitsSampling.h +++ b/modules/EightBitsSampling.h @@ -25,8 +25,10 @@ #ifndef __EIGHTBITSSAMPLING_H__ #define __EIGHTBITSSAMPLING_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class EightBitsSampling: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( EightBitsSampling ) diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index 05dc32e..c0378f5 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -22,10 +22,10 @@ * \brief Filter component frame module */ -#include -#include #include "FilterComponent.h" +#include + FilterComponentModule::FilterComponentModule() { m_pcFilteredFrame = NULL; diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index f9b86a6..4744763 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -25,8 +25,10 @@ #ifndef __FILTERCOMPONENT_H__ #define __FILTERCOMPONENT_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class FilterComponentModule: public PlaYUVerModuleIf { private: diff --git a/modules/FrameBinarization.cpp b/modules/FrameBinarization.cpp index 5ea8d58..fd7f7c5 100644 --- a/modules/FrameBinarization.cpp +++ b/modules/FrameBinarization.cpp @@ -24,6 +24,7 @@ #include "FrameBinarization.h" + FrameBinarization::FrameBinarization() { /* Module Definition */ diff --git a/modules/FrameBinarization.h b/modules/FrameBinarization.h index 4b53a0a..2b346c2 100644 --- a/modules/FrameBinarization.h +++ b/modules/FrameBinarization.h @@ -25,8 +25,10 @@ #ifndef __FRAMEBINARIZATION_H__ #define __FRAMEBINARIZATION_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class FrameBinarization: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameBinarization ) diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index 82f8082..e758ef4 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -24,6 +24,7 @@ #include "FrameCrop.h" + FrameCrop::FrameCrop() { /* Module Definition */ diff --git a/modules/FrameCrop.h b/modules/FrameCrop.h index f0d859a..f429bd2 100644 --- a/modules/FrameCrop.h +++ b/modules/FrameCrop.h @@ -25,8 +25,10 @@ #ifndef __FRAMECROP_H__ #define __FRAMECROP_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class FrameCrop: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameCrop ) diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index bbfefde..0ef9712 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -23,7 +23,7 @@ */ #include "FrameDifference.h" -#include + FrameDifference::FrameDifference() { diff --git a/modules/FrameDifference.h b/modules/FrameDifference.h index da43c63..8a388b0 100644 --- a/modules/FrameDifference.h +++ b/modules/FrameDifference.h @@ -25,9 +25,9 @@ #ifndef __FRAMEDIFFERENCE_H__ #define __FRAMEDIFFERENCE_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -#include class FrameDifference: public PlaYUVerModuleIf { diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index f5f6f7e..2a92fbd 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -23,8 +23,7 @@ */ #include "FrameMask.h" -#include -class be; + FrameMask::FrameMask() { diff --git a/modules/FrameMask.h b/modules/FrameMask.h index 09d0430..baf2cdf 100644 --- a/modules/FrameMask.h +++ b/modules/FrameMask.h @@ -25,9 +25,9 @@ #ifndef __FRAMEMASK_H__ #define __FRAMEMASK_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -#include class FrameMask: public PlaYUVerModuleIf { diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index ea7b495..0c098f4 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -24,6 +24,7 @@ #include "FrameShift.h" + FrameShift::FrameShift() { /* Module Definition */ diff --git a/modules/FrameShift.h b/modules/FrameShift.h index 758c972..78e86a2 100644 --- a/modules/FrameShift.h +++ b/modules/FrameShift.h @@ -25,8 +25,10 @@ #ifndef __FRAMESHIFT_H__ #define __FRAMESHIFT_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class FrameShift: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( FrameShift ) diff --git a/modules/LumaAverage.cpp b/modules/LumaAverage.cpp index 22dcf68..5e1d531 100644 --- a/modules/LumaAverage.cpp +++ b/modules/LumaAverage.cpp @@ -24,6 +24,7 @@ #include "LumaAverage.h" + LumaAverage::LumaAverage() { /* Module Definition */ diff --git a/modules/LumaAverage.h b/modules/LumaAverage.h index 4b51482..be46dd4 100644 --- a/modules/LumaAverage.h +++ b/modules/LumaAverage.h @@ -25,8 +25,10 @@ #ifndef __LUMAAVERAGE_H__ #define __LUMAAVERAGE_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class LumaAverage: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( LumaAverage ) diff --git a/modules/MeasureOpticalFlowDualTVL1.cpp b/modules/MeasureOpticalFlowDualTVL1.cpp index 139aa4b..a18b28a 100644 --- a/modules/MeasureOpticalFlowDualTVL1.cpp +++ b/modules/MeasureOpticalFlowDualTVL1.cpp @@ -23,7 +23,6 @@ */ #include "MeasureOpticalFlowDualTVL1.h" -#include using cv::Scalar; using cv::Mat; diff --git a/modules/MeasureOpticalFlowDualTVL1.h b/modules/MeasureOpticalFlowDualTVL1.h index 3692b0f..282f3ba 100644 --- a/modules/MeasureOpticalFlowDualTVL1.h +++ b/modules/MeasureOpticalFlowDualTVL1.h @@ -28,8 +28,10 @@ #include #include +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class MeasureOpticalFlowDualTVL1: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( MeasureOpticalFlowDualTVL1 ) diff --git a/modules/OpticalFlow.h b/modules/OpticalFlow.h index de739a6..4df33d5 100644 --- a/modules/OpticalFlow.h +++ b/modules/OpticalFlow.h @@ -32,6 +32,7 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" + class OpticalFlowModule: public PlaYUVerModuleIf { protected: @@ -77,6 +78,7 @@ public: Bool create( std::vector apcFrameList ); }; + class OpticalFlowFarneback: public OpticalFlowModule { REGISTER_CLASS_FACTORY( OpticalFlowFarneback ) diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index d80827d..30ab8f3 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -23,14 +23,18 @@ */ #include "config.h" +#include "PlaYUVerModuleFactory.h" + #include #include #ifdef USE_DYNLOAD #include #endif -#include "PlaYUVerModuleFactory.h" + +// Generated by cmake #include "ModulesListHeader.h" + PlaYUVerModuleFactory::PlaYUVerModuleFactory() { REGISTER_ALL_MODULES diff --git a/modules/PlaYUVerModuleFactory.h b/modules/PlaYUVerModuleFactory.h index 83bbe94..daee368 100644 --- a/modules/PlaYUVerModuleFactory.h +++ b/modules/PlaYUVerModuleFactory.h @@ -25,8 +25,9 @@ #ifndef __PLAYUVERMODULESFACTORY_H__ #define __PLAYUVERMODULESFACTORY_H__ -#include #include + +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" #define REGISTER_MODULE(X) Register( "X", &(X::Create) ); diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index ae52b76..539bbb6 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -19,7 +19,7 @@ /** * \file SetChromaHalfScale.cpp - * \brief Binarize frame module + * \brief Set chrome value to half scale (gray) */ #include "SetChromaHalfScale.h" diff --git a/modules/SetChromaHalfScale.h b/modules/SetChromaHalfScale.h index bcf16ea..9c865c5 100644 --- a/modules/SetChromaHalfScale.h +++ b/modules/SetChromaHalfScale.h @@ -19,12 +19,13 @@ /** * \file SetChromaHalfScale.h - * \brief Binarize frame module + * \brief Set chrome value to half scale (gray) */ -#ifndef __CHROMA128_H__ -#define __CHROMA128_H__ +#ifndef _SETCHROMAHALFSCALE_H_ +#define _SETCHROMAHALFSCALE_H_ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" class SetChromaHalfScale: public PlaYUVerModuleIf @@ -44,5 +45,5 @@ private: }; -#endif // __CHROMA128_H__ +#endif // _SETCHROMAHALFSCALE_H_ diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 5c75e9f..47076da 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -23,8 +23,6 @@ */ #include "WeightedPSNR.h" -#include -#include WeightedPSNR::WeightedPSNR() { diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h index c9743ca..c420e2b 100644 --- a/modules/WeightedPSNR.h +++ b/modules/WeightedPSNR.h @@ -25,10 +25,9 @@ #ifndef __WEIGHTEDPSNR_H__ #define __WEIGHTEDPSNR_H__ +// PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -#include - class WeightedPSNR: public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( WeightedPSNR ) From ccc0e11856cfd11f3fa1f713256bf58262ee1b4d Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 17 May 2016 21:33:11 +0100 Subject: [PATCH 086/127] Cleanup tools app --- lib/PlaYUVerDefs.h | 8 ++++---- tools/PlaYUVerTools.cpp | 12 ++++++------ tools/PlaYUVerTools.h | 6 ++++-- tools/PlaYUVerToolsCmdParser.cpp | 5 ++++- tools/PlaYUVerToolsCmdParser.h | 2 -- 5 files changed, 18 insertions(+), 15 deletions(-) diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 0639be6..4e7d678 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -80,10 +80,10 @@ typedef UChar Byte; // Limits definition // ==================================================================================================================== -#define MAX_UINT 0xFFFFFFFFU ///< max. value of unsigned 32-bit integer -#define MAX_INT 2147483647 ///< max. value of signed 32-bit integer -#define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of signed 64-bit integer -#define MAX_DOUBLE 1.7e+308 ///< max. value of double-type value +// #define MAX_UINT 0xFFFFFFFFU ///< max. value of unsigned 32-bit integer +// #define MAX_INT 2147483647 ///< max. value of signed 32-bit integer +// #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of signed 64-bit integer +// #define MAX_DOUBLE 1.7e+308 ///< max. value of double-type value // ==================================================================================================================== diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index a71dfcc..a1d8a4e 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -22,6 +22,7 @@ * \brief Main definition of the PlaYUVerTools APp */ +#include "config.h" #include "PlaYUVerTools.h" #include @@ -29,6 +30,7 @@ #include "lib/PlaYUVerPixel.h" #include "lib/PlaYUVerFrame.h" +#include "lib/PlaYUVerStream.h" #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" @@ -115,19 +117,17 @@ Int PlaYUVerTools::openInputs() } } - m_uiNumberOfFrames = MAX_UINT; + m_uiNumberOfFrames = UINT_MAX; if( Opts().hasOpt( "frames" ) ) { m_uiNumberOfFrames = m_iFrames; } - m_uiNumberOfComponents = MAX_UINT; + m_uiNumberOfComponents = UINT_MAX; for( UInt i = 0; i < m_apcInputStreams.size(); i++ ) { - if( m_apcInputStreams[i]->getFrameNum() < m_uiNumberOfFrames ) - m_uiNumberOfFrames = m_apcInputStreams[i]->getFrameNum(); - if( m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() < m_uiNumberOfComponents ) - m_uiNumberOfComponents = m_apcInputStreams[i]->getCurrFrame()->getNumberChannels(); + m_uiNumberOfFrames = std::min( m_uiNumberOfFrames, m_apcInputStreams[i]->getFrameNum() ); + m_uiNumberOfComponents = std::min( m_uiNumberOfComponents, m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() ); } return 0; diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index d636f31..3795098 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -25,14 +25,16 @@ #ifndef __PLAYUVERTOOLS_H__ #define __PLAYUVERTOOLS_H__ -#include "config.h" #include "lib/PlaYUVerDefs.h" #include "lib/PlaYUVerFrame.h" -#include "lib/PlaYUVerStream.h" + #include "PlaYUVerToolsCmdParser.h" +class PlaYUVerFrame; +class PlaYUVerStream; class PlaYUVerModuleIf; + #define MAX_NUMBER_INPUTS 10 class PlaYUVerTools: public PlaYUVerToolsCmdParser diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 83bd08a..7c1a509 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -22,14 +22,17 @@ * \brief Handle for command line */ +#include "PlaYUVerToolsCmdParser.h" + #include #include -#include "PlaYUVerToolsCmdParser.h" + #include "lib/PlaYUVerFrame.h" #include "lib/PlaYUVerStream.h" #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" + PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() { m_uiLogLevel = 0; diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index e5fb046..2b2cb77 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -29,8 +29,6 @@ #include "lib/PlaYUVerDefs.h" #include "lib/PlaYUVerOptions.h" -class PlaYUVerStream; - class PlaYUVerToolsCmdParser { public: From 72fec7e6e07e14be5a9f8991e50fe81e447a2422 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 19 May 2016 14:38:19 +0100 Subject: [PATCH 087/127] Remove file associations --- app/resources/playuver.desktop | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/resources/playuver.desktop b/app/resources/playuver.desktop index c0f9a90..7d52b74 100755 --- a/app/resources/playuver.desktop +++ b/app/resources/playuver.desktop @@ -5,6 +5,6 @@ Name=PlaYUVer Exec=playuver %U Icon=playuver Terminal=false -MimeType=video/x-raw;image/png;video/dv;video/mpeg;video/x-mpeg;video/msvideo;video/quicktime;video/x-anim;video/x-avi;video/x-ms-asf;video/x-ms-wmv;video/x-msvideo;video/x-nsv;video/x-flc;video/x-fli;video/x-flv;video/mp4;video/mp4v-es;video/mp2t;application/x-matroska;video/x-matroska;video/webm;x-content/video-vcd;x-content/video-svcd;image/gif;image/jpeg;image/png;image/bmp;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-xbitmap;image/x-xpixmap;image/tiff;image/x-psd; +MimeType=video/x-raw;image/jpeg;image/png;image/bmp;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap Categories=AudioVideo;Video;Player; GenericName=raw video player From fcfd2d5da151f0035dc79a60552aadbd4ed408ad Mon Sep 17 00:00:00 2001 From: Luis Lucas Date: Mon, 6 Jun 2016 13:51:39 +0100 Subject: [PATCH 088/127] Fix crashing when actual number of bits is larger than the specified one. --- CMakeLists.txt | 2 +- lib/PlaYUVerFrame.cpp | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index efb8a14..3912c0d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -148,7 +148,7 @@ IF( USE_WERROR ) SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror" ) ENDIF() -SET( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g" ) +SET( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -O0" ) SET( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2" ) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 4ddd1af..9a012b0 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -576,6 +576,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) Int endByte = bytesPixel; Int incByte = 1; Int b; + Int maxval = pow(2, d->m_uiBitsPel) - 1; if( d->m_iEndianness == 0 ) { @@ -608,6 +609,10 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) { *pPel += *pTmpBuff << ( b * 8 ); pTmpBuff++; + // Check max value and bound it to "maxval" to prevent segfault when calculating histogram + if(*pPel > maxval) + *pPel = 0; + // ----- } pPel++; pTmpBuff += step; From ade9ec3f2fdb28c53bceccaae10fb3a572a8a66d Mon Sep 17 00:00:00 2001 From: Luis Lucas Date: Mon, 6 Jun 2016 14:08:02 +0100 Subject: [PATCH 089/127] Add endianness parameter to filter component module, in order to avoid app crash when filtering images with more than 8bpp. --- modules/FilterComponent.cpp | 13 ++++++++----- modules/FilterComponent.h | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index c0378f5..fb6a586 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -31,10 +31,10 @@ FilterComponentModule::FilterComponentModule() m_pcFilteredFrame = NULL; } -Bool FilterComponentModule::createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel ) +Bool FilterComponentModule::createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel, UInt uiEndianness ) { m_pcFilteredFrame = NULL; - m_pcFilteredFrame = new PlaYUVerFrame( uiWidth, uiHeight, PlaYUVerFrame::GRAY, bitsPixel ); + m_pcFilteredFrame = new PlaYUVerFrame( uiWidth, uiHeight, PlaYUVerFrame::GRAY, bitsPixel, uiEndianness ); return true; } @@ -69,7 +69,8 @@ FilterComponentLuma::FilterComponentLuma() Bool FilterComponentLuma::create( std::vector apcFrameList ) { - return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getBitsPel(), + apcFrameList[0]->getEndianness() ); } PlaYUVerFrame* FilterComponentLuma::process( std::vector apcFrameList ) @@ -93,7 +94,8 @@ Bool FilterComponentChromaU::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel(), + apcFrameList[0]->getEndianness() ); } return false; } @@ -119,7 +121,8 @@ Bool FilterComponentChromaV::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel(), + apcFrameList[0]->getEndianness() ); } return false; } diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index 4744763..cfefc87 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -42,7 +42,7 @@ private: PlaYUVerFrame* process( std::vector apcFrameList ) = 0; Void destroy(); - Bool createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel ); + Bool createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel, UInt uiEndianness ); PlaYUVerFrame* filterComponent( PlaYUVerFrame* InputFrame, Int Component ); }; From f8eb8a365091f24fecc7e2f9acdcc117fbc79123 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 8 Jun 2016 16:28:56 +0100 Subject: [PATCH 090/127] Add tiff extension to libav handler --- lib/StreamHandlerLibav.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index add5e60..f0ff243 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -34,6 +34,7 @@ std::vector StreamHandlerLibav::supportedReadFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Tagged Image File Format", "tiff" ); // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); From fdcb04e400c2a38953f38401a55f4af3495518a2 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 21 Jun 2016 15:23:27 +0100 Subject: [PATCH 091/127] Add interval of pixel range --- app/FramePropertiesDock.cpp | 38 +++++++++++++++-------- app/FramePropertiesDock.h | 14 ++++----- lib/PlaYUVerFrame.cpp | 60 +++++++++++++++++++++++++++++++++++++ lib/PlaYUVerFrame.h | 3 ++ 4 files changed, 93 insertions(+), 22 deletions(-) diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index cb67391..ed44fbd 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -143,8 +143,8 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc // ------------------------------------------------------------- - QLabel *rangeLabel = new QLabel( tr( "Range:" ) ); - rangeLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); + QLabel *rangeSelectionLabel = new QLabel( tr( "Range:" ) ); + rangeSelectionLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); minInterv = new QSpinBox; minInterv->setRange( 0, 255 ); @@ -161,7 +161,7 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc " of the histogram selection." ) ); QHBoxLayout *rangeLayout = new QHBoxLayout; - rangeLayout->addWidget( rangeLabel ); + rangeLayout->addWidget( rangeSelectionLabel ); rangeLayout->addWidget( minInterv ); rangeLayout->addWidget( maxInterv ); @@ -179,6 +179,11 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc labelCountValue = new QLabel; labelCountValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); + QLabel *rangeLabel = new QLabel( tr( "Range:" ) ); + rangeLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); + labelRangeValue = new QLabel; + labelRangeValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); + QLabel *meanLabel = new QLabel( tr( "Mean:" ) ); meanLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelMeanValue = new QLabel; @@ -199,17 +204,20 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc labelPercentileValue = new QLabel; labelPercentileValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); + Int gridRow = 0; QGridLayout *statisticsLayout = new QGridLayout; - statisticsLayout->addWidget( pixelsLabel, 0, 0 ); - statisticsLayout->addWidget( labelPixelsValue, 0, 1 ); - statisticsLayout->addWidget( countLabel, 1, 0 ); - statisticsLayout->addWidget( labelCountValue, 1, 1 ); - statisticsLayout->addWidget( meanLabel, 2, 0 ); - statisticsLayout->addWidget( labelMeanValue, 2, 1 ); - statisticsLayout->addWidget( stdDevLabel, 3, 0 ); - statisticsLayout->addWidget( labelStdDevValue, 3, 1 ); - statisticsLayout->addWidget( medianLabel, 4, 0 ); - statisticsLayout->addWidget( labelMedianValue, 4, 1 ); + statisticsLayout->addWidget( pixelsLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelPixelsValue, gridRow++, 1 ); + statisticsLayout->addWidget( countLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelCountValue, gridRow++, 1 ); + statisticsLayout->addWidget( rangeLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelRangeValue, gridRow++, 1 ); + statisticsLayout->addWidget( meanLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelMeanValue, gridRow++, 1 ); + statisticsLayout->addWidget( stdDevLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelStdDevValue, gridRow++, 1 ); + statisticsLayout->addWidget( medianLabel, gridRow, 0 ); + statisticsLayout->addWidget( labelMedianValue, gridRow++, 1 ); // statisticsLayout->addWidget( percentileLabel, 5, 0 ); // statisticsLayout->addWidget( labelPercentileValue, 5, 1 ); @@ -437,6 +445,10 @@ Void FramePropertiesDock::updateStatistiques() if( frame ) { + + QString rangeText = "[" + QString::number( frame->getMin( channel ) ) + ":" + QString::number( frame->getMax( channel ) ) + "]"; + labelRangeValue->setText( rangeText ); + double mean = frame->getMean( channel, min, max ); labelMeanValue->setText( value.setNum( mean, 'f', 1 ) ); diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index 90071ef..2a490fd 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -90,19 +90,15 @@ private: QSpinBox *minInterv; QSpinBox *maxInterv; - QLabel *colorsLabel; - QLabel *labelMeanValue; QLabel *labelPixelsValue; - QLabel *labelStdDevValue; QLabel *labelCountValue; + QLabel *labelRangeValue; + QLabel *labelMeanValue; + QLabel *labelStdDevValue; QLabel *labelMedianValue; QLabel *labelPercentileValue; - QLabel *formatValueLabel; - QLabel *sizeValueLabel; - QLabel *colorSpaceValueLabel; - QLabel *colorModeValueLabel; - QLabel *depthValueLabel; - QLabel *alphaValueLabel; + + QLabel *colorsLabel; QRect m_cSelectionArea; diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 9a012b0..6737c30 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -901,6 +901,66 @@ Int getRealHistoChannel( Int colorSpace, Int channel ) return histoChannel; } +UInt PlaYUVerFrame::getMin( Int channel ) +{ + UInt value; + Int histoChannel; + Int indexStart; + + if( !d->m_bHasHistogram ) + { + return 0; + } + + histoChannel = getRealHistoChannel( getColorSpace(), channel ); + + if( histoChannel == -1 ) + { + return 0; + } + + indexStart = histoChannel * d->m_uiHistoSegments; + + for( value = 0; value <= d->m_uiHistoSegments; value++ ) + { + if( d->m_puiHistogram[indexStart + value] > 0) + { + break; + } + } + return value; +} + +UInt PlaYUVerFrame::getMax( Int channel ) +{ + Int value; + Int histoChannel; + Int indexStart; + + if( !d->m_bHasHistogram ) + { + return 0; + } + + histoChannel = getRealHistoChannel( getColorSpace(), channel ); + + if( histoChannel == -1 ) + { + return 0; + } + + indexStart = histoChannel * d->m_uiHistoSegments; + + for( value = d->m_uiHistoSegments - 1; value >= 0; value-- ) + { + if( d->m_puiHistogram[indexStart + value] > 0) + { + break; + } + } + return value; +} + UInt PlaYUVerFrame::getCount( Int channel, UInt start, UInt end ) { UInt i; diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 0343632..dbe26bb 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -223,6 +223,9 @@ public: */ Void calcHistogram(); + UInt getMin( Int channel ); + UInt getMax( Int channel ); + UInt getCount( Int channel, UInt start, UInt end ); Double getMean( Int channel, UInt start, UInt end ); Int getMedian( Int channel, UInt start, UInt end ); From 61174e310a1cd6e70139e88157a3df4fcb9d86ff Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 15 Sep 2016 13:08:09 +0100 Subject: [PATCH 092/127] Fix missing includes --- lib/PlaYUVerDefs.h | 2 ++ modules/WeightedPSNR.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 4e7d678..647541d 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -27,6 +27,8 @@ #define __PLAYUVERDEFS_H__ #include +#include +#include // ==================================================================================================================== // Basic type redefinition diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 47076da..df8f3e9 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -23,6 +23,7 @@ */ #include "WeightedPSNR.h" +#include WeightedPSNR::WeightedPSNR() { From bc4588226cd058ff56018edf2d6cb26fd320e98e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 26 Sep 2016 12:17:40 +0100 Subject: [PATCH 093/127] Add new optical flow algorithm into modules --- modules/CMakeLists.txt | 1 + modules/OpticalFlow.cpp | 15 +++++++++++++++ modules/OpticalFlow.h | 12 ++++++++++++ 3 files changed, 28 insertions(+) diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 8796b5c..98c4108 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -32,6 +32,7 @@ ADD_MODULE_USE_OPENCV( MeasureOpticalFlowDualTVL1 "MeasureOpticalFlowDualTVL1" V ADD_MODULE_USE_OPENCV( OpticalFlowDualTVL1 "OpticalFlow" VERSION 3.1.0 MODULES optflow ) ADD_MODULE_USE_OPENCV( OpticalFlowSparseToDense "OpticalFlow" VERSION 3.1.0 MODULES optflow ) ADD_MODULE_USE_OPENCV( OpticalFlowFarneback "OpticalFlow" VERSION 3.1.0 MODULES video optflow ) +ADD_MODULE_USE_OPENCV( OpticalDeepFlow "OpticalFlow" VERSION 3.1.0 MODULES video optflow ) ADD_MODULE_USE_OPENCV( DisparityStereoBM "DisparityStereoBM" VERSION 2.4.13.0 MODULES calib3d ) ADD_MODULE_USE_OPENCV( DisparityStereoSGBM "DisparityStereoSGBM" VERSION 2.4.13.0 MODULES calib3d ) diff --git a/modules/OpticalFlow.cpp b/modules/OpticalFlow.cpp index ba3e24d..8d538d2 100644 --- a/modules/OpticalFlow.cpp +++ b/modules/OpticalFlow.cpp @@ -210,5 +210,20 @@ Bool OpticalFlowFarneback::create( std::vector apcFrameList ) return bRet; } +OpticalDeepFlow::OpticalDeepFlow() +{ + /* Module Definition */ + m_pchModuleName = "OpticalDeepFlow"; + m_pchModuleTooltip = "Measure optical flow using Farneback method"; +} + +Bool OpticalDeepFlow::create( std::vector apcFrameList ) +{ + Bool bRet = commonCreate( apcFrameList ); + if( !bRet ) + return bRet; + m_cOpticalFlow = cv::optflow::createOptFlow_DeepFlow(); + return bRet; +} diff --git a/modules/OpticalFlow.h b/modules/OpticalFlow.h index 4df33d5..affe3ff 100644 --- a/modules/OpticalFlow.h +++ b/modules/OpticalFlow.h @@ -90,5 +90,17 @@ public: Bool create( std::vector apcFrameList ); }; +class OpticalDeepFlow: public OpticalFlowModule +{ + REGISTER_CLASS_FACTORY( OpticalDeepFlow ) +public: + OpticalDeepFlow(); + virtual ~OpticalDeepFlow() + { + } + Bool create( std::vector apcFrameList ); +}; + + #endif // __OPTICALFLOW_H__ From 8de161907980c9457922a5e6e7f5c44ef327e0da Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 13 Oct 2016 00:19:35 +0100 Subject: [PATCH 094/127] Add option to create a custom resolution --- app/ConfigureFormatDialog.cpp | 115 ++++++++++++++++++++++++++++++---- 1 file changed, 103 insertions(+), 12 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 5ddcce7..1829a08 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,76 @@ #include "ConfigureFormatDialog.h" +#define MAX_SUPPORTED_RESOLUTION 9999 + +class AddCustomFormat: public QDialog +{ +public: + AddCustomFormat( QWidget *parent = NULL ) : + QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ) + { + + setWindowModality( Qt::ApplicationModal ); + setWindowTitle( "Add custom resolution" ); + + QLabel* nameLabel = new QLabel( "Name" ); + m_lineEdtName = new QLineEdit(); + + QLabel* widthLabel = new QLabel( "Width" ); + m_spinWidth = new QSpinBox; + m_spinWidth->setMinimumSize( 70, 5 ); + m_spinWidth->setMaximumSize( 70, 30 ); + m_spinWidth->setMinimum( 0 ); + m_spinWidth->setMaximum( MAX_SUPPORTED_RESOLUTION ); + + QLabel* heightLabel = new QLabel( "Heigth" ); + m_spinHeight = new QSpinBox; + m_spinHeight->setMinimumSize( 70, 5 ); + m_spinHeight->setMaximumSize( 70, 30 ); + m_spinHeight->setMinimum( 0 ); + m_spinHeight->setMaximum( MAX_SUPPORTED_RESOLUTION ); + + QDialogButtonBox* dialogButtonOkCancel = new QDialogButtonBox(); + dialogButtonOkCancel->setObjectName( QString::fromUtf8( "dialogButtonBox" ) ); + dialogButtonOkCancel->setStandardButtons( QDialogButtonBox::Cancel | QDialogButtonBox::Ok ); + dialogButtonOkCancel->setCenterButtons( false ); + + QGridLayout* mainLayout = new QGridLayout; + mainLayout->addWidget( nameLabel, 0, 0, 1, 1, Qt::AlignCenter ); + mainLayout->addWidget( widthLabel, 0, 1, 1, 1, Qt::AlignCenter ); + mainLayout->addWidget( heightLabel, 0, 2, 1, 1, Qt::AlignCenter ); + + mainLayout->addWidget( m_lineEdtName, 1, 0, 1, 1, Qt::AlignCenter ); + mainLayout->addWidget( m_spinWidth, 1, 1, 1, 1, Qt::AlignCenter ); + mainLayout->addWidget( m_spinHeight, 1, 2, 1, 1, Qt::AlignCenter ); + + mainLayout->addWidget( dialogButtonOkCancel, 2, 0, 1, 3, Qt::AlignRight ); + + setLayout( mainLayout ); + + connect( dialogButtonOkCancel, SIGNAL( accepted() ), this, SLOT( accept() ) ); + connect( dialogButtonOkCancel, SIGNAL( rejected() ), this, SLOT( reject() ) ); + } + + PlaYUVerStdResolution runDialog() + { + PlaYUVerStdResolution stdResolution; + stdResolution.shortName = ""; + if( exec() == QDialog::Accepted ) + { + stdResolution.shortName = m_lineEdtName->text().toStdString(); + stdResolution.uiWidth = m_spinWidth->value(); + stdResolution.uiHeight = m_spinHeight->value(); + } + return stdResolution; + } + +private: + QLineEdit* m_lineEdtName; + QSpinBox* m_spinWidth; + QSpinBox* m_spinHeight; +}; + ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : QDialog( parent ) { @@ -52,6 +123,9 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : standardResolutionSizes.append( QSize( uiWidth, uiHeight ) ); } + standardResolutionNames.append( QStringLiteral( "Custom..." ) ); + standardResolutionSizes.append( QSize( 0, 0 ) ); + setObjectName( "ConfigureFormat" ); setWindowTitle( "Configure Resolution" ); @@ -71,16 +145,16 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : normalFont.setBold( false ); // menusFont.setPointSize( 12 ); -// // headLayout -// QHBoxLayout* headLayout = new QHBoxLayout(); -// QLabel* dialogTitleLabel = new QLabel(); -// dialogTitleLabel->setFont( titleFont ); -// dialogTitleLabel->setText( "Configure Resolution" ); -// headLayout->addWidget( dialogTitleLabel ); -// headLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); -// -// MainLayout->addLayout( headLayout ); -// MainLayout->addItem( new QSpacerItem( 10, 20, QSizePolicy::Minimum ) ); + // // headLayout + // QHBoxLayout* headLayout = new QHBoxLayout(); + // QLabel* dialogTitleLabel = new QLabel(); + // dialogTitleLabel->setFont( titleFont ); + // dialogTitleLabel->setText( "Configure Resolution" ); + // headLayout->addWidget( dialogTitleLabel ); + // headLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + // + // MainLayout->addLayout( headLayout ); + // MainLayout->addItem( new QSpacerItem( 10, 20, QSizePolicy::Minimum ) ); /* * Filename layout @@ -122,14 +196,14 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : QLabel* widthLabel = new QLabel( "Width" ); widthLabel->setFont( normalFont ); m_spinBoxWidth = new QSpinBox(); - m_spinBoxWidth->setRange( 0, 99999 ); + m_spinBoxWidth->setRange( 0, MAX_SUPPORTED_RESOLUTION ); m_spinBoxWidth->setValue( 0 ); m_spinBoxWidth->setFont( normalFont ); QLabel* heightLabel = new QLabel( "Height" ); heightLabel->setFont( normalFont ); m_spinBoxheight = new QSpinBox(); - m_spinBoxheight->setRange( 0, 99999 ); + m_spinBoxheight->setRange( 0, MAX_SUPPORTED_RESOLUTION ); m_spinBoxheight->setValue( 0 ); m_spinBoxheight->setFont( normalFont ); @@ -340,6 +414,23 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UI void ConfigureFormatDialog::slotStandardResolutionSelected( Int idx ) { + if( idx == standardResolutionSizes.size() - 1 ) + { + AddCustomFormat* pcCustomFmtDialog = new AddCustomFormat; + PlaYUVerStdResolution customResolution = pcCustomFmtDialog->runDialog(); + if( customResolution.shortName != "" ) + { + QString name = QString::fromStdString( customResolution.shortName ); + name.append( QString( " (%2x%3)" ).arg( customResolution.uiWidth ).arg( customResolution.uiHeight ) ); + standardResolutionNames.append( name ); + standardResolutionSizes.append( QSize( customResolution.uiWidth, customResolution.uiHeight ) ); + + m_comboBoxStandardResolution->blockSignals( true ); + m_comboBoxStandardResolution->insertItem( 0, name ); + m_comboBoxStandardResolution->setCurrentIndex( 0 ); + m_comboBoxStandardResolution->blockSignals( false ); + } + } if( idx >= 0 ) { QSize currSize = standardResolutionSizes.at( idx ); From 5f6ad706df15b7364a2bb850d27c59e272b5299e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 27 Oct 2016 16:40:37 +0100 Subject: [PATCH 095/127] Fix saving of custom resolutions --- app/ConfigureFormatDialog.cpp | 66 +++++++++++++++++++++++++++++++++-- app/ConfigureFormatDialog.h | 12 +++++++ app/main.cpp | 3 ++ 3 files changed, 78 insertions(+), 3 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 1829a08..659ea58 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -29,17 +29,48 @@ #include #include #include +#include #include #include #include #include "lib/PlaYUVerFrame.h" -#include "lib/PlaYUVerStream.h" #include "ConfigureFormatDialog.h" #define MAX_SUPPORTED_RESOLUTION 9999 +QDataStream& operator<<( QDataStream& out, const PlaYUVerStdResolutionVector& array ) +{ + PlaYUVerStdResolution d; + out << array.size(); + for( Int i = 0; i < array.size(); i++ ) + { + d = array.at( i ); + out << QString::fromStdString( d.shortName ) + << d.uiWidth + << d.uiHeight; + } + return out; +} + +QDataStream& operator>>( QDataStream& in, PlaYUVerStdResolutionVector& array ) +{ + PlaYUVerStdResolution d; + QString auxName; + Int array_size; + in >> array_size; + for( Int i = 0; i < array_size; i++ ) + { + in >> auxName; + d.shortName = auxName.toStdString(); + in >> d.uiWidth; + in >> d.uiHeight; + array.append( d ); + } + return in; +} + class AddCustomFormat: public QDialog { public: @@ -113,6 +144,17 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : { QString Name; UInt uiWidth, uiHeight; + + readSettings(); + for( UInt i = 0; i < aRCustomFileFormats.size(); i++ ) + { + Name = QString::fromStdString( aRCustomFileFormats[i].shortName ); + uiWidth = aRCustomFileFormats[i].uiWidth; + uiHeight = aRCustomFileFormats[i].uiHeight; + standardResolutionNames.append( QString( "%1 (%2x%3)" ).arg( Name ).arg( uiWidth ).arg( uiHeight ) ); + standardResolutionSizes.append( QSize( uiWidth, uiHeight ) ); + } + std::vector listPlaYUVerStdResolution = PlaYUVerStream::stdResolutionSizes(); for( UInt i = 0; i < listPlaYUVerStdResolution.size(); i++ ) { @@ -391,6 +433,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UI } if( exec() == QDialog::Rejected ) { + writeSettings(); return QDialog::Rejected; } rWidth = m_spinBoxWidth->value(); @@ -409,6 +452,7 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UI rBits = m_spinBoxBits->value(); rEndianess = m_comboBoxEndianness->currentIndex(); rFrameRate = m_spinBoxFrameRate->value(); + writeSettings(); return QDialog::Accepted; } @@ -418,12 +462,13 @@ void ConfigureFormatDialog::slotStandardResolutionSelected( Int idx ) { AddCustomFormat* pcCustomFmtDialog = new AddCustomFormat; PlaYUVerStdResolution customResolution = pcCustomFmtDialog->runDialog(); + aRCustomFileFormats.append( customResolution ); if( customResolution.shortName != "" ) { QString name = QString::fromStdString( customResolution.shortName ); name.append( QString( " (%2x%3)" ).arg( customResolution.uiWidth ).arg( customResolution.uiHeight ) ); - standardResolutionNames.append( name ); - standardResolutionSizes.append( QSize( customResolution.uiWidth, customResolution.uiHeight ) ); + standardResolutionNames.insert( 0, name ); + standardResolutionSizes.insert( 0, QSize( customResolution.uiWidth, customResolution.uiHeight ) ); m_comboBoxStandardResolution->blockSignals( true ); m_comboBoxStandardResolution->insertItem( 0, name ); @@ -484,3 +529,18 @@ Void ConfigureFormatDialog::slotBitsChange( Int idx ) } } +Void ConfigureFormatDialog::readSettings() +{ + QSettings appSettings; + QVariant value = appSettings.value( "ConfigureFormatDialog/CustomFormats" ); + aRCustomFileFormats = value.value(); + +} + +Void ConfigureFormatDialog::writeSettings() +{ + QSettings appSettings; + QVariant var; + var.setValue( aRCustomFileFormats ); + appSettings.setValue( "ConfigureFormatDialog/CustomFormats", var ); +} diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index fc78f3b..8e5daec 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -29,6 +29,7 @@ #include #include "PlaYUVerAppDefs.h" +#include "lib/PlaYUVerStream.h" class QComboBox; class QHBoxLayout; @@ -37,6 +38,10 @@ class QSpinBox; class QString; class QWidget; +typedef QVector PlaYUVerStdResolutionVector; +QDataStream& operator<<( QDataStream& out, const PlaYUVerStdResolutionVector& array ); +QDataStream& operator>>( QDataStream& in, PlaYUVerStdResolutionVector& array ); + /** * */ @@ -49,6 +54,9 @@ public: ConfigureFormatDialog( QWidget *parent = 0 ); Int runConfigureFormatDialog( const QString& Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ); + Void readSettings(); + Void writeSettings(); + private Q_SLOTS: void slotStandardResolutionSelected( int ); void slotResolutionChange(); @@ -58,6 +66,7 @@ private Q_SLOTS: private: QStringList standardResolutionNames; QVector standardResolutionSizes; + PlaYUVerStdResolutionVector aRCustomFileFormats; QLabel* m_labelFilename; QComboBox *m_comboBoxStandardResolution; @@ -73,4 +82,7 @@ private: }; +Q_DECLARE_METATYPE( PlaYUVerStdResolution ); +Q_DECLARE_METATYPE( PlaYUVerStdResolutionVector ); + #endif // __CONFIGUREFORMATDIALOG_H__ diff --git a/app/main.cpp b/app/main.cpp index e707bfa..fdadc31 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -27,6 +27,7 @@ #include "PlaYUVerAppDefs.h" #include "PlaYUVerApp.h" #include "VideoSubWindow.h" +#include "ConfigureFormatDialog.h" #ifdef USE_QTDBUS #include "PlaYUVerAppAdaptor.h" #endif @@ -42,6 +43,8 @@ int main( int argc, char *argv[] ) { qRegisterMetaType(); qRegisterMetaTypeStreamOperators(); + qRegisterMetaType(); + qRegisterMetaTypeStreamOperators(); QApplication application( argc, argv ); QApplication::setApplicationName( "PlaYUVer" ); From 2aaeb9f6edd8077bb348c351425570b59f17b60b Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 29 Oct 2016 04:25:33 +0100 Subject: [PATCH 096/127] Version bump 0.11.0 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3912c0d..37ca70e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ set( PROJECT_NAME "playuver" CACHE INTERNAL "" FORCE ) PROJECT( ${PROJECT_NAME} ) SET( PLAYUVER_VERSION_MAJOR "0" ) -SET( PLAYUVER_VERSION_MINOR "10" ) +SET( PLAYUVER_VERSION_MINOR "11" ) SET( PLAYUVER_VERSION_PATCH "0" ) set( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLAYUVER_VERSION_PATCH}" CACHE INTERNAL "" FORCE ) From 10a6d64e8df5bb9f8a88e25c6a9f76fcf1445762 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 31 Oct 2016 14:25:40 +0000 Subject: [PATCH 097/127] Fix custom resolution message when open a new sequence --- app/ConfigureFormatDialog.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 659ea58..d480e57 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -33,12 +33,13 @@ #include #include #include +#include #include "lib/PlaYUVerFrame.h" #include "ConfigureFormatDialog.h" -#define MAX_SUPPORTED_RESOLUTION 9999 +#define MAX_SUPPORTED_RESOLUTION 99999 QDataStream& operator<<( QDataStream& out, const PlaYUVerStdResolutionVector& array ) { @@ -423,19 +424,23 @@ Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UI m_widgetEndianness->setVisible( false ); } m_spinBoxFrameRate->setValue( rFrameRate ); - for( Int i = 0; i < standardResolutionSizes.size(); i++ ) + + for( Int i = 0; i < standardResolutionSizes.size() - 1; i++ ) { if( standardResolutionSizes.at( i ) == QSize( rWidth, rHeight ) ) { m_comboBoxStandardResolution->setCurrentIndex( i ); + qDebug() << "ola"; break; } } + if( exec() == QDialog::Rejected ) { writeSettings(); return QDialog::Rejected; } + rWidth = m_spinBoxWidth->value(); rHeight = m_spinBoxheight->value(); colorSpace = m_comboBoxColorSpace->currentIndex(); From e68b091e4326b2f7a7d40f12a89f0ffb6725f1fe Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 31 Oct 2016 14:49:18 +0000 Subject: [PATCH 098/127] Add .rgb format --- lib/PlaYUVerStream.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index efcb150..c9d6569 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -48,6 +48,7 @@ std::vector PlaYUVerStream::supportedReadFormats() INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "yuv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "gray" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "rgb" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable BitMap ", "pbm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable GrayMap ", "pgm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerPortableMap::Create, "Portable PixMap ", "ppm" ); From 07ec18822abde6d998f075783f8275209b3259f0 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 31 Oct 2016 15:17:25 +0000 Subject: [PATCH 099/127] Add feautes list to about dialog --- app/AboutDialog.cpp | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index e07a6d3..cd67614 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -23,6 +23,8 @@ * Based on the work of Glad Deschrijver in KTikZ project */ +#include + #include "AboutDialog.h" #include #include @@ -30,24 +32,46 @@ #include #include +#define TAB_FROM_SPACES "   " + AboutDialog::AboutDialog( QWidget *parent ) : QDialog( parent ) { - QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ).scaled( QSize( 350, 350 ), Qt::KeepAspectRatio ); + QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ).scaled( QSize( 500, 350 ), Qt::KeepAspectRatio ); QLabel *pixmapLabel = new QLabel; pixmapLabel->setPixmap( logo ); - QLabel *label = new QLabel( QString( "

%1 Version %2

%3

%4

" ) + QLabel *label = new QLabel( QString( "

%1 Version %2

%3

" ) .arg( QApplication::applicationName() ) .arg( QApplication::applicationVersion() ) - .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) - .arg( tr( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ) ); + .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) ); label->setWordWrap( true ); + + QString featuresList = QStringLiteral( "

Features:

    " ); + +#ifdef USE_QTDBUS + featuresList.append( QStringLiteral( "
  • Support for Qt DBus messages" ) ); +#endif +#ifdef USE_FFMPEG + featuresList.append( QStringLiteral( "
  • Support for FFmpeg" ) ); +#endif +#ifdef USE_OPENCV + featuresList.append( QStringLiteral( "
  • Support for OpenCV" ) ); +#endif + featuresList.append( QStringLiteral( "

" ) ); + + QLabel *labelFeatures = new QLabel( featuresList ); + + + QLabel *labelCopyright = new QLabel( QStringLiteral( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ); + QWidget *topWidget = new QWidget; QVBoxLayout *topLayout = new QVBoxLayout; topLayout->addWidget( pixmapLabel ); topLayout->addWidget( label ); + topLayout->addWidget( labelFeatures ); + topLayout->addWidget( labelCopyright ); topWidget->setLayout( topLayout ); // QTextEdit *textEdit = new QTextEdit(tr("

This program is free " From 41159c5bd732f703ae2ed41351779d5a4e223cf9 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 31 Oct 2016 15:17:36 +0000 Subject: [PATCH 100/127] fix using of custom resolution --- app/ConfigureFormatDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index d480e57..f24955f 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -477,8 +477,8 @@ void ConfigureFormatDialog::slotStandardResolutionSelected( Int idx ) m_comboBoxStandardResolution->blockSignals( true ); m_comboBoxStandardResolution->insertItem( 0, name ); - m_comboBoxStandardResolution->setCurrentIndex( 0 ); m_comboBoxStandardResolution->blockSignals( false ); + m_comboBoxStandardResolution->setCurrentIndex( 0 ); } } if( idx >= 0 ) From ed0b967234a97da402e4fa5370e49a5590329457 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 18 Nov 2016 17:41:09 +0000 Subject: [PATCH 101/127] Add RGB planar format and try to guess bpp --- app/VideoSubWindow.cpp | 20 +++++++++++++++++--- app/VideoSubWindow.h | 2 +- lib/PlaYUVerFrame.h | 1 + lib/PlaYUVerFramePixelFormats.cpp | 24 +++++++++++++++++++----- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 04a46a1..f3c6f65 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -317,7 +317,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) m_pCurrStream = new PlaYUVerStream; } - if( guessFormat( cFilename, Width, Height, InputFormat, FrameRate ) || bForceDialog ) + if( guessFormat( cFilename, Width, Height, InputFormat, BitsPel ) || bForceDialog ) { if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) @@ -428,7 +428,7 @@ Void VideoSubWindow::updateVideoWindowInfo() } } -Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rFrameRate ) +Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel ) { std::vector stdResList = PlaYUVerStream::stdResolutionSizes(); Bool bGuessed = true; @@ -470,8 +470,9 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, rWidth = stdResList[iMatch].uiWidth; rHeight = stdResList[iMatch].uiHeight; } - // Guess resolution - match %dx%d + #if( QT_VERSION_PLAYUVER == 5 ) + // Guess resolution - match %dx%d QRegularExpressionMatch resolutionMatch = QRegularExpression( "_\\d*x\\d*" ).match( FilenameShort ); if( resolutionMatch.hasMatch() ) { @@ -487,6 +488,19 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, } } } + // Guess bits per pixel - match %dbpp + QRegularExpressionMatch BppMatch = QRegularExpression( "_\\d*bpp" ).match( FilenameShort ); + if( BppMatch.hasMatch() ) + { + QString matchString = BppMatch.captured( 0 ); + matchString.remove( "_" ); + matchString.remove( "bpp" ); + rBitsPerPixel = matchString.toUInt(); + if( !( rBitsPerPixel > 0 && rBitsPerPixel < 16 ) ) + { + rBitsPerPixel = -1; + } + } #endif } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index c448eca..b803912 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -103,7 +103,7 @@ private: Void refreshFrameOperation(); - static Bool guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rFrameRate ); + static Bool guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel ); /** * Private zoom function to handle diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index dbe26bb..654d3ac 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -58,6 +58,7 @@ public: YUV422p, YUYV422, GRAY, + RGBp, RGB24, BGR24, NUMBER_PEL_FORMATS diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 2bd4374..07c3b9e 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -268,7 +268,21 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU { { 0, 0, 1 } }, /* Y */ }, { - "RGB24", + "RGBp", + PlaYUVerPixel::COLOR_RGB, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + { + { 0, 0, 1 }, /* R */ + { 1, 0, 1 }, /* G */ + { 2, 0, 1 }, /* B */ + }, + }, + { + "RGB", PlaYUVerPixel::COLOR_RGB, 3, 1, @@ -282,7 +296,7 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU }, }, { - "BGR24", + "BGR", PlaYUVerPixel::COLOR_RGB, 3, 1, @@ -290,9 +304,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), { - { 0, 2, 3}, /* R */ - { 0, 2, 2}, /* G */ - { 0, 2, 1}, /* B */ + { 0, 2, 3}, /* B */ + { 0, 2, 2}, /* R */ + { 0, 2, 1}, /* G */ }, } }; From aaeaef7438fd2d5b59e3c80302fbac15c719bbfc Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Mon, 21 Nov 2016 12:20:26 +0000 Subject: [PATCH 102/127] Fix guessing format function --- app/VideoSubWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index f3c6f65..ee28aab 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -440,7 +440,7 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, { return false; } - if( !fileExtension.compare( "yuv" ) ) + if( !fileExtension.compare( "yuv" ) || !fileExtension.compare( "gray" ) || !fileExtension.compare( "gray" ) ) { bGuessed = false; // Guess pixel format From 0e8984fa413a917f1ff074cdf44e8a40f1a0f4dd Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 24 Nov 2016 17:52:19 +0000 Subject: [PATCH 103/127] Bugfix: wrong if instruction --- app/VideoSubWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index ee28aab..25229b9 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -440,7 +440,7 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, { return false; } - if( !fileExtension.compare( "yuv" ) || !fileExtension.compare( "gray" ) || !fileExtension.compare( "gray" ) ) + if( !fileExtension.compare( "yuv" ) || !fileExtension.compare( "rgb" ) || !fileExtension.compare( "gray" ) ) { bGuessed = false; // Guess pixel format From 6d2f5eacdb31bf1eb19f13290b8b3f4c53c461c1 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 24 Nov 2016 18:24:32 +0000 Subject: [PATCH 104/127] Fix PSNR formula --- lib/PlaYUVerFrame.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 6737c30..7a2325d 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1327,10 +1327,12 @@ Double PlaYUVerFrame::getMSE( PlaYUVerFrame* Org, Int component ) Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) { + UInt uiMaxValue = ( 1 << Org->getBitsPel() ); + Double uiMaxValueSquare = uiMaxValue * uiMaxValue; Double dPSNR = 100; Double dMSE = getMSE( Org, component ); if( dMSE != 0 ) - dPSNR = 10 * log10( 65025 / dMSE ); + dPSNR = 10 * log10( uiMaxValueSquare / dMSE ); return dPSNR; } From 594b0eee1d90493ae87f741f6250668bf231ff7f Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 25 Nov 2016 09:53:05 +0000 Subject: [PATCH 105/127] Bugfix PSNR calculation --- lib/PlaYUVerFrame.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 7a2325d..fc62f7e 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1327,7 +1327,7 @@ Double PlaYUVerFrame::getMSE( PlaYUVerFrame* Org, Int component ) Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) { - UInt uiMaxValue = ( 1 << Org->getBitsPel() ); + UInt uiMaxValue = ( 1 << Org->getBitsPel() - 1 ); Double uiMaxValueSquare = uiMaxValue * uiMaxValue; Double dPSNR = 100; Double dMSE = getMSE( Org, component ); From af6ec494a210687f79ac990a6f22b2a8aa3dbc4e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 30 Nov 2016 02:09:28 +0000 Subject: [PATCH 106/127] Fix some warnings --- app/VideoSubWindow.cpp | 5 +---- lib/PlaYUVerStream.cpp | 6 +++--- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 25229b9..bdf6eee 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -507,15 +507,12 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, // Guess resolution by file size if( rWidth == 0 && rHeight == 0 ) { - Char *filename_char = new char[filename.length() + 1]; - memcpy( filename_char, filename.toUtf8().constData(), filename.length() + 1 * sizeof(char) ); - FILE* pF = fopen( filename_char, "rb" ); + FILE* pF = fopen( filename.toStdString().c_str(), "rb" ); if( pF ) { fseek( pF, 0, SEEK_END ); UInt64 uiFileSize = ftell( pF ); fclose( pF ); - delete[] filename_char; Int count = 0, module, frame_bytes, match; for( UInt i = 0; i < stdResList.size(); i++ ) diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index c9d6569..7b71812 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -164,8 +164,8 @@ String PlaYUVerStream::getCodecName() Bool PlaYUVerStream::open( String filename, String resolution, String input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) { - UInt width; - UInt height; + UInt width = 0; + UInt height = 0; Int input_format = -1; if( resolution.size() > 0 ) @@ -575,7 +575,7 @@ Bool PlaYUVerStream::seekInputRelative( Bool bIsFoward ) Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) { - if( !m_bInit || new_frame_num < 0 || new_frame_num >= m_uiTotalFrameNum || ( Int64 )new_frame_num == m_iCurrFrameNum ) + if( !m_bInit || new_frame_num >= m_uiTotalFrameNum || ( Int64 )new_frame_num == m_iCurrFrameNum ) return false; m_iCurrFrameNum = new_frame_num - 1; From 26cd949d9a2a34ff05ebbe8e7a7cc7cbc099bd8f Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 15 Dec 2016 16:51:13 +0000 Subject: [PATCH 107/127] Add guessing for endianness --- app/VideoSubWindow.cpp | 44 ++++++++++++++++++++++++++++-------------- app/VideoSubWindow.h | 7 ++++++- lib/PlaYUVerDefs.h | 7 +++++++ 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index bdf6eee..718d43e 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -428,7 +428,7 @@ Void VideoSubWindow::updateVideoWindowInfo() } } -Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel ) +Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel, Int& rEndianness ) { std::vector stdResList = PlaYUVerStream::stdResolutionSizes(); Bool bGuessed = true; @@ -488,19 +488,6 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, } } } - // Guess bits per pixel - match %dbpp - QRegularExpressionMatch BppMatch = QRegularExpression( "_\\d*bpp" ).match( FilenameShort ); - if( BppMatch.hasMatch() ) - { - QString matchString = BppMatch.captured( 0 ); - matchString.remove( "_" ); - matchString.remove( "bpp" ); - rBitsPerPixel = matchString.toUInt(); - if( !( rBitsPerPixel > 0 && rBitsPerPixel < 16 ) ) - { - rBitsPerPixel = -1; - } - } #endif } @@ -534,6 +521,35 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, } } + // Guess bits per pixel - match %dbpp +#if( QT_VERSION_PLAYUVER == 5 ) + QRegularExpressionMatch BppMatch = QRegularExpression( "_\\d*bpp" ).match( FilenameShort ); + if( BppMatch.hasMatch() ) + { + QString matchString = BppMatch.captured( 0 ); + matchString.remove( "_" ); + matchString.remove( "bpp" ); + rBitsPerPixel = matchString.toUInt(); + if( !( rBitsPerPixel > 0 && rBitsPerPixel < 16 ) ) + { + rBitsPerPixel = -1; + } + } +#endif + + // Guess Endianness + if( rEndianness == -1 ) + { + if( FilenameShort.contains( QStringLiteral( "be" ), Qt::CaseInsensitive ) ) + { + rEndianness = PLAYUVER_BIG_ENDIAN; + } + if( FilenameShort.contains( QStringLiteral( "le" ), Qt::CaseInsensitive ) ) + { + rEndianness = PLAYUVER_LITTLE_ENDIAN; + } + } + if( rWidth > 0 && rHeight > 0 && rInputFormat >= 0 ) bGuessed = true && !bGuessedByFilesize; } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index b803912..badbb44 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -103,7 +103,7 @@ private: Void refreshFrameOperation(); - static Bool guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel ); + static Bool guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel, Int& rEndianness ); /** * Private zoom function to handle @@ -164,6 +164,11 @@ public: return m_pCurrStream; } + PlaYUVerStream* getCurrStream() + { + return m_pCurrStream; + } + PlaYUVerFrame* getCurrFrame() { return m_pcCurrFrame; diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 647541d..7461c49 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -115,6 +115,13 @@ enum RGBcomponent COLOR_A, }; +enum Endianness +{ + PLAYUVER_BIG_ENDIAN = 0, + PLAYUVER_LITTLE_ENDIAN = 1, +}; + + inline String lowercase( const String& in ) { String out; From 8afb575c1f9d7ac230f06cb84b9d10a77cb0c51e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 15 Dec 2016 16:55:57 +0000 Subject: [PATCH 108/127] Finish last commit --- app/VideoSubWindow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 718d43e..170a964 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -306,7 +306,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) { ConfigureFormatDialog formatDialog( this ); UInt Width = 0, Height = 0, BitsPel = 8, FrameRate = 30; - Int Endianness = 0; + Int Endianness = PLAYUVER_BIG_ENDIAN; Int InputFormat = PlaYUVerFrame::YUV420p; if( m_pCurrStream ) @@ -317,7 +317,7 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) m_pCurrStream = new PlaYUVerStream; } - if( guessFormat( cFilename, Width, Height, InputFormat, BitsPel ) || bForceDialog ) + if( guessFormat( cFilename, Width, Height, InputFormat, BitsPel, Endianness ) || bForceDialog ) { if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) == QDialog::Rejected ) From f42be2c25be29251a083e70e525a418095c1443e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 20 Dec 2016 16:00:46 +0000 Subject: [PATCH 109/127] Bugfix in MSE calculation --- lib/PlaYUVerFrame.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index fc62f7e..9d0a6a6 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1322,7 +1322,7 @@ Double PlaYUVerFrame::getMSE( PlaYUVerFrame* Org, Int component ) { return 0.0; } - return ssd / ( Org->getWidth() * Org->getHeight() ); + return ssd / Double( numberOfPixels ); } Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) From 57c81319b2693874fee3f755dd21327f0a7a0d7c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 20 Dec 2016 18:21:33 +0000 Subject: [PATCH 110/127] Add InterFrameVariance module Now modules support variable number of inputs --- app/ModulesHandle.cpp | 17 +++-- app/PlaYUVerAppModuleIf.cpp | 4 +- app/PlaYUVerAppModuleIf.h | 4 +- lib/PlaYUVerModuleIf.h | 8 ++- modules/CMakeLists.txt | 1 + modules/InterFrameVariance.cpp | 111 +++++++++++++++++++++++++++++++++ modules/InterFrameVariance.h | 51 +++++++++++++++ 7 files changed, 184 insertions(+), 12 deletions(-) create mode 100644 modules/InterFrameVariance.cpp create mode 100644 modules/InterFrameVariance.h diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index f2b8a99..d3aaf63 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -279,10 +279,17 @@ Void ModulesHandle::activateModule() Int numberOfFrames = pcCurrAppModuleIf->m_pcModule->m_uiNumberOfFrames; if( numberOfFrames > MODULE_REQUIRES_ONE_FRAME ) // Show dialog to select sub windows { - DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, SubWindowAbstract::VIDEO_SUBWINDOW, numberOfFrames, numberOfFrames ); + Int minNumFrames = numberOfFrames; + Int maxNumFrames = numberOfFrames; + if( numberOfFrames == MODULE_REQUIRES_SEVERAL_FRAMES ) + { + minNumFrames = 0; + maxNumFrames = 255; + } + DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, SubWindowAbstract::VIDEO_SUBWINDOW, minNumFrames, maxNumFrames ); QList windowsList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); - if( windowsList.size() <= numberOfFrames ) + if( windowsList.size() == minNumFrames && windowsList.size() == maxNumFrames ) { for( Int i = 0; i < windowsList.size(); i++ ) { @@ -291,7 +298,7 @@ Void ModulesHandle::activateModule() } else { - if( windowsList.size() <= numberOfFrames ) + if( windowsList.size() <= minNumFrames ) { for( Int i = 0; i < windowsList.size(); i++ ) { @@ -400,7 +407,7 @@ Void ModulesHandle::activateModule() { if( pcCurrAppModuleIf->m_pcDisplaySubWindow ) pcCurrAppModuleIf->m_pcDisplaySubWindow->enableModule( pcCurrAppModuleIf ); - for( Int i = 0; i < numberOfFrames; i++ ) + for( Int i = 0; i < videoSubWindowList.size(); i++ ) { pcCurrAppModuleIf->m_pcSubWindow[i]->associateModule( pcCurrAppModuleIf ); } @@ -411,7 +418,7 @@ Void ModulesHandle::activateModule() if( pcCurrAppModuleIf->m_pcModule->m_iModuleAPI == MODULE_API_2 ) { std::vector apcFrameList; - for( UInt i = 0; i < pcCurrAppModuleIf->m_pcModule->m_uiNumberOfFrames; i++ ) + for( UInt i = 0; i < videoSubWindowList.size(); i++ ) { apcFrameList.push_back( pcCurrAppModuleIf->m_pcSubWindow[i]->getCurrFrame() ); } diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 6998717..fb4d85e 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -38,7 +38,7 @@ PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaY m_dMeasurementResult( 0 ) { setParent( parent ); - for( Int i = 0; i < MAX_NUMBER_FRAMES; i++ ) + for( Int i = 0; i < MODULE_REQUIRES_MAX_NUM_FRAMES; i++ ) { m_pcSubWindow[i] = NULL; } @@ -194,7 +194,7 @@ Void PlaYUVerAppModuleIf::destroy() m_pcDisplaySubWindow->closeSubWindow(); m_pcDisplaySubWindow = NULL; - for( Int i = 0; i < MAX_NUMBER_FRAMES; i++ ) + for( Int i = 0; i < MODULE_REQUIRES_MAX_NUM_FRAMES; i++ ) { if( m_pcSubWindow[i] ) { diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index 36b1980..7536f18 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -60,7 +60,7 @@ private: QAction* m_pcModuleAction; PlaYUVerModuleIf* m_pcModule; - VideoSubWindow* m_pcSubWindow[MAX_NUMBER_FRAMES]; + VideoSubWindow* m_pcSubWindow[MODULE_REQUIRES_MAX_NUM_FRAMES]; VideoSubWindow* m_pcDisplaySubWindow; @@ -93,7 +93,7 @@ public: QList getSubWindowList() { QList arraySubWindows; - for( Int i = 0; i < MAX_NUMBER_FRAMES; i++ ) + for( Int i = 0; i < MODULE_REQUIRES_MAX_NUM_FRAMES; i++ ) if( m_pcSubWindow[i] ) arraySubWindows.append( m_pcSubWindow[i] ); return arraySubWindows; diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index 725054c..fa73c46 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -76,8 +76,6 @@ enum Module_Type FRAME_MEASUREMENT_MODULE, }; -#define MAX_NUMBER_FRAMES 3 - /** Module_NumberOfFrames Enum * \ingroup PlaYUVerLib_Modules * Number of frames requires by a module @@ -88,7 +86,11 @@ enum Module_NumberOfFrames MODULE_REQUIRES_ONE_FRAME = 1, MODULE_REQUIRES_TWO_FRAMES, MODULE_REQUIRES_THREE_FRAMES, - MODULE_REQUIRES_MAX_FRAMES = 255, + MODULE_REQUIRES_FOUR_FRAMES, + MODULE_REQUIRES_FIVE_FRAMES, + MODULE_REQUIRES_SIX_FRAMES, + MODULE_REQUIRES_SEVERAL_FRAMES = 255, + MODULE_REQUIRES_MAX_NUM_FRAMES, }; /** Module_Features Enum diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 98c4108..fc9ba38 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -19,6 +19,7 @@ ADD_MODULE( FilterComponentChromaV "FilterComponent" ) ADD_MODULE( FrameDifference "FrameDifference" ) ADD_MODULE( FrameMask "FrameMask" ) ADD_MODULE( AbsoluteFrameDifference "AbsoluteFrameDifference" ) +ADD_MODULE( InterFrameVariance "InterFrameVariance" ) ADD_MODULE( FrameBinarization "FrameBinarization" ) ADD_MODULE( FrameShift "FrameShift" ) ADD_MODULE( SetChromaHalfScale "SetChromaHalfScale" ) diff --git a/modules/InterFrameVariance.cpp b/modules/InterFrameVariance.cpp new file mode 100644 index 0000000..2abb77c --- /dev/null +++ b/modules/InterFrameVariance.cpp @@ -0,0 +1,111 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file InterFrameVariance.cpp + * \brief Variance across several frames + */ + +#include "InterFrameVariance.h" +#include "lib/LibMemory.h" + +InterFrameVariance::InterFrameVariance() +{ + /* Module Definition */ + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + // See this example for details on the functions prototype + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "InterFrameVariance"; // Name + m_pchModuleTooltip = "Measure the variance across several frames"; + m_uiNumberOfFrames = MODULE_REQUIRES_SEVERAL_FRAMES; // Number of Frames required (This module allows a variable number of inputs) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. + m_pcFrameVariance = NULL; + +} + +Bool InterFrameVariance::create( std::vector apcFrameList ) +{ + m_uiNumberOfFrames = Module_NumberOfFrames( apcFrameList.size() ); + + _BASIC_MODULE_API_2_CHECK_ + + for( UInt i = 1; i < apcFrameList.size(); i++ ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + return false; + + m_pcFrameVariance = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY, 8 ); + getMem2D( &m_pVariance, apcFrameList[0]->getHeight(), apcFrameList[0]->getWidth() ); + + return true; +} + +PlaYUVerFrame* InterFrameVariance::process( std::vector apcFrameList ) +{ + Int numFrames = apcFrameList.size(); + + Pel* pInput[numFrames]; + Pel* pOutputPelYUV = m_pcFrameVariance->getPelBufferYUV()[0][0]; + + for( Int i = 0; i < numFrames; i++ ) + { + pInput[i] = apcFrameList[i]->getPelBufferYUV()[0][0]; + } + + Double maxVariance = 0; + for( UInt y = 0; y < m_pcFrameVariance->getHeight(); y++ ) + for( UInt x = 0; x < m_pcFrameVariance->getWidth(); x++ ) + { + Int sum = 0; + Int v = 0; + m_pVariance[y][x] = 0; + + for( Int i = 0; i < numFrames; i++ ) + { + v = *pInput[i]++; + sum += v; + m_pVariance[y][x] += v * v; + + } + //Final result of the variance for one block + m_pVariance[y][x] -= Double( sum * sum ) / Double( numFrames ); + m_pVariance[y][x] /= Double( numFrames ); + if( m_pVariance[y][x] > maxVariance ) + maxVariance = m_pVariance[y][x]; + } + + for( UInt y = 0; y < m_pcFrameVariance->getHeight(); y++ ) + for( UInt x = 0; x < m_pcFrameVariance->getWidth(); x++ ) + { + *pOutputPelYUV++ = m_pVariance[y][x] * 255 / maxVariance; + } + return m_pcFrameVariance; +} + +Void InterFrameVariance::destroy() +{ + if( m_pVariance ) + freeMem2D( m_pVariance ); + m_pVariance = NULL; + if( m_pcFrameVariance ) + delete m_pcFrameVariance; + m_pcFrameVariance = NULL; +} + diff --git a/modules/InterFrameVariance.h b/modules/InterFrameVariance.h new file mode 100644 index 0000000..2ae8fab --- /dev/null +++ b/modules/InterFrameVariance.h @@ -0,0 +1,51 @@ +/* This file is a part of plaYUVer project + * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Joao Carreira (jfmcarreira@gmail.com) + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * \file InterFrameVariance.h + * \brief Absolute Frame Difference module + */ + +#ifndef __INTERFRAMEVARIANCE_H__ +#define __INTERFRAMEVARIANCE_H__ + +// PlaYUVerLib +#include "lib/PlaYUVerModuleIf.h" + + +class InterFrameVariance: public PlaYUVerModuleIf +{ + REGISTER_CLASS_FACTORY( InterFrameVariance ) + +private: + PlaYUVerFrame* m_pcFrameVariance; + Double** m_pVariance; +public: + InterFrameVariance(); + virtual ~InterFrameVariance() + { + } + Bool create( std::vector apcFrameList ); + PlaYUVerFrame* process( std::vector apcFrameList ); + Void destroy(); + +}; + +#endif // __INTERFRAMEVARIANCE_H__ + From 9091719dc9f379d36292e46f5e777ec4a5860654 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 6 Jan 2017 16:18:14 +0000 Subject: [PATCH 111/127] Catch exception in PlaYUVerTools --- tools/PlaYUVerTools.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index a1d8a4e..2741819 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -281,9 +281,13 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) pcModFrame = applyFrameModule(); } PlaYUVerStream* pcModStream = new PlaYUVerStream; - if( !pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), - pcModFrame->getEndianness(), 1, false ) ) + try { + pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), pcModFrame->getEndianness(), 1, false ); + } + catch( const char *msg ) + { + log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", outputFileNames[0].c_str(), msg ); delete pcModStream; pcModStream = NULL; return 2; From c8d7fb1c43c7c0d07d92f798f111cf4ca0fff6d9 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 10 Jan 2017 17:15:23 +0000 Subject: [PATCH 112/127] Fix guessing endian --- app/VideoSubWindow.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 170a964..2a0bf15 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -538,16 +538,13 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, #endif // Guess Endianness - if( rEndianness == -1 ) + if( FilenameShort.contains( QStringLiteral( "be" ), Qt::CaseInsensitive ) ) { - if( FilenameShort.contains( QStringLiteral( "be" ), Qt::CaseInsensitive ) ) - { - rEndianness = PLAYUVER_BIG_ENDIAN; - } - if( FilenameShort.contains( QStringLiteral( "le" ), Qt::CaseInsensitive ) ) - { - rEndianness = PLAYUVER_LITTLE_ENDIAN; - } + rEndianness = PLAYUVER_BIG_ENDIAN; + } + if( FilenameShort.contains( QStringLiteral( "le" ), Qt::CaseInsensitive ) ) + { + rEndianness = PLAYUVER_LITTLE_ENDIAN; } if( rWidth > 0 && rHeight > 0 && rInputFormat >= 0 ) From a69c32bfbf7c08a7eae607b8866c1d5d5c60e5c4 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 11 Jan 2017 01:37:26 +0000 Subject: [PATCH 113/127] Transfer endianess from frame to stream only --- app/ModulesHandle.cpp | 5 ++-- app/VideoHandle.cpp | 13 ++++++++++- lib/PlaYUVerFrame.cpp | 39 ++++++++++++-------------------- lib/PlaYUVerFrame.h | 9 ++++---- lib/PlaYUVerStream.cpp | 9 +++++--- lib/PlaYUVerStream.h | 1 + lib/StreamHandlerLibav.cpp | 2 +- lib/StreamHandlerPortableMap.cpp | 4 ++-- lib/StreamHandlerRaw.cpp | 4 ++-- modules/FilterComponent.cpp | 13 ++++------- modules/FilterComponent.h | 2 +- tools/PlaYUVerTools.cpp | 2 +- 12 files changed, 52 insertions(+), 51 deletions(-) diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index d3aaf63..c6798b7 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -501,7 +501,7 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) if( !pcCurrModuleIf->m_pcModuleStream ) { UInt Width = 0, Height = 0, FrameRate = 30; - Int BitsPixel, Endianness, InputFormat = -1; + Int BitsPixel, InputFormat = -1; QString supported = tr( "Supported Files (" ); QStringList formatsList; @@ -531,11 +531,10 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight(); InputFormat = pcCurrModuleIf->m_pcProcessedFrame->getPelFormat(); BitsPixel = pcCurrModuleIf->m_pcProcessedFrame->getBitsPel(); - Endianness = pcCurrModuleIf->m_pcProcessedFrame->getEndianness(); FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate(); pcCurrModuleIf->m_pcModuleStream = new PlaYUVerStream; - if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, Endianness, FrameRate, false ) ) + if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, PLAYUVER_LITTLE_ENDIAN, FrameRate, false ) ) { delete pcCurrModuleIf->m_pcModuleStream; pcCurrModuleIf->m_pcModuleStream = NULL; diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index 9b9738e..098e5db 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -319,8 +319,19 @@ Void VideoHandle::update() if( pcFrame ) { resolution.append( QString( " %1 bpp" ).arg( pcFrame->getBitsPel() ) ); - m_pcResolutionLabel->setText( resolution ); } + if( pcStream && pcFrame->getBitsPel() > 8 ) + { + if( pcStream->getEndianess() == PLAYUVER_BIG_ENDIAN ) + { + resolution.append( QStringLiteral( " (BE)" ) ); + } + else + { + resolution.append( QStringLiteral( " (LE)" ) ); + } + } + m_pcResolutionLabel->setText( resolution ); m_pcFramePropertiesSideBar->setFrame( pcFrame ); diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 9d0a6a6..dfa487c 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -135,7 +135,7 @@ struct PlaYUVerFramePrivate Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) Int m_iNumberChannels; //!< Number of channels UInt m_uiBitsPel; //!< Bits per pixel/channel - Int m_iEndianness; //!< Endiannes of bytes +// Int m_iEndianness; //!< Endiannes of bytes UInt m_uiHalfPelValue; //!< Bits per pixel/channel Pel*** m_pppcInputPel; @@ -165,7 +165,7 @@ struct PlaYUVerFramePrivate * @param pel_format pixel format index (always use PixelFormats enum) * */ - Void init( UInt width, UInt height, Int pel_format, Int bitsPixel, Int endianness ) + Void init( UInt width, UInt height, Int pel_format, Int bitsPixel ) { m_bInit = false; m_pppcInputPel = NULL; @@ -175,11 +175,6 @@ struct PlaYUVerFramePrivate m_iPixelFormat = pel_format; m_iNumberChannels = 3; m_uiBitsPel = bitsPixel > 8 ? bitsPixel : 8; - m_iEndianness = endianness; - if( m_uiBitsPel > 8 && m_iEndianness == -1 ) - { - throw PlaYUVerFailure( "PlaYUVerFrame", "Invalid endianness type for Bits per Pixel greater than 8" ); - } m_uiHalfPelValue = 1 << ( m_uiBitsPel - 1 ); if( m_uiWidth == 0 || m_uiHeight == 0 || m_iPixelFormat == -1 || bitsPixel > 16 ) @@ -220,16 +215,16 @@ struct PlaYUVerFramePrivate * \brief Constructors */ -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel, Int endianness ) : +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) : d( new PlaYUVerFramePrivate ) { - d->init( width, height, pelFormat, bitsPixel, endianness ); + d->init( width, height, pelFormat, bitsPixel ); } PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other ) : d( new PlaYUVerFramePrivate ) { - d->init( other.getWidth(), other.getHeight(), other.getPelFormat(), other.getBitsPel(), other.getEndianness() ); + d->init( other.getWidth(), other.getHeight(), other.getPelFormat(), other.getBitsPel() ); copyFrom( &other ); } @@ -239,7 +234,7 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other ) : { if( other ) { - d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + d->init( other->getWidth(), other->getHeight(), other->getPelFormat(), other->getBitsPel() ); copyFrom( other ); } } @@ -265,7 +260,7 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt w height++; } - d->init( width, height, other.getPelFormat(), other.getBitsPel(), other.getEndianness() ); + d->init( width, height, other.getPelFormat(), other.getBitsPel() ); copyFrom( other, x, y ); } @@ -293,7 +288,7 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other, UInt posX, UInt posY, areaHeight++; } - d->init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel(), other->getEndianness() ); + d->init( areaWidth, areaHeight, other->getPelFormat(), other->getBitsPel() ); copyFrom( other, posX, posY ); } @@ -410,10 +405,6 @@ UInt PlaYUVerFrame::getBitsPel() const { return d->m_uiBitsPel; } -Int PlaYUVerFrame::getEndianness() const -{ - return d->m_iEndianness; -} UInt64 PlaYUVerFrame::getBytesPerFrame() { @@ -556,15 +547,15 @@ Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other, UInt x, UInt y ) copyFrom( *other, x, y ); } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, UInt64 uiBuffSize ) +Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness, UInt64 uiBuffSize ) { if( uiBuffSize != getBytesPerFrame() ) return; - frameFromBuffer( Buff ); + frameFromBuffer( Buff, iEndianness ); } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) +Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness ) { Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; @@ -578,7 +569,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) Int b; Int maxval = pow(2, d->m_uiBitsPel) - 1; - if( d->m_iEndianness == 0 ) + if( iEndianness == 0 ) { startByte = bytesPixel - 1; endByte = -1; @@ -622,7 +613,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff ) d->m_bHasHistogram = false; } -Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) +Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer, Int iEndianness ) { UInt bytesPixel = ( d->m_uiBitsPel - 1 ) / 8 + 1; Byte* ppBuff[MAX_NUMBER_PLANES]; @@ -635,7 +626,7 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer ) Int incByte = 1; Int b; - if( d->m_iEndianness == 0 ) + if( iEndianness == 0 ) { startByte = bytesPixel - 1; endByte = -1; @@ -1225,7 +1216,7 @@ Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) return false; } } - d->init( cvMat.cols, cvMat.rows, d->m_iPixelFormat, 8, -1 ); + d->init( cvMat.cols, cvMat.rows, d->m_iPixelFormat, 8 ); } d->m_bHasRGBPel = false; diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index 654d3ac..ced24be 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -101,7 +101,7 @@ public: * * @note this function might misbehave if the pixel format enum is not correct */ - PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel = 8, Int endianness = -1 ); + PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel = 8 ); /** * Copy contructor @@ -178,7 +178,6 @@ public: UInt getChromaSize() const; UInt getBitsPel() const; - Int getEndianness() const; /** * Get number of bytes per frame of an existing frame @@ -213,9 +212,9 @@ public: Void copyFrom( const PlaYUVerFrame&, UInt, UInt ); Void copyFrom( const PlaYUVerFrame*, UInt, UInt ); - Void frameFromBuffer( Byte*, UInt64 ); - Void frameFromBuffer( Byte* ); - Void frameToBuffer( Byte* ); + Void frameFromBuffer( Byte*, Int, UInt64 ); + Void frameFromBuffer( Byte*, Int ); + Void frameToBuffer( Byte*, Int ); Void fillRGBBuffer(); diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 7b71812..ff26c03 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -240,8 +240,7 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel, - m_pcHandler->m_iEndianness ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); } catch( PlaYUVerFailure& e ) { @@ -349,6 +348,10 @@ UInt PlaYUVerStream::getHeight() const { return m_pcHandler->m_uiHeight; } +Int PlaYUVerStream::getEndianess() const +{ + return m_pcHandler->m_iEndianness; +} Double PlaYUVerStream::getFrameRate() { return m_pcHandler->m_dFrameRate; @@ -498,7 +501,7 @@ Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame *saveFrame { PlaYUVerStream auxSaveStream; if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), - saveFrame->getEndianness(), 1, false ) ) + PLAYUVER_LITTLE_ENDIAN, 1, false ) ) { return false; } diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 32fc8c5..2be47e0 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -105,6 +105,7 @@ public: UInt getFrameNum(); UInt getWidth() const; UInt getHeight() const; + Int getEndianess() const; Int getCurrFrameNum(); Double getFrameRate(); Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ); diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index f0ff243..8afb14f 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -358,7 +358,7 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) if( orig_pkt.size ) av_free_packet( &orig_pkt ); - pcFrame->frameFromBuffer( m_pStreamBuffer ); + pcFrame->frameFromBuffer( m_pStreamBuffer, m_iEndianness ); return true; } diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index df8460d..2e47cf8 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -120,7 +120,7 @@ Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; - pcFrame->frameFromBuffer( m_pStreamBuffer ); + pcFrame->frameFromBuffer( m_pStreamBuffer, PLAYUVER_BIG_ENDIAN ); return true; } @@ -132,7 +132,7 @@ Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) { fprintf( m_pFile, "%d\n", m_iMaxValue ); } - pcFrame->frameToBuffer( m_pStreamBuffer ); + pcFrame->frameToBuffer( m_pStreamBuffer, PLAYUVER_BIG_ENDIAN ); UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 02f5d87..1128840 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -81,13 +81,13 @@ Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; - pcFrame->frameFromBuffer( m_pStreamBuffer ); + pcFrame->frameFromBuffer( m_pStreamBuffer, m_iEndianness ); return true; } Bool StreamHandlerRaw::write( PlaYUVerFrame* pcFrame ) { - pcFrame->frameToBuffer( m_pStreamBuffer ); + pcFrame->frameToBuffer( m_pStreamBuffer, m_iEndianness ); UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index fb6a586..c0378f5 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -31,10 +31,10 @@ FilterComponentModule::FilterComponentModule() m_pcFilteredFrame = NULL; } -Bool FilterComponentModule::createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel, UInt uiEndianness ) +Bool FilterComponentModule::createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel ) { m_pcFilteredFrame = NULL; - m_pcFilteredFrame = new PlaYUVerFrame( uiWidth, uiHeight, PlaYUVerFrame::GRAY, bitsPixel, uiEndianness ); + m_pcFilteredFrame = new PlaYUVerFrame( uiWidth, uiHeight, PlaYUVerFrame::GRAY, bitsPixel ); return true; } @@ -69,8 +69,7 @@ FilterComponentLuma::FilterComponentLuma() Bool FilterComponentLuma::create( std::vector apcFrameList ) { - return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getBitsPel(), - apcFrameList[0]->getEndianness() ); + return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getBitsPel() ); } PlaYUVerFrame* FilterComponentLuma::process( std::vector apcFrameList ) @@ -94,8 +93,7 @@ Bool FilterComponentChromaU::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel(), - apcFrameList[0]->getEndianness() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); } return false; } @@ -121,8 +119,7 @@ Bool FilterComponentChromaV::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel(), - apcFrameList[0]->getEndianness() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); } return false; } diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index cfefc87..4744763 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -42,7 +42,7 @@ private: PlaYUVerFrame* process( std::vector apcFrameList ) = 0; Void destroy(); - Bool createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel, UInt uiEndianness ); + Bool createFilter( UInt uiWidth, UInt uiHeight, UInt bitsPixel ); PlaYUVerFrame* filterComponent( PlaYUVerFrame* InputFrame, Int Component ); }; diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 2741819..c0e3e02 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -283,7 +283,7 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) PlaYUVerStream* pcModStream = new PlaYUVerStream; try { - pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), pcModFrame->getEndianness(), 1, false ); + pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ); } catch( const char *msg ) { From 8a60bb27662b800a001e550f3fc507ca95505b6b Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Sat, 28 Jan 2017 19:43:48 +0000 Subject: [PATCH 114/127] Change copyright and format the code using clang-format --- .clang-format | 97 + app/AboutDialog.cpp | 52 +- app/AboutDialog.h | 12 +- app/ConfigureFormatDialog.cpp | 43 +- app/ConfigureFormatDialog.h | 40 +- app/DialogSubWindowSelector.cpp | 29 +- app/DialogSubWindowSelector.h | 26 +- app/FramePropertiesDock.cpp | 228 +- app/FramePropertiesDock.h | 61 +- app/GridManager.cpp | 126 +- app/GridManager.h | 16 +- app/HistogramWidget.cpp | 614 +- app/HistogramWidget.h | 51 +- app/ModuleHandleDock.cpp | 12 +- app/ModuleHandleDock.h | 14 +- app/ModulesHandle.cpp | 97 +- app/ModulesHandle.h | 30 +- app/ModulesHandleOptDialog.cpp | 19 +- app/ModulesHandleOptDialog.h | 17 +- app/PlaYUVerApp.cpp | 165 +- app/PlaYUVerApp.h | 39 +- app/PlaYUVerAppAdaptor.cpp | 13 +- app/PlaYUVerAppAdaptor.h | 36 +- app/PlaYUVerAppDefs.h | 6 +- app/PlaYUVerAppModuleIf.cpp | 62 +- app/PlaYUVerAppModuleIf.h | 39 +- app/PlaYUVerMdiSubWindow.cpp | 8 +- app/PlaYUVerMdiSubWindow.h | 19 +- app/PlaYUVerSubWindowHandle.cpp | 106 +- app/PlaYUVerSubWindowHandle.h | 33 +- app/PlotSubWindow.cpp | 47 +- app/PlotSubWindow.h | 33 +- app/ProgressBar.cpp | 13 +- app/ProgressBar.h | 14 +- app/QualityHandle.cpp | 60 +- app/QualityHandle.h | 18 +- app/QualityMeasurementSidebar.cpp | 44 +- app/QualityMeasurementSidebar.h | 31 +- app/SeekStreamDialog.cpp | 9 +- app/SeekStreamDialog.h | 15 +- app/SubWindowAbstract.cpp | 21 +- app/SubWindowAbstract.h | 45 +- app/VideoHandle.cpp | 82 +- app/VideoHandle.h | 25 +- app/VideoSubWindow.cpp | 161 +- app/VideoSubWindow.h | 117 +- app/ViewArea.cpp | 233 +- app/ViewArea.h | 106 +- app/WidgetFrameNumber.cpp | 8 +- app/WidgetFrameNumber.h | 16 +- app/external/qcustomplot.cpp | 15549 ++++++++-------- app/external/qcustomplot.h | 4048 ++-- app/main.cpp | 40 +- config.h.in | 2 +- .../AbsoluteFrameDifferenceExample.cpp | 34 +- .../modules/AbsoluteFrameDifferenceExample.h | 18 +- examples/modules/FrameBinarization_APIv1.cpp | 7 +- examples/modules/FrameBinarization_APIv1.h | 19 +- lib/LibMemory.h | 74 +- lib/PlaYUVerDefs.h | 27 +- lib/PlaYUVerFrame.cpp | 272 +- lib/PlaYUVerFrame.h | 14 +- lib/PlaYUVerFramePixelFormats.cpp | 71 +- lib/PlaYUVerFramePixelFormats.h | 9 +- lib/PlaYUVerLib.h | 4 +- lib/PlaYUVerModuleIf.h | 70 +- lib/PlaYUVerOptions.cpp | 159 +- lib/PlaYUVerOptions.h | 67 +- lib/PlaYUVerPixel.cpp | 8 +- lib/PlaYUVerPixel.h | 23 +- lib/PlaYUVerStream.cpp | 107 +- lib/PlaYUVerStream.h | 74 +- lib/PlaYUVerStreamHandlerIf.h | 40 +- lib/StreamHandlerLibav.cpp | 143 +- lib/StreamHandlerLibav.h | 35 +- lib/StreamHandlerOpenCV.cpp | 5 +- lib/StreamHandlerOpenCV.h | 19 +- lib/StreamHandlerPortableMap.cpp | 7 +- lib/StreamHandlerPortableMap.h | 21 +- lib/StreamHandlerRaw.cpp | 8 +- lib/StreamHandlerRaw.h | 23 +- modules/AbsoluteFrameDifference.cpp | 33 +- modules/AbsoluteFrameDifference.h | 19 +- modules/DisparityStereoBM.cpp | 15 +- modules/DisparityStereoBM.h | 23 +- modules/DisparityStereoSGBM.cpp | 18 +- modules/DisparityStereoSGBM.h | 23 +- modules/DisparityStereoVar.cpp | 17 +- modules/DisparityStereoVar.h | 20 +- modules/EightBitsSampling.cpp | 7 +- modules/EightBitsSampling.h | 20 +- modules/FilterComponent.cpp | 18 +- modules/FilterComponent.h | 47 +- modules/FrameBinarization.cpp | 8 +- modules/FrameBinarization.h | 20 +- modules/FrameCrop.cpp | 14 +- modules/FrameCrop.h | 20 +- modules/FrameDifference.cpp | 14 +- modules/FrameDifference.h | 19 +- modules/FrameMask.cpp | 32 +- modules/FrameMask.h | 19 +- modules/FrameShift.cpp | 16 +- modules/FrameShift.h | 20 +- modules/InterFrameVariance.cpp | 33 +- modules/InterFrameVariance.h | 18 +- modules/LumaAverage.cpp | 21 +- modules/LumaAverage.h | 19 +- modules/MeasureOpticalFlowDualTVL1.cpp | 18 +- modules/MeasureOpticalFlowDualTVL1.h | 19 +- modules/OpticalFlow.cpp | 25 +- modules/OpticalFlow.h | 52 +- modules/PlaYUVerModuleFactory.cpp | 13 +- modules/PlaYUVerModuleFactory.h | 31 +- modules/SetChromaHalfScale.cpp | 7 +- modules/SetChromaHalfScale.h | 19 +- modules/WeightedPSNR.cpp | 9 +- modules/WeightedPSNR.h | 18 +- tools/PlaYUVerTools.cpp | 63 +- tools/PlaYUVerTools.h | 15 +- tools/PlaYUVerToolsCmdParser.cpp | 32 +- tools/PlaYUVerToolsCmdParser.h | 25 +- tools/main.cpp | 5 +- 122 files changed, 12950 insertions(+), 12139 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..d8f4194 --- /dev/null +++ b/.clang-format @@ -0,0 +1,97 @@ +--- +Language: Cpp +# BasedOnStyle: Chromium +ColumnLimit: 80 +ColumnLimit: 120 +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: true +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: false +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false +BreakBeforeBinaryOperators: None +#BreakBeforeBraces: Attach +BreakBeforeBraces: Allman +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +CommentPragmas: '^ IWYU pragma:' +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeCategories: + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: false +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +ReflowComments: true +SortIncludes: false +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: true +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 8 +UseTab: Never +... + diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index cd67614..db81251 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,20 +34,18 @@ #define TAB_FROM_SPACES "   " -AboutDialog::AboutDialog( QWidget *parent ) : - QDialog( parent ) +AboutDialog::AboutDialog( QWidget* parent ) : QDialog( parent ) { QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ).scaled( QSize( 500, 350 ), Qt::KeepAspectRatio ); - QLabel *pixmapLabel = new QLabel; + QLabel* pixmapLabel = new QLabel; pixmapLabel->setPixmap( logo ); - QLabel *label = new QLabel( QString( "

%1 Version %2

%3

" ) - .arg( QApplication::applicationName() ) - .arg( QApplication::applicationVersion() ) - .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) ); + QLabel* label = new QLabel( QString( "

%1 Version %2

%3

" ) + .arg( QApplication::applicationName() ) + .arg( QApplication::applicationVersion() ) + .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) ); label->setWordWrap( true ); - QString featuresList = QStringLiteral( "

Features:

    " ); #ifdef USE_QTDBUS @@ -61,39 +59,37 @@ AboutDialog::AboutDialog( QWidget *parent ) : #endif featuresList.append( QStringLiteral( "

" ) ); - QLabel *labelFeatures = new QLabel( featuresList ); + QLabel* labelFeatures = new QLabel( featuresList ); + QLabel* labelCopyright = new QLabel( QStringLiteral( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ); - QLabel *labelCopyright = new QLabel( QStringLiteral( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ); - - QWidget *topWidget = new QWidget; - QVBoxLayout *topLayout = new QVBoxLayout; + QWidget* topWidget = new QWidget; + QVBoxLayout* topLayout = new QVBoxLayout; topLayout->addWidget( pixmapLabel ); topLayout->addWidget( label ); topLayout->addWidget( labelFeatures ); topLayout->addWidget( labelCopyright ); topWidget->setLayout( topLayout ); -// QTextEdit *textEdit = new QTextEdit(tr("

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 2 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.

")); -// textEdit->setReadOnly(true); - QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok ); + // QTextEdit *textEdit = new QTextEdit(tr("

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 2 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.

")); + // textEdit->setReadOnly(true); + QDialogButtonBox* buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok ); connect( buttonBox, SIGNAL( accepted() ), this, SLOT( accept() ) ); - QVBoxLayout *mainLayout = new QVBoxLayout( this ); + QVBoxLayout* mainLayout = new QVBoxLayout( this ); mainLayout->addWidget( topWidget ); - //mainLayout->addWidget(textEdit); + // mainLayout->addWidget(textEdit); mainLayout->addWidget( buttonBox ); mainLayout->setSpacing( 10 ); buttonBox->setFocus(); setWindowTitle( tr( "About %1" ).arg( QApplication::applicationName() ) ); } - diff --git a/app/AboutDialog.h b/app/AboutDialog.h index f2e1617..317ea3c 100644 --- a/app/AboutDialog.h +++ b/app/AboutDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,12 +28,12 @@ #include -class AboutDialog: public QDialog +class AboutDialog : public QDialog { -Q_OBJECT + Q_OBJECT -public: - AboutDialog( QWidget *parent = 0 ); + public: + AboutDialog( QWidget* parent = 0 ); }; -#endif // __ABOUTDIALOG_H__ +#endif // __ABOUTDIALOG_H__ diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index f24955f..52831a3 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -48,9 +48,7 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStdResolutionVector& ar for( Int i = 0; i < array.size(); i++ ) { d = array.at( i ); - out << QString::fromStdString( d.shortName ) - << d.uiWidth - << d.uiHeight; + out << QString::fromStdString( d.shortName ) << d.uiWidth << d.uiHeight; } return out; } @@ -72,13 +70,11 @@ QDataStream& operator>>( QDataStream& in, PlaYUVerStdResolutionVector& array ) return in; } -class AddCustomFormat: public QDialog +class AddCustomFormat : public QDialog { -public: - AddCustomFormat( QWidget *parent = NULL ) : - QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ) + public: + AddCustomFormat( QWidget* parent = NULL ) : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ) { - setWindowModality( Qt::ApplicationModal ); setWindowTitle( "Add custom resolution" ); @@ -134,14 +130,13 @@ public: return stdResolution; } -private: + private: QLineEdit* m_lineEdtName; QSpinBox* m_spinWidth; QSpinBox* m_spinHeight; }; -ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : - QDialog( parent ) +ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( parent ) { QString Name; UInt uiWidth, uiHeight; @@ -369,11 +364,12 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : MainLayout->addItem( new QSpacerItem( 10, 5, QSizePolicy::Minimum, QSizePolicy::Expanding ) ); MainLayout->addWidget( dialogButtonOkCancel ); - connect( m_comboBoxStandardResolution, SIGNAL( currentIndexChanged(int) ), this, SLOT( slotStandardResolutionSelected(int) ) ); - connect( m_spinBoxWidth, SIGNAL( valueChanged(int) ), this, SLOT( slotResolutionChange() ) ); - connect( m_spinBoxheight, SIGNAL( valueChanged(int) ), this, SLOT( slotResolutionChange() ) ); - connect( m_comboBoxColorSpace, SIGNAL( currentIndexChanged(int) ), this, SLOT( slotColorSpaceChange(int) ) ); - connect( m_spinBoxBits, SIGNAL( valueChanged(int) ), this, SLOT( slotBitsChange(int) ) ); + connect( m_comboBoxStandardResolution, SIGNAL( currentIndexChanged( int ) ), this, + SLOT( slotStandardResolutionSelected( int ) ) ); + connect( m_spinBoxWidth, SIGNAL( valueChanged( int ) ), this, SLOT( slotResolutionChange() ) ); + connect( m_spinBoxheight, SIGNAL( valueChanged( int ) ), this, SLOT( slotResolutionChange() ) ); + connect( m_comboBoxColorSpace, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotColorSpaceChange( int ) ) ); + connect( m_spinBoxBits, SIGNAL( valueChanged( int ) ), this, SLOT( slotBitsChange( int ) ) ); connect( dialogButtonOkCancel, SIGNAL( accepted() ), this, SLOT( accept() ) ); connect( dialogButtonOkCancel, SIGNAL( rejected() ), this, SLOT( reject() ) ); @@ -381,14 +377,18 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget *parent ) : m_comboBoxColorSpace->setCurrentIndex( 0 ); setFixedSize( MainLayout->sizeHint() ); - } -Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, - UInt& rFrameRate ) +Int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, + UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBits, + Int& rEndianess, + UInt& rFrameRate ) { // Set default values - //setWindowTitle( "Configure resolution for " + Filename ); + // setWindowTitle( "Configure resolution for " + Filename ); m_labelFilename->setText( QFileInfo( Filename ).fileName() ); m_spinBoxWidth->setValue( rWidth ); m_spinBoxheight->setValue( rHeight ); @@ -539,7 +539,6 @@ Void ConfigureFormatDialog::readSettings() QSettings appSettings; QVariant value = appSettings.value( "ConfigureFormatDialog/CustomFormats" ); aRCustomFileFormats = value.value(); - } Void ConfigureFormatDialog::writeSettings() diff --git a/app/ConfigureFormatDialog.h b/app/ConfigureFormatDialog.h index 8e5daec..d45abd5 100644 --- a/app/ConfigureFormatDialog.h +++ b/app/ConfigureFormatDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -45,44 +45,48 @@ QDataStream& operator>>( QDataStream& in, PlaYUVerStdResolutionVector& array ); /** * */ -class ConfigureFormatDialog: public QDialog +class ConfigureFormatDialog : public QDialog { -Q_OBJECT + Q_OBJECT -public: - - ConfigureFormatDialog( QWidget *parent = 0 ); - Int runConfigureFormatDialog( const QString& Filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBits, Int& rEndianess, UInt& rFrameRate ); + public: + ConfigureFormatDialog( QWidget* parent = 0 ); + Int runConfigureFormatDialog( const QString& Filename, + UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBits, + Int& rEndianess, + UInt& rFrameRate ); Void readSettings(); Void writeSettings(); -private Q_SLOTS: + private Q_SLOTS: void slotStandardResolutionSelected( int ); void slotResolutionChange(); void slotColorSpaceChange( int ); void slotBitsChange( int ); -private: + private: QStringList standardResolutionNames; QVector standardResolutionSizes; PlaYUVerStdResolutionVector aRCustomFileFormats; QLabel* m_labelFilename; - QComboBox *m_comboBoxStandardResolution; - QSpinBox *m_spinBoxWidth; - QSpinBox *m_spinBoxheight; - QComboBox *m_comboBoxColorSpace; - QComboBox *m_comboBoxPixelFormat; - QSpinBox *m_spinBoxBits; + QComboBox* m_comboBoxStandardResolution; + QSpinBox* m_spinBoxWidth; + QSpinBox* m_spinBoxheight; + QComboBox* m_comboBoxColorSpace; + QComboBox* m_comboBoxPixelFormat; + QSpinBox* m_spinBoxBits; QWidget* m_widgetEndianness; QComboBox* m_comboBoxEndianness; QHBoxLayout* framerateFormatLayout; - QSpinBox *m_spinBoxFrameRate; - + QSpinBox* m_spinBoxFrameRate; }; Q_DECLARE_METATYPE( PlaYUVerStdResolution ); Q_DECLARE_METATYPE( PlaYUVerStdResolutionVector ); -#endif // __CONFIGUREFORMATDIALOG_H__ +#endif // __CONFIGUREFORMATDIALOG_H__ diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index 2d7d0dc..9c51ac3 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,15 +28,17 @@ #include "DialogSubWindowSelector.h" #include "VideoSubWindow.h" -DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWindowHandle *windowManager, UInt uiCategory, Int minWindowsSelected, - Int maxWindowsSelected ) : - QDialog( parent ), - m_uiCategory( uiCategory ), - m_iMinSelectedWindows( minWindowsSelected ), - m_iMaxSlectedWindows( maxWindowsSelected ), - m_pcMainWindowManager( windowManager ) +DialogSubWindowSelector::DialogSubWindowSelector( QWidget* parent, + PlaYUVerSubWindowHandle* windowManager, + UInt uiCategory, + Int minWindowsSelected, + Int maxWindowsSelected ) + : QDialog( parent ), + m_uiCategory( uiCategory ), + m_iMinSelectedWindows( minWindowsSelected ), + m_iMaxSlectedWindows( maxWindowsSelected ), + m_pcMainWindowManager( windowManager ) { - QSize windowSize( 350, 80 ); resize( windowSize ); setWindowTitle( "Select desired Sub-Windows" ); @@ -79,9 +81,9 @@ DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWi connect( m_pushButtonRemoveAll, SIGNAL( clicked() ), this, SLOT( removeAllSubWindow() ) ); m_mapperWindowsList = new QSignalMapper( this ); - connect( m_mapperWindowsList, SIGNAL( mapped(int) ), this, SLOT( toggleSubWindow(int) ) ); + connect( m_mapperWindowsList, SIGNAL( mapped( int ) ), this, SLOT( toggleSubWindow( int ) ) ); - SubWindowAbstract *subWindow; + SubWindowAbstract* subWindow; QString currSubWindowName; QCheckBox* windowCheckBox; m_apcSubWindowList = m_pcMainWindowManager->findSubWindow( m_uiCategory ); @@ -90,7 +92,7 @@ DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWi subWindow = m_apcSubWindowList.at( i ); currSubWindowName = subWindow->getWindowName(); windowCheckBox = new QCheckBox( currSubWindowName, this ); - connect( windowCheckBox, SIGNAL( stateChanged(int) ), m_mapperWindowsList, SLOT( map() ) ); + connect( windowCheckBox, SIGNAL( stateChanged( int ) ), m_mapperWindowsList, SLOT( map() ) ); m_mapperWindowsList->setMapping( windowCheckBox, i ); m_apcWindowsListCheckBox.append( windowCheckBox ); } @@ -98,7 +100,6 @@ DialogSubWindowSelector::DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWi update(); setFixedSize( mainLayout->sizeHint() ); - } Void DialogSubWindowSelector::updateSubWindowList() @@ -137,7 +138,7 @@ Void DialogSubWindowSelector::updateSubWindowList() } } -Void DialogSubWindowSelector::selectSubWindow( SubWindowAbstract * subWindow ) +Void DialogSubWindowSelector::selectSubWindow( SubWindowAbstract* subWindow ) { Int iIdx = m_apcSubWindowList.indexOf( subWindow ); if( iIdx >= 0 ) diff --git a/app/DialogSubWindowSelector.h b/app/DialogSubWindowSelector.h index 9857cba..36df182 100644 --- a/app/DialogSubWindowSelector.h +++ b/app/DialogSubWindowSelector.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -48,19 +48,20 @@ class SubWindowAbstract; * Class to define the dialog box to select sub windows * This class enable the selection of several group of windows */ -class DialogSubWindowSelector: public QDialog +class DialogSubWindowSelector : public QDialog { -Q_OBJECT + Q_OBJECT -public: - DialogSubWindowSelector( QWidget *parent, PlaYUVerSubWindowHandle *windowManager, UInt uiCategory, Int minWindowsSelected = 1, Int maxWindowsSelected = -1 ); + public: + DialogSubWindowSelector( QWidget* parent, + PlaYUVerSubWindowHandle* windowManager, + UInt uiCategory, + Int minWindowsSelected = 1, + Int maxWindowsSelected = -1 ); Void selectSubWindow( SubWindowAbstract* subWindow ); - QList getSelectedWindows() - { - return m_apcSelectedSubWindowList; - } -private: + QList getSelectedWindows() { return m_apcSelectedSubWindowList; } + private: UInt m_uiCategory; Int m_iMinSelectedWindows; Int m_iMaxSlectedWindows; @@ -81,11 +82,10 @@ private: Void updateSubWindowList(); Void update(); -private Q_SLOTS: + private Q_SLOTS: void toggleSubWindow( int ); void addAllSubWindow(); void removeAllSubWindow(); - }; -#endif // __DIALOGSUBWINDOWSELECTOR_H__ +#endif // __DIALOGSUBWINDOWSELECTOR_H__ diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index ed44fbd..17f281e 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -27,9 +27,8 @@ #include #include "FramePropertiesDock.h" -FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ) : - QWidget( parent ), - m_pbIsPlaying( pbMainPlaySwitch ) +FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ) + : QWidget( parent ), m_pbIsPlaying( pbMainPlaySwitch ) { // -------------- Variables definition -------------- m_pcFrame = NULL; @@ -38,29 +37,31 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc // Histogram area ----------------------------------------------------- - QLabel *channelLabel = new QLabel( tr( "Channel:" ) ); + QLabel* channelLabel = new QLabel( tr( "Channel:" ) ); channelLabel->setAlignment( Qt::AlignVCenter | Qt::AlignRight ); channelCB = new QComboBox; channelCB->addItem( tr( "Luminance" ) ); channelCB->setItemIcon( 0, QIcon( ":/images/channel-luma.png" ) ); - channelCB->setWhatsThis( tr( "

Select here the histogram channel to display:

" - "Luminance: Display luminance (perceived brightness).

" - "Red: Display the red image channel.

" - "Green: Display the green image channel.

" - "Blue: Display the blue image channel.

" - "Alpha: Display the alpha image channel. " - "This channel corresponds to the transparency value and " - "is supported by some image formats such as PNG or TIFF.

" - "Colors: Display all color channel values at " - "the same time." ) ); + channelCB->setWhatsThis( + tr( "

Select here the histogram channel to display:

" + "Luminance: Display luminance (perceived brightness).

" + "Red: Display the red image channel.

" + "Green: Display the green image channel.

" + "Blue: Display the blue image channel.

" + "Alpha: Display the alpha image channel. " + "This channel corresponds to the transparency value and " + "is supported by some image formats such as PNG or TIFF.

" + "Colors: Display all color channel values at " + "the same time." ) ); - QString scaleWhatsThis( tr( "

Select here the histogram scale.

" - "If the image's maximal values are small, you can use the " - "linear scale.

Logarithmic scale can be used when the maximal" - " values are big; if it is used, all values (small and large) " - "will be visible on the graph." ) ); + QString scaleWhatsThis( + tr( "

Select here the histogram scale.

" + "If the image's maximal values are small, you can use the " + "linear scale.

Logarithmic scale can be used when the maximal" + " values are big; if it is used, all values (small and large) " + "will be visible on the graph." ) ); linHistoButton = new QPushButton; linHistoButton->setToolTip( tr( "Linear" ) ); @@ -81,7 +82,7 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc scaleButtonGroup->addButton( linHistoButton, HistogramWidget::LinScaleHistogram ); scaleButtonGroup->addButton( logHistoButton, HistogramWidget::LogScaleHistogram ); - QHBoxLayout *scaleLayout = new QHBoxLayout; + QHBoxLayout* scaleLayout = new QHBoxLayout; scaleLayout->addWidget( linHistoButton ); scaleLayout->addWidget( logHistoButton ); @@ -92,10 +93,11 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc colorsCB->hide(); colorsLabel->hide(); - QString regionWhatsThis( tr( "

Select here from which region the histogram will be computed:" - "

Full Image: Compute histogram using the full image." - "

Selection: Compute histogram using the current image " - "selection." ) ); + QString regionWhatsThis( + tr( "

Select here from which region the histogram will be computed:" + "

Full Image: Compute histogram using the full image." + "

Selection: Compute histogram using the current image " + "selection." ) ); fullImageButton = new QPushButton; fullImageButton->setToolTip( tr( "Full Image" ) ); @@ -116,11 +118,11 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc renderingButtonGroup->addButton( fullImageButton, HistogramWidget::FullImageHistogram ); renderingButtonGroup->addButton( selectionImageButton, HistogramWidget::ImageSelectionHistogram ); - QHBoxLayout *regionLayout = new QHBoxLayout; + QHBoxLayout* regionLayout = new QHBoxLayout; regionLayout->addWidget( fullImageButton ); regionLayout->addWidget( selectionImageButton ); - QGridLayout *mainLayout = new QGridLayout; + QGridLayout* mainLayout = new QGridLayout; mainLayout->addWidget( channelLabel, 1, 0 ); mainLayout->addWidget( channelCB, 1, 1 ); mainLayout->addLayout( scaleLayout, 1, 3 ); @@ -132,10 +134,11 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc // ------------------------------------------------------------- histogramWidget = new HistogramWidget( 100, 100 ); - histogramWidget->setWhatsThis( tr( "

This is the histogram drawing of " - "the selected image channel" ) ); + histogramWidget->setWhatsThis( + tr( "

This is the histogram drawing of " + "the selected image channel" ) ); - QVBoxLayout *histogramLayout = new QVBoxLayout; + QVBoxLayout* histogramLayout = new QVBoxLayout; histogramLayout->setSpacing( 1 ); histogramLayout->addWidget( histogramWidget ); @@ -143,24 +146,26 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc // ------------------------------------------------------------- - QLabel *rangeSelectionLabel = new QLabel( tr( "Range:" ) ); + QLabel* rangeSelectionLabel = new QLabel( tr( "Range:" ) ); rangeSelectionLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); minInterv = new QSpinBox; minInterv->setRange( 0, 255 ); minInterv->setSingleStep( 1 ); minInterv->setValue( 0 ); - minInterv->setWhatsThis( tr( "

Select here the minimal intensity " - "value of the histogram selection." ) ); + minInterv->setWhatsThis( + tr( "

Select here the minimal intensity " + "value of the histogram selection." ) ); maxInterv = new QSpinBox; maxInterv->setRange( 0, 255 ); maxInterv->setSingleStep( 1 ); maxInterv->setValue( 0 ); - minInterv->setWhatsThis( tr( "

Select here the maximal intensity value" - " of the histogram selection." ) ); + minInterv->setWhatsThis( + tr( "

Select here the maximal intensity value" + " of the histogram selection." ) ); - QHBoxLayout *rangeLayout = new QHBoxLayout; + QHBoxLayout* rangeLayout = new QHBoxLayout; rangeLayout->addWidget( rangeSelectionLabel ); rangeLayout->addWidget( minInterv ); rangeLayout->addWidget( maxInterv ); @@ -169,43 +174,43 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc // ----------------- GUI definition ----------------- - QLabel *pixelsLabel = new QLabel( tr( "Pixels:" ) ); + QLabel* pixelsLabel = new QLabel( tr( "Pixels:" ) ); pixelsLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelPixelsValue = new QLabel; labelPixelsValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *countLabel = new QLabel( tr( "Selected:" ) ); + QLabel* countLabel = new QLabel( tr( "Selected:" ) ); countLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelCountValue = new QLabel; labelCountValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *rangeLabel = new QLabel( tr( "Range:" ) ); + QLabel* rangeLabel = new QLabel( tr( "Range:" ) ); rangeLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelRangeValue = new QLabel; labelRangeValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *meanLabel = new QLabel( tr( "Mean:" ) ); + QLabel* meanLabel = new QLabel( tr( "Mean:" ) ); meanLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelMeanValue = new QLabel; labelMeanValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *stdDevLabel = new QLabel( tr( "Std. deviation:" ) ); + QLabel* stdDevLabel = new QLabel( tr( "Std. deviation:" ) ); stdDevLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelStdDevValue = new QLabel; labelStdDevValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *medianLabel = new QLabel( tr( "Median:" ) ); + QLabel* medianLabel = new QLabel( tr( "Median:" ) ); medianLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelMedianValue = new QLabel; labelMedianValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QLabel *percentileLabel = new QLabel( tr( "Percentile:" ) ); + QLabel* percentileLabel = new QLabel( tr( "Percentile:" ) ); percentileLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); labelPercentileValue = new QLabel; labelPercentileValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); Int gridRow = 0; - QGridLayout *statisticsLayout = new QGridLayout; + QGridLayout* statisticsLayout = new QGridLayout; statisticsLayout->addWidget( pixelsLabel, gridRow, 0 ); statisticsLayout->addWidget( labelPixelsValue, gridRow++, 1 ); statisticsLayout->addWidget( countLabel, gridRow, 0 ); @@ -218,14 +223,15 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc statisticsLayout->addWidget( labelStdDevValue, gridRow++, 1 ); statisticsLayout->addWidget( medianLabel, gridRow, 0 ); statisticsLayout->addWidget( labelMedianValue, gridRow++, 1 ); -// statisticsLayout->addWidget( percentileLabel, 5, 0 ); -// statisticsLayout->addWidget( labelPercentileValue, 5, 1 ); + // statisticsLayout->addWidget( percentileLabel, 5, 0 ); + // statisticsLayout->addWidget( labelPercentileValue, 5, 1 ); - QGroupBox *statisticsGroup = new QGroupBox( tr( "Statistics" ) ); + QGroupBox* statisticsGroup = new QGroupBox( tr( "Statistics" ) ); statisticsGroup->setLayout( statisticsLayout ); - statisticsGroup->setWhatsThis( tr( "

Here you can see the statistical results calculated from the " - "selected histogram part. These values are available for all " - "channels." ) ); + statisticsGroup->setWhatsThis( + tr( "

Here you can see the statistical results calculated from the " + "selected histogram part. These values are available for all " + "channels." ) ); mainLayout->addWidget( statisticsGroup, 5, 0, 1, 4 ); @@ -233,17 +239,17 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc setLayout( mainLayout ); setEnabled( false ); - connect( channelCB, SIGNAL( activated(int) ), this, SLOT( slotChannelChanged(int) ) ); - connect( scaleButtonGroup, SIGNAL( buttonClicked(int) ), this, SLOT( slotScaleChanged(int) ) ); - connect( colorsCB, SIGNAL( activated(int) ), this, SLOT( slotColorsChanged(int) ) ); - connect( renderingButtonGroup, SIGNAL( buttonClicked(int) ), this, SLOT( slotRenderingChanged(int) ) ); - connect( histogramWidget, SIGNAL( signalIntervalChanged( int, int ) ), this, SLOT( slotUpdateInterval(int, int) ) ); - connect( histogramWidget, SIGNAL( signalMaximumValueChanged(int) ), this, SLOT( slotUpdateIntervRange(int) ) ); - connect( histogramWidget, SIGNAL( signalHistogramComputationDone(int) ), this, SLOT( slotRefreshOptions(int) ) ); - connect( histogramWidget, SIGNAL( signalHistogramComputationFailed(void) ), this, SLOT( slotHistogramComputationFailed(void) ) ); - connect( minInterv, SIGNAL( valueChanged (int) ), this, SLOT( slotMinValueChanged(int) ) ); - connect( maxInterv, SIGNAL( valueChanged (int) ), this, SLOT( slotMaxValueChanged(int) ) ); - + connect( channelCB, SIGNAL( activated( int ) ), this, SLOT( slotChannelChanged( int ) ) ); + connect( scaleButtonGroup, SIGNAL( buttonClicked( int ) ), this, SLOT( slotScaleChanged( int ) ) ); + connect( colorsCB, SIGNAL( activated( int ) ), this, SLOT( slotColorsChanged( int ) ) ); + connect( renderingButtonGroup, SIGNAL( buttonClicked( int ) ), this, SLOT( slotRenderingChanged( int ) ) ); + connect( histogramWidget, SIGNAL( signalIntervalChanged( int, int ) ), this, SLOT( slotUpdateInterval( int, int ) ) ); + connect( histogramWidget, SIGNAL( signalMaximumValueChanged( int ) ), this, SLOT( slotUpdateIntervRange( int ) ) ); + connect( histogramWidget, SIGNAL( signalHistogramComputationDone( int ) ), this, SLOT( slotRefreshOptions( int ) ) ); + connect( histogramWidget, SIGNAL( signalHistogramComputationFailed( void ) ), this, + SLOT( slotHistogramComputationFailed( void ) ) ); + connect( minInterv, SIGNAL( valueChanged( int ) ), this, SLOT( slotMinValueChanged( int ) ) ); + connect( maxInterv, SIGNAL( valueChanged( int ) ), this, SLOT( slotMaxValueChanged( int ) ) ); } FramePropertiesDock::~FramePropertiesDock() @@ -314,10 +320,11 @@ Void FramePropertiesDock::setFrame( PlaYUVerFrame* pcFrame ) colorsCB->addItem( "Green" ); colorsCB->addItem( "Blue" ); colorsCB->setEnabled( false ); - colorsCB->setWhatsThis( tr( "

Select here the main color displayed with Colors Channel mode:" - "

Red: Draw the Red image channel in the foreground.

" - "Green: Draw the Green image channel in the foreground.

" - "Blue: Draw the Blue image channel in the foreground.

" ) ); + colorsCB->setWhatsThis( + tr( "

Select here the main color displayed with Colors Channel mode:" + "

Red: Draw the Red image channel in the foreground.

" + "Green: Draw the Green image channel in the foreground.

" + "Blue: Draw the Blue image channel in the foreground.

" ) ); colorsCB->show(); colorsLabel->show(); } @@ -334,10 +341,11 @@ Void FramePropertiesDock::setFrame( PlaYUVerFrame* pcFrame ) colorsCB->addItem( "Chroma U" ); colorsCB->addItem( "Chroma V" ); colorsCB->setEnabled( false ); - colorsCB->setWhatsThis( tr( "

Select here the main color displayed with Colors Channel mode:" - "

Luminance: DraupdateDataw the Luminance channel in the foreground.

" - "Chroma U: Draw the Chroma U channel in the foreground.

" - "Chroma V: Draw the Chroma V channel in the foreground.

" ) ); + colorsCB->setWhatsThis( + tr( "

Select here the main color displayed with Colors Channel mode:" + "

Luminance: DraupdateDataw the Luminance channel in the foreground.

" + "Chroma U: Draw the Chroma U channel in the foreground.

" + "Chroma V: Draw the Chroma V channel in the foreground.

" ) ); colorsCB->show(); colorsLabel->show(); } @@ -358,7 +366,7 @@ Void FramePropertiesDock::setFrame( PlaYUVerFrame* pcFrame ) } } -Void FramePropertiesDock::setSelection( const QRect &selectionArea ) +Void FramePropertiesDock::setSelection( const QRect& selectionArea ) { if( m_pcFrame ) { @@ -378,7 +386,8 @@ Void FramePropertiesDock::setSelection( const QRect &selectionArea ) { delete m_pcSelectedFrame; } - m_pcSelectedFrame = new PlaYUVerFrame( m_pcFrame, selectionArea.x(), selectionArea.y(), selectionArea.width(), selectionArea.height() ); + m_pcSelectedFrame = new PlaYUVerFrame( m_pcFrame, selectionArea.x(), selectionArea.y(), selectionArea.width(), + selectionArea.height() ); } updateDataHistogram(); selectionImageButton->click(); @@ -445,21 +454,21 @@ Void FramePropertiesDock::updateStatistiques() if( frame ) { - - QString rangeText = "[" + QString::number( frame->getMin( channel ) ) + ":" + QString::number( frame->getMax( channel ) ) + "]"; + QString rangeText = + "[" + QString::number( frame->getMin( channel ) ) + ":" + QString::number( frame->getMax( channel ) ) + "]"; labelRangeValue->setText( rangeText ); double mean = frame->getMean( channel, min, max ); labelMeanValue->setText( value.setNum( mean, 'f', 1 ) ); double pixels = frame->getPixels(); - labelPixelsValue->setText( value.setNum( ( float )pixels, 'f', 0 ) ); + labelPixelsValue->setText( value.setNum( (float)pixels, 'f', 0 ) ); double stddev = frame->getStdDev( channel, min, max ); labelStdDevValue->setText( value.setNum( stddev, 'f', 1 ) ); double counts = frame->getCount( channel, min, max ); - labelCountValue->setText( value.setNum( ( float )counts, 'f', 0 ) ); + labelCountValue->setText( value.setNum( (float)counts, 'f', 0 ) ); double median = frame->getMedian( channel, min, max ); labelMedianValue->setText( value.setNum( median, 'f', 1 ) ); @@ -515,31 +524,31 @@ Void FramePropertiesDock::slotChannelChanged( Int channel ) switch( channel ) { - case FirstChannel: - histogramWidget->m_channelType = HistogramWidget::FirstChannelHistogram; - colorsCB->setEnabled( false ); - break; - case SecondChannel: - histogramWidget->m_channelType = HistogramWidget::SecondChannelHistogram; - colorsCB->setEnabled( false ); - break; - case ThirdChannel: - histogramWidget->m_channelType = HistogramWidget::ThirdChannelHistogram; - colorsCB->setEnabled( false ); - break; - case AlphaChannel: - histogramWidget->m_channelType = HistogramWidget::AlphaChannelHistogram; - colorsCB->setEnabled( false ); - break; - case ColorChannels: - histogramWidget->m_channelType = HistogramWidget::ColorChannelsHistogram; - colorsCB->setEnabled( true ); - break; - default: // Luminance. - //histogramWidget->m_channelType = HistogramWidget::LumaHistogram; - histogramWidget->m_channelType = HistogramWidget::FirstChannelHistogram; - colorsCB->setEnabled( false ); - break; + case FirstChannel: + histogramWidget->m_channelType = HistogramWidget::FirstChannelHistogram; + colorsCB->setEnabled( false ); + break; + case SecondChannel: + histogramWidget->m_channelType = HistogramWidget::SecondChannelHistogram; + colorsCB->setEnabled( false ); + break; + case ThirdChannel: + histogramWidget->m_channelType = HistogramWidget::ThirdChannelHistogram; + colorsCB->setEnabled( false ); + break; + case AlphaChannel: + histogramWidget->m_channelType = HistogramWidget::AlphaChannelHistogram; + colorsCB->setEnabled( false ); + break; + case ColorChannels: + histogramWidget->m_channelType = HistogramWidget::ColorChannelsHistogram; + colorsCB->setEnabled( true ); + break; + default: // Luminance. + // histogramWidget->m_channelType = HistogramWidget::LumaHistogram; + histogramWidget->m_channelType = HistogramWidget::FirstChannelHistogram; + colorsCB->setEnabled( false ); + break; } histogramWidget->update(); updateStatistiques(); @@ -555,15 +564,15 @@ Void FramePropertiesDock::slotColorsChanged( Int color ) { switch( color ) { - case AllColorsGreen: - histogramWidget->m_colorType = HistogramWidget::SecondChannelColor; - break; - case AllColorsBlue: - histogramWidget->m_colorType = HistogramWidget::ThirdChannelColor; - break; - default: // Red. - histogramWidget->m_colorType = HistogramWidget::FirstChannelColor; - break; + case AllColorsGreen: + histogramWidget->m_colorType = HistogramWidget::SecondChannelColor; + break; + case AllColorsBlue: + histogramWidget->m_colorType = HistogramWidget::ThirdChannelColor; + break; + default: // Red. + histogramWidget->m_colorType = HistogramWidget::FirstChannelColor; + break; } histogramWidget->update(); @@ -625,4 +634,3 @@ Void FramePropertiesDock::slotUpdateIntervRange( Int range ) maxInterv->setMaximum( range ); maxInterv->blockSignals( false ); } - diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index 2a490fd..fe777bc 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -37,21 +37,21 @@ #include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" -class FramePropertiesDock: public QWidget +class FramePropertiesDock : public QWidget { -Q_OBJECT - public: + Q_OBJECT + public: FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ); ~FramePropertiesDock(); QSize sizeHint() const; Void setFrame( PlaYUVerFrame* m_pcFrame ); - Void setSelection( const QRect &selectionArea ); + Void setSelection( const QRect& selectionArea ); Void reset(); Void stopHistogram(); -private: + private: enum ColorChannel { LuminosityChannel = 0, @@ -69,45 +69,45 @@ private: AllColorsBlue }; - PlaYUVerFrame *m_pcFrame; - PlaYUVerFrame *m_pcSelectedFrame; + PlaYUVerFrame* m_pcFrame; + PlaYUVerFrame* m_pcSelectedFrame; Int m_iLastFrameType; Bool* m_pbIsPlaying; - QComboBox *channelCB; - QComboBox *colorsCB; - QComboBox *renderingCB; + QComboBox* channelCB; + QComboBox* colorsCB; + QComboBox* renderingCB; - QPushButton *linHistoButton; - QPushButton *logHistoButton; - QPushButton *fullImageButton; - QPushButton *selectionImageButton; + QPushButton* linHistoButton; + QPushButton* logHistoButton; + QPushButton* fullImageButton; + QPushButton* selectionImageButton; - QButtonGroup *scaleButtonGroup; - QButtonGroup *renderingButtonGroup; + QButtonGroup* scaleButtonGroup; + QButtonGroup* renderingButtonGroup; - QSpinBox *minInterv; - QSpinBox *maxInterv; + QSpinBox* minInterv; + QSpinBox* maxInterv; - QLabel *labelPixelsValue; - QLabel *labelCountValue; - QLabel *labelRangeValue; - QLabel *labelMeanValue; - QLabel *labelStdDevValue; - QLabel *labelMedianValue; - QLabel *labelPercentileValue; + QLabel* labelPixelsValue; + QLabel* labelCountValue; + QLabel* labelRangeValue; + QLabel* labelMeanValue; + QLabel* labelStdDevValue; + QLabel* labelMedianValue; + QLabel* labelPercentileValue; - QLabel *colorsLabel; + QLabel* colorsLabel; QRect m_cSelectionArea; - HistogramWidget *histogramWidget; + HistogramWidget* histogramWidget; Void updateStatistiques(); Void updateDataHistogram(); -private Q_SLOTS: + private Q_SLOTS: void slotRefreshOptions( int range ); void slotHistogramComputationFailed( void ); void slotChannelChanged( int channel ); @@ -119,7 +119,6 @@ private Q_SLOTS: void slotUpdateInterval( int min, int max ); void slotUpdateIntervRange( int range ); - }; -#endif // __FRAMEPROPERTIESDOCK_H__ +#endif // __FRAMEPROPERTIESDOCK_H__ diff --git a/app/GridManager.cpp b/app/GridManager.cpp index ba4b1a3..68c4ffa 100644 --- a/app/GridManager.cpp +++ b/app/GridManager.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -47,10 +47,10 @@ GridManager::GridManager() //////////////////////////////////////////////////////////////////////////////// // Grid Drawer //////////////////////////////////////////////////////////////////////////////// -void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter ) +void GridManager::drawGrid( QPixmap& image, const QRect& area, QPainter* painter ) { - int offsetx = 0; // Grid offset doesn't applies to SCODE - int offsety = 0; // project for now... + int offsetx = 0; // Grid offset doesn't applies to SCODE + int offsety = 0; // project for now... int imageWidth = image.width(); int imageHeight = image.height(); @@ -65,82 +65,82 @@ void GridManager::drawGrid( QPixmap &image, const QRect& area, QPainter *painter style = Solid; switch( style ) { - case IntersectionDot: + case IntersectionDot: case IntersectionCross: { - painter->setPen( mainPen ); - // Draw crosses or dots on intersections - for( int x = offsetx; x <= area.right(); x += hSpacing ) - { - if( x >= imageWidth ) - break; + painter->setPen( mainPen ); + // Draw crosses or dots on intersections + for( int x = offsetx; x <= area.right(); x += hSpacing ) + { + if( x >= imageWidth ) + break; + for( int y = offsety; y <= area.bottom(); y += vSpacing ) + { + if( y >= imageHeight ) + break; + + if( x >= area.x() && y >= area.y() ) + { + if( style == IntersectionDot ) + painter->drawPoint( x, y ); // Dot + else + { // Crosses: + painter->drawLine( x, y - 1, x, y + 1 ); // Ver.line + painter->drawLine( x - 1, y, x + 1, y ); // Hor.line + } + } + } + } + break; + } + case Dashed: + { + // Change pen to the dashed line + mainPen.setStyle( Qt::DashLine ); + } + default: // Solid: + { + painter->setPen( mainPen ); + + // Draw vertical line + for( int x = offsetx; x <= area.right(); x += hSpacing ) + { + if( x >= imageWidth ) + break; + + if( x >= area.x() ) + { + // Always draw the full line otherwise the line stippling + // varies with the location of view area and we get glitchy + // patterns. + painter->drawLine( x, 0, x, imageHeight - 1 ); + } + } + // Draw horizontal line for( int y = offsety; y <= area.bottom(); y += vSpacing ) { if( y >= imageHeight ) break; - if( x >= area.x() && y >= area.y() ) + if( y >= area.y() ) { - if( style == IntersectionDot ) - painter->drawPoint( x, y ); // Dot - else - { // Crosses: - painter->drawLine( x, y - 1, x, y + 1 ); // Ver.line - painter->drawLine( x - 1, y, x + 1, y ); // Hor.line - } + painter->drawLine( 0, y, imageWidth - 1, y ); } } + break; } - break; - } - case Dashed: - { - // Change pen to the dashed line - mainPen.setStyle( Qt::DashLine ); - } - default: // Solid: - { - painter->setPen( mainPen ); - - // Draw vertical line - for( int x = offsetx; x <= area.right(); x += hSpacing ) - { - if( x >= imageWidth ) - break; - - if( x >= area.x() ) - { - // Always draw the full line otherwise the line stippling - // varies with the location of view area and we get glitchy - // patterns. - painter->drawLine( x, 0, x, imageHeight - 1 ); - } - } - // Draw horizontal line - for( int y = offsety; y <= area.bottom(); y += vSpacing ) - { - if( y >= imageHeight ) - break; - - if( y >= area.y() ) - { - painter->drawLine( 0, y, imageWidth - 1, y ); - } - } - break; - } } } //////////////////////////////////////////////////////////////////////////////// -QRect GridManager::rectContains( const QPoint &pos ) const - { +QRect GridManager::rectContains( const QPoint& pos ) const +{ return rectContains( pos.x(), pos.y() ); } QRect GridManager::rectContains( int x, int y ) const - { +{ QRect rect; QPoint pos; int multiPosX; @@ -242,8 +242,8 @@ bool GridManager::isNear( int x, int y ) { for( int i = 0; i < 2; i++ ) { - gx = ( int )( multiPosX * hSpacing + i * hSpacing ); - gy = ( int )( multiPosY * vSpacing + j * vSpacing ); + gx = (int)( multiPosX * hSpacing + i * hSpacing ); + gy = (int)( multiPosY * vSpacing + j * vSpacing ); gridPoint.setX( gx ); gridPoint.setY( gy ); rect.moveCenter( gridPoint ); @@ -259,7 +259,7 @@ bool GridManager::isNear( int x, int y ) return false; } -bool GridManager::isNear( const QPoint &pos ) +bool GridManager::isNear( const QPoint& pos ) { return isNear( pos.x(), pos.y() ); } diff --git a/app/GridManager.h b/app/GridManager.h index 3291151..f68a439 100644 --- a/app/GridManager.h +++ b/app/GridManager.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -41,8 +41,7 @@ class QPainter; */ class GridManager { -public: - + public: enum Style { IntersectionDot = 0, @@ -53,7 +52,7 @@ public: GridManager(); - void drawGrid( QPixmap &image, const QRect& area, QPainter *painter ); + void drawGrid( QPixmap& image, const QRect& area, QPainter* painter ); /** * @returns a QRect defined by the grid that contains the point (x, y). @@ -64,7 +63,7 @@ public: * This is an overloaded member function, provided for convenience. * @returns a QRect defined by the grid that contains the QPoint pos. */ - QRect rectContains( const QPoint &pos ) const; + QRect rectContains( const QPoint& pos ) const; /** * @returns @c true if the point (x, y) is over a grid crossing, otherwise @@ -84,7 +83,7 @@ public: * returns @c false. * @see @p nearPos() */ - bool isNear( const QPoint &pos ); + bool isNear( const QPoint& pos ); /** * @returns the grid crossing position that is near the point (x,y). If @@ -93,8 +92,7 @@ public: */ QPoint nearPos( int x = -1, int y = -1 ); -private: - + private: UInt m_uiHSpace; UInt m_uiVSpace; QColor m_cGridColor; @@ -102,4 +100,4 @@ private: QPoint m_nearPos; }; -#endif // __GRIDMANAGER_H__ +#endif // __GRIDMANAGER_H__ diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index a2a89dc..c36abf2 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -23,7 +23,7 @@ * Based on the work of Ricardo N. Rocha Sardo in SCode project */ -//TODO: +// TODO: // - Optimizar paintEvent. Parece haver codigo redundante !! #include "config.h" #include @@ -31,14 +31,13 @@ #include #include "HistogramWidget.h" -class HistogramWorker: public QThread +class HistogramWorker : public QThread { -private: + private: QObject* m_parent; PlaYUVerFrame* m_pcFrame; -public: - + public: HistogramWorker( QObject* parent ) { m_pcFrame = NULL; @@ -54,18 +53,18 @@ public: { if( m_pcFrame && m_parent ) { - EventData *eventData = new EventData(); -// eventDm_imageHistogramata->starting = true; -// eventData->success = false; -// eventData->histogram = m_histogram; -// QCoreApplication::postEvent( m_parent, eventData ); + EventData* eventData = new EventData(); + // eventDm_imageHistogramata->starting = true; + // eventData->success = false; + // eventData->histogram = m_histogram; + // QCoreApplication::postEvent( m_parent, eventData ); eventData->starting = true; m_pcFrame->calcHistogram(); eventData->starting = false; -// eventData->success = m_pcFrame->getHasHistogram(); + // eventData->success = m_pcFrame->getHasHistogram(); eventData->success = true; eventData->frame = m_pcFrame; QCoreApplication::postEvent( m_parent, eventData ); @@ -75,13 +74,10 @@ public: /** * Custom Event */ - class EventData: public QEvent + class EventData : public QEvent { - - public: - - EventData() : - QEvent( QEvent::User ) + public: + EventData() : QEvent( QEvent::User ) { starting = false; success = false; @@ -90,37 +86,34 @@ public: bool starting; bool success; - PlaYUVerFrame *frame; + PlaYUVerFrame* frame; }; - }; -const QBrush g_eColorPallet[][3] = +const QBrush g_eColorPallet[][3] = { { - { - Qt::darkGray, // Luma - Qt::blue, // Cb - Qt::red, // Cr - }, - { - Qt::red, // Channel Red - Qt::green, // Channel Green - Qt::blue, // Channel Blue - }, - }; + Qt::darkGray, // Luma + Qt::blue, // Cb + Qt::red, // Cr + }, + { + Qt::red, // Channel Red + Qt::green, // Channel Green + Qt::blue, // Channel Blue + }, +}; class HistogramWidgetPrivate { -public: - + public: enum RepaintType { - HistogramNone = 0, // No current histogram values calculation. - HistogramDataLoading, // The image is being loaded - HistogramStarted, // Histogram values calculation started. - HistogramCompleted, // Histogram values calculation completed. - HistogramSkipped, // Skip histogram while playing - HistogramFailed // Histogram values calculation failed. + HistogramNone = 0, // No current histogram values calculation. + HistogramDataLoading, // The image is being loaded + HistogramStarted, // Histogram values calculation started. + HistogramCompleted, // Histogram values calculation completed. + HistogramSkipped, // Skip histogram while playing + HistogramFailed // Histogram values calculation failed. }; HistogramWidgetPrivate() @@ -142,7 +135,7 @@ public: double xminOrg; double xmax; Int range; - Int clearFlag; // Clear drawing zone with message. + Int clearFlag; // Clear drawing zone with message. // Image informations Int imageChannels; @@ -152,17 +145,17 @@ public: bool guideVisible; // Display color guide. bool statisticsVisible; // Display tooltip histogram statistics. bool inSelected; - bool selectMode; // If true, a part of the histogram can be - // selected ! + bool selectMode; // If true, a part of the histogram can be + // selected ! bool blinkFlag; - bool blinkComputation; // If true, a message will be displayed during - // histogram computation, else nothing (limit - // flicker effect in widget especially for small - // image/computation time). - bool lumaChannel; // Compute luminance channel if true. + bool blinkComputation; // If true, a message will be displayed during + // histogram computation, else nothing (limit + // flicker effect in widget especially for small + // image/computation time). + bool lumaChannel; // Compute luminance channel if true. bool inInitialRepaintWait; - QTimer *blinkTimer; + QTimer* blinkTimer; QColor colorGuide; }; @@ -171,15 +164,14 @@ public: // Constructors //////////////////////////////////////////////////////////////////////////////// -//Constructor without image data -HistogramWidget::HistogramWidget( Int width, Int height, QWidget *parent ) : - QWidget( parent ) +// Constructor without image data +HistogramWidget::HistogramWidget( Int width, Int height, QWidget* parent ) : QWidget( parent ) { setAttribute( Qt::WA_DeleteOnClose ); d = new HistogramWidgetPrivate; -// m_channelType = LumaHistogram; + // m_channelType = LumaHistogram; m_channelType = FirstChannelHistogram; m_scaleType = LogScaleHistogram; m_colorType = FirstChannelColor; @@ -210,11 +202,11 @@ HistogramWidget::~HistogramWidget() { d->blinkTimer->stop(); -// if( m_imageHistogram ) -// delete m_imageHistogram; -// -// if( m_selectionHistogram ) -// delete m_selectionHistogram; + // if( m_imageHistogram ) + // delete m_imageHistogram; + // + // if( m_selectionHistogram ) + // delete m_selectionHistogram; delete m_imageWorker; delete m_selectionWorker; @@ -227,10 +219,10 @@ HistogramWidget::~HistogramWidget() Void HistogramWidget::setOptions( HistogramOptions options ) { - d->statisticsVisible = ( bool )( options & ShowStatistics ); - d->selectMode = ( bool )( options & SelectMode ); - d->blinkComputation = ( bool )( options & BlinkComputation ); - d->lumaChannel = ( bool )( options & ShowLumaChannel ); + d->statisticsVisible = (bool)( options & ShowStatistics ); + d->selectMode = (bool)( options & SelectMode ); + d->blinkComputation = (bool)( options & BlinkComputation ); + d->lumaChannel = (bool)( options & ShowLumaChannel ); } Void HistogramWidget::setHistogramGuideByColor( QColor color ) @@ -254,14 +246,14 @@ Void HistogramWidget::reset() // Custom Event Handler //////////////////////////////////////////////////////////////////////////////// -Void HistogramWidget::customEvent( QEvent *event ) +Void HistogramWidget::customEvent( QEvent* event ) { if( !event ) { return; } - HistogramWorker::EventData *ed = ( HistogramWorker::EventData* )event; + HistogramWorker::EventData* ed = (HistogramWorker::EventData*)event; if( !ed ) { @@ -326,21 +318,21 @@ Void HistogramWidget::customEvent( QEvent *event ) // Remove old histogram data from memory. m_fullImage = NULL; m_selectionImage = NULL; -// if( m_imageHistogram ) -// { -// delete m_imageHistogram; -// m_imageHistogram = 0; -// } -// if( m_selectionHistogram ) -// { -// delete m_selectionHistogram; -// m_selectionHistogram = 0; -// } + // if( m_imageHistogram ) + // { + // delete m_imageHistogram; + // m_imageHistogram = 0; + // } + // if( m_selectionHistogram ) + // { + // delete m_selectionHistogram; + // m_selectionHistogram = 0; + // } emit signalHistogramComputationFailed(); } } - //delete ed; + // delete ed; } //////////////////////////////////////////////////////////////////////////////// // Data Loading Functions @@ -382,11 +374,11 @@ Void HistogramWidget::setLoadingFailed() Void HistogramWidget::stopHistogramComputation() { -// if( m_imageHistogram ) -// m_imageHistogram->setRunningFlag( false ); -// -// if( m_selectionHistogram ) -// m_selectionHistogram->setRunningFlag( false ); + // if( m_imageHistogram ) + // m_imageHistogram->setRunningFlag( false ); + // + // if( m_selectionHistogram ) + // m_selectionHistogram->setRunningFlag( false ); d->blinkTimer->stop(); } @@ -395,7 +387,7 @@ Void HistogramWidget::stopHistogramComputation() // Update Data Methods //////////////////////////////////////////////////////////////////////////////// -Void HistogramWidget::updateData( PlaYUVerFrame *pcFrame, PlaYUVerFrame *pcFrameSelection ) +Void HistogramWidget::updateData( PlaYUVerFrame* pcFrame, PlaYUVerFrame* pcFrameSelection ) { d->imageBits = pcFrame->getBitsPel(); d->imageColorSpace = pcFrame->getColorSpace(); @@ -416,7 +408,6 @@ Void HistogramWidget::updateData( PlaYUVerFrame *pcFrame, PlaYUVerFrame *pcFrame m_selectionImage = pcFrameSelection; m_selectionWorker->setup( pcFrameSelection ); - } //////////////////////////////////////////////////////////////////////////////// @@ -433,7 +424,7 @@ Void HistogramWidget::slotBlinkTimerDone() // Paint Event //////////////////////////////////////////////////////////////////////////////// -Void HistogramWidget::paintEvent( QPaintEvent * ) +Void HistogramWidget::paintEvent( QPaintEvent* ) { int maxX = size().width() - 1; int maxY = size().height() - 1; @@ -441,8 +432,9 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) // Widget is disabled, not initialized, // or loading, but no message shall be drawn: // Drawing grayed frame. - if( !isEnabled() || d->clearFlag == HistogramWidgetPrivate::HistogramNone - || ( !d->blinkComputation && ( d->clearFlag == HistogramWidgetPrivate::HistogramStarted || d->clearFlag == HistogramWidgetPrivate::HistogramDataLoading ) ) ) + if( !isEnabled() || d->clearFlag == HistogramWidgetPrivate::HistogramNone || + ( !d->blinkComputation && ( d->clearFlag == HistogramWidgetPrivate::HistogramStarted || + d->clearFlag == HistogramWidgetPrivate::HistogramDataLoading ) ) ) { QPainter p1( this ); @@ -454,7 +446,8 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) } // Image data is loading or histogram is being computed: // Draw message. - else if( d->blinkComputation && ( d->clearFlag == HistogramWidgetPrivate::HistogramStarted || d->clearFlag == HistogramWidgetPrivate::HistogramDataLoading ) ) + else if( d->blinkComputation && ( d->clearFlag == HistogramWidgetPrivate::HistogramStarted || + d->clearFlag == HistogramWidgetPrivate::HistogramDataLoading ) ) { QPainter p1( this ); @@ -480,7 +473,7 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) p1.fillRect( 0, 0, maxX, maxY, Qt::white ); p1.setPen( Qt::darkGreen ); p1.drawText( 0, 0, maxX, maxY, Qt::AlignCenter, tr( "Histogram\ncalculation\nskipped." ) ); - //bitBlt(this, 0, 0, &pm); + // bitBlt(this, 0, 0, &pm); return; } // Histogram computation failed: @@ -491,16 +484,16 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) p1.fillRect( 0, 0, maxX, maxY, Qt::white ); p1.setPen( Qt::red ); p1.drawText( 0, 0, maxX, maxY, Qt::AlignCenter, tr( "Histogram\ncalculation\nfailed." ) ); - //bitBlt(this, 0, 0, &pm); + // bitBlt(this, 0, 0, &pm); return; } int x, y; - int yr, yg, yb; // For all color channels. + int yr, yg, yb; // For all color channels. int wWidth = width() - 1; int wHeight = height() - 1; double max; - PlaYUVerFrame *frame; + PlaYUVerFrame* frame; if( m_renderingType == ImageSelectionHistogram && m_selectionImage ) frame = m_selectionImage; @@ -519,38 +512,38 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) switch( m_channelType ) { - case HistogramWidget::FirstChannelHistogram: // Y channel. - max = frame->getMaximum( LUMA ); - break; - case HistogramWidget::SecondChannelHistogram: // Cb channel. - max = frame->getMaximum( CHROMA_U ); - break; - case HistogramWidget::ThirdChannelHistogram: // Cr channel. - max = frame->getMaximum( CHROMA_V ); - break; - case HistogramWidget::AlphaChannelHistogram: // Alpha channel. - max = frame->getMaximum( COLOR_A ); - break; + case HistogramWidget::FirstChannelHistogram: // Y channel. + max = frame->getMaximum( LUMA ); + break; + case HistogramWidget::SecondChannelHistogram: // Cb channel. + max = frame->getMaximum( CHROMA_U ); + break; + case HistogramWidget::ThirdChannelHistogram: // Cr channel. + max = frame->getMaximum( CHROMA_V ); + break; + case HistogramWidget::AlphaChannelHistogram: // Alpha channel. + max = frame->getMaximum( COLOR_A ); + break; - case HistogramWidget::ColorChannelsHistogram: // All color channels. - max = qMax( qMax( frame->getMaximum( LUMA ), frame->getMaximum( CHROMA_U ) ), frame->getMaximum( CHROMA_V ) ); - break; -// case HistogramWidget::LumaHistogram: // Luminance. -// max = frame->getMaximum( LUMA ); -// break; + case HistogramWidget::ColorChannelsHistogram: // All color channels. + max = qMax( qMax( frame->getMaximum( LUMA ), frame->getMaximum( CHROMA_U ) ), frame->getMaximum( CHROMA_V ) ); + break; + // case HistogramWidget::LumaHistogram: // Luminance. + // max = frame->getMaximum( LUMA ); + // break; } switch( m_scaleType ) { - case HistogramWidget::LinScaleHistogram: - break; + case HistogramWidget::LinScaleHistogram: + break; - case HistogramWidget::LogScaleHistogram: - if( max > 0.0 ) - max = log( max ); - else - max = 1.0; - break; + case HistogramWidget::LogScaleHistogram: + if( max > 0.0 ) + max = log( max ); + else + max = 1.0; + break; } // From Qt 4.0, QWidget automatically double-buffers its painting, @@ -573,7 +566,7 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) do { double v; - double vr, vg, vb; // For all color channels. + double vr, vg, vb; // For all color channels. v = 0.0; vr = 0.0; @@ -582,27 +575,26 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) switch( m_channelType ) { - case HistogramWidget::FirstChannelHistogram: // Y channel. - v = frame->getHistogramValue( LUMA, i++ ); - break; - case HistogramWidget::SecondChannelHistogram: // Cb channel. - v = frame->getHistogramValue( CHROMA_U, i++ ); - break; - case HistogramWidget::ThirdChannelHistogram: // Cr channel. - v = frame->getHistogramValue( CHROMA_V, i++ ); - break; - case HistogramWidget::AlphaChannelHistogram: // Alpha channel. - v = frame->getHistogramValue( COLOR_A, i++ ); - break; - case HistogramWidget::ColorChannelsHistogram: // All color. - vr = frame->getHistogramValue( LUMA, i ); - vg = frame->getHistogramValue( CHROMA_U, i ); - vb = frame->getHistogramValue( CHROMA_V, i++ ); - break; -// case HistogramWidget::LumaHistogram: // Luminance. -// v = frame->getHistogramValue( LUMA, i++ ); -// break; - + case HistogramWidget::FirstChannelHistogram: // Y channel. + v = frame->getHistogramValue( LUMA, i++ ); + break; + case HistogramWidget::SecondChannelHistogram: // Cb channel. + v = frame->getHistogramValue( CHROMA_U, i++ ); + break; + case HistogramWidget::ThirdChannelHistogram: // Cr channel. + v = frame->getHistogramValue( CHROMA_V, i++ ); + break; + case HistogramWidget::AlphaChannelHistogram: // Alpha channel. + v = frame->getHistogramValue( COLOR_A, i++ ); + break; + case HistogramWidget::ColorChannelsHistogram: // All color. + vr = frame->getHistogramValue( LUMA, i ); + vg = frame->getHistogramValue( CHROMA_U, i ); + vb = frame->getHistogramValue( CHROMA_V, i++ ); + break; + // case HistogramWidget::LumaHistogram: // Luminance. + // v = frame->getHistogramValue( LUMA, i++ ); + // break; } if( m_channelType != HistogramWidget::ColorChannelsHistogram ) @@ -619,55 +611,54 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) if( vb > value_b ) value_b = vb; } - } - while( i < j ); + } while( i < j ); if( m_channelType != HistogramWidget::ColorChannelsHistogram ) { switch( m_scaleType ) { - case HistogramWidget::LinScaleHistogram: - y = ( int )( ( wHeight * value ) / max ); - break; + case HistogramWidget::LinScaleHistogram: + y = (int)( ( wHeight * value ) / max ); + break; - case HistogramWidget::LogScaleHistogram: - if( value <= 0.0 ) - value = 1.0; - y = ( int )( ( wHeight * log( value ) ) / max ); - break; + case HistogramWidget::LogScaleHistogram: + if( value <= 0.0 ) + value = 1.0; + y = (int)( ( wHeight * log( value ) ) / max ); + break; - default: - y = 0; - break; + default: + y = 0; + break; } } else { switch( m_scaleType ) { - case HistogramWidget::LinScaleHistogram: - yr = ( int )( ( wHeight * value_r ) / max ); - yg = ( int )( ( wHeight * value_g ) / max ); - yb = ( int )( ( wHeight * value_b ) / max ); - break; + case HistogramWidget::LinScaleHistogram: + yr = (int)( ( wHeight * value_r ) / max ); + yg = (int)( ( wHeight * value_g ) / max ); + yb = (int)( ( wHeight * value_b ) / max ); + break; - case HistogramWidget::LogScaleHistogram: - if( value_r <= 0.0 ) - value_r = 1.0; - if( value_g <= 0.0 ) - value_g = 1.0; - if( value_b <= 0.0 ) - value_b = 1.0; - yr = ( int )( ( wHeight * log( value_r ) ) / max ); - yg = ( int )( ( wHeight * log( value_g ) ) / max ); - yb = ( int )( ( wHeight * log( value_b ) ) / max ); - break; + case HistogramWidget::LogScaleHistogram: + if( value_r <= 0.0 ) + value_r = 1.0; + if( value_g <= 0.0 ) + value_g = 1.0; + if( value_b <= 0.0 ) + value_b = 1.0; + yr = (int)( ( wHeight * log( value_r ) ) / max ); + yg = (int)( ( wHeight * log( value_g ) ) / max ); + yb = (int)( ( wHeight * log( value_b ) ) / max ); + break; - default: - yr = 0; - yg = 0; - yb = 0; - break; + default: + yr = 0; + yg = 0; + yb = 0; + break; } } @@ -675,9 +666,9 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) if( m_channelType != HistogramWidget::ColorChannelsHistogram ) { - if( d->selectMode == true ) // Selection mode enable ? + if( d->selectMode == true ) // Selection mode enable ? { - if( x >= ( int )( d->xmin * wWidth ) && x <= ( int )( d->xmax * wWidth ) ) + if( x >= (int)( d->xmin * wWidth ) && x <= (int)( d->xmax * wWidth ) ) { p1.setPen( QPen( Qt::black, 1, Qt::SolidLine ) ); p1.drawLine( x, wHeight, x, 0 ); @@ -712,11 +703,11 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) } } } - else // All colors channel + else // All colors channel { - if( d->selectMode == true ) // Histogram selection mode enable ? + if( d->selectMode == true ) // Histogram selection mode enable ? { - if( x >= ( int )( d->xmin * wWidth ) && x <= ( int )( d->xmax * wWidth ) ) + if( x >= (int)( d->xmin * wWidth ) && x <= (int)( d->xmax * wWidth ) ) { p1.setPen( QPen( Qt::black, 1, Qt::SolidLine ) ); p1.drawLine( x, wHeight, x, 0 ); @@ -726,17 +717,17 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) // colors channel mode? switch( m_colorType ) { - case HistogramWidget::FirstChannelColor: - p1.drawLine( x, wHeight, x, wHeight - yr ); - break; + case HistogramWidget::FirstChannelColor: + p1.drawLine( x, wHeight, x, wHeight - yr ); + break; - case HistogramWidget::SecondChannelColor: - p1.drawLine( x, wHeight, x, wHeight - yg ); - break; + case HistogramWidget::SecondChannelColor: + p1.drawLine( x, wHeight, x, wHeight - yg ); + break; - default: - p1.drawLine( x, wHeight, x, wHeight - yb ); - break; + default: + p1.drawLine( x, wHeight, x, wHeight - yb ); + break; } } else @@ -745,56 +736,56 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) // colors channel mode? switch( m_colorType ) { - case HistogramWidget::FirstChannelColor: - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); + case HistogramWidget::FirstChannelColor: + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - break; + break; - case HistogramWidget::SecondChannelColor: - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); + case HistogramWidget::SecondChannelColor: + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - break; + break; - default: - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); + default: + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - break; + break; } if( x == wWidth / 4 || x == wWidth / 2 || x == 3 * wWidth / 4 ) @@ -810,65 +801,65 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) // colors channel mode? switch( m_colorType ) { - case HistogramWidget::FirstChannelColor: - p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); + case HistogramWidget::FirstChannelColor: + p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); + p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); + p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - break; + break; - case HistogramWidget::SecondChannelColor: - p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); + case HistogramWidget::SecondChannelColor: + p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); + p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); + p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - break; + break; - default: - p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yr ); - p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yg ); - p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); - p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight, x, wHeight - yb ); + default: + p1.setPen( QPen( Qt::red, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][FirstChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yr ); + p1.setPen( QPen( Qt::green, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][SecondChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yg ); + p1.setPen( QPen( Qt::blue, 1, Qt::SolidLine ) ); + p1.setPen( QPen( g_eColorPallet[pallet][ThirdChannelColor], 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight, x, wHeight - yb ); - p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); - p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); - p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); - p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); - p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); + p1.setPen( QPen( Qt::white, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - qMax( qMax( yr, yg ), yb ), x, 0 ); + p1.setPen( QPen( Qt::gray, 1, Qt::SolidLine ) ); + p1.drawLine( x, wHeight - yr - 1, x, wHeight - yr ); + p1.drawLine( x, wHeight - yg - 1, x, wHeight - yg ); + p1.drawLine( x, wHeight - yb - 1, x, wHeight - yb ); - break; + break; } if( x == wWidth / 4 || x == wWidth / 2 || x == 3 * wWidth / 4 ) @@ -889,25 +880,25 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) { switch( m_channelType ) { - case HistogramWidget::FirstChannelHistogram: - guidePos = d->colorGuide.red(); - break; + case HistogramWidget::FirstChannelHistogram: + guidePos = d->colorGuide.red(); + break; - case HistogramWidget::SecondChannelHistogram: - guidePos = d->colorGuide.green(); - break; + case HistogramWidget::SecondChannelHistogram: + guidePos = d->colorGuide.green(); + break; - case HistogramWidget::ThirdChannelHistogram: - guidePos = d->colorGuide.blue(); - break; + case HistogramWidget::ThirdChannelHistogram: + guidePos = d->colorGuide.blue(); + break; -// case HistogramWidget::LumaHistogram: -// guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() ), d->colorGuide.blue() ); -// break; + // case HistogramWidget::LumaHistogram: + // guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() ), d->colorGuide.blue() ); + // break; - default: // Alpha. - guidePos = -1; - break; + default: // Alpha. + guidePos = -1; + break; } if( guidePos != -1 ) @@ -954,7 +945,7 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) tipText += cellBeg + tr( "Pixels:" ) + cellMid; double pixels = frame->getPixels(); - tipText += value.setNum( ( float )pixels, 'f', 0 ) + cellEnd; + tipText += value.setNum( (float)pixels, 'f', 0 ) + cellEnd; tipText += cellBeg + tr( "Std dev.:" ) + cellMid; double stddev = frame->getStdDev( m_channelType, 0, frame->getHistogramSegment() - 1 ); @@ -962,7 +953,7 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) tipText += cellBeg + tr( "Selected:" ) + cellMid; double counts = frame->getCount( m_channelType, 0, frame->getHistogramSegment() - 1 ); - tipText += value.setNum( ( float )counts, 'f', 0 ) + cellEnd; + tipText += value.setNum( (float)counts, 'f', 0 ) + cellEnd; tipText += cellBeg + tr( "Median:" ) + cellMid; double median = frame->getMedian( m_channelType, 0, frame->getHistogramSegment() - 1 ); @@ -982,14 +973,14 @@ Void HistogramWidget::paintEvent( QPaintEvent * ) p1.setPen( QPen( Qt::black, 1, Qt::SolidLine ) ); p1.drawRect( 0, 0, maxX, maxY ); - //bitBlt(this, 0, 0, &pm); + // bitBlt(this, 0, 0, &pm); } //////////////////////////////////////////////////////////////////////////////// // Mouse Events //////////////////////////////////////////////////////////////////////////////// -Void HistogramWidget::mousePressEvent( QMouseEvent * e ) +Void HistogramWidget::mousePressEvent( QMouseEvent* e ) { if( d->selectMode == true && d->clearFlag == HistogramWidgetPrivate::HistogramCompleted ) { @@ -999,15 +990,15 @@ Void HistogramWidget::mousePressEvent( QMouseEvent * e ) update(); } - d->xmin = ( ( double )e->pos().x() ) / ( ( double )width() ); + d->xmin = ( (double)e->pos().x() ) / ( (double)width() ); d->xminOrg = d->xmin; notifyValuesChanged(); - //emit signalValuesChanged( (int)(d->xmin * d->range), ); + // emit signalValuesChanged( (int)(d->xmin * d->range), ); d->xmax = 0.0; } } -Void HistogramWidget::mouseReleaseEvent( QMouseEvent * ) +Void HistogramWidget::mouseReleaseEvent( QMouseEvent* ) { if( d->selectMode == true && d->clearFlag == HistogramWidgetPrivate::HistogramCompleted ) @@ -1017,15 +1008,15 @@ Void HistogramWidget::mouseReleaseEvent( QMouseEvent * ) if( d->xmax == 0.0 ) { d->xmin = 0.0; - //emit signalMinValueChanged( 0 ); - //emit signalMaxValueChanged( d->range ); + // emit signalMinValueChanged( 0 ); + // emit signalMaxValueChanged( d->range ); notifyValuesChanged(); update(); } } } -Void HistogramWidget::mouseMoveEvent( QMouseEvent * e ) +Void HistogramWidget::mouseMoveEvent( QMouseEvent* e ) { if( d->selectMode == true && d->clearFlag == HistogramWidgetPrivate::HistogramCompleted ) { @@ -1033,14 +1024,14 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent * e ) if( d->inSelected ) { - double max = ( ( double )e->pos().x() ) / ( ( double )width() ); - //int max = (int)(e->pos().x()*((float)m_imageHistogram->getHistogramSegment()/(float)width())); + double max = ( (double)e->pos().x() ) / ( (double)width() ); + // int max = (int)(e->pos().x()*((float)m_imageHistogram->getHistogramSegment()/(float)width())); if( max < d->xminOrg ) { d->xmax = d->xminOrg; d->xmin = max; - //emit signalMinValueChanged( (int)(d->xmin * d->range) ); + // emit signalMinValueChanged( (int)(d->xmin * d->range) ); } else { @@ -1049,7 +1040,7 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent * e ) } notifyValuesChanged(); - //emit signalMaxValueChanged( d->xmax == 0.0 ? d->range : (int)(d->xmax * d->range) ); + // emit signalMaxValueChanged( d->xmax == 0.0 ? d->range : (int)(d->xmax * d->range) ); update(); } @@ -1060,7 +1051,7 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent * e ) Void HistogramWidget::notifyValuesChanged() { - emit signalIntervalChanged( ( int )( d->xmin * d->range ), d->xmax == 0.0 ? d->range : ( int )( d->xmax * d->range ) ); + emit signalIntervalChanged( (int)( d->xmin * d->range ), d->xmax == 0.0 ? d->range : (int)( d->xmax * d->range ) ); } Void HistogramWidget::slotMinValueChanged( int min ) @@ -1075,7 +1066,7 @@ Void HistogramWidget::slotMinValueChanged( int min ) } if( min >= 0 && min < d->range ) { - d->xmin = ( ( double )min ) / d->range; + d->xmin = ( (double)min ) / d->range; } update(); } @@ -1093,9 +1084,8 @@ Void HistogramWidget::slotMaxValueChanged( int max ) } else if( max > 0 && max <= d->range ) { - d->xmax = ( ( double )max ) / d->range; + d->xmax = ( (double)max ) / d->range; } update(); } } - diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index a10a0d1..23104a5 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -37,16 +37,15 @@ class QEvent; class HistogramWorker; class HistogramWidgetPrivate; -class HistogramWidget: public QWidget +class HistogramWidget : public QWidget { -Q_OBJECT - -public: + Q_OBJECT + public: enum HistogramChannel { /** Luminance */ - //LumaHistogram = 0, + // LumaHistogram = 0, /** Channels */ FirstChannelHistogram = 0, SecondChannelHistogram, @@ -93,10 +92,10 @@ public: ShowLumaChannel = 0x8, /** Set all the options */ AllOptions = BlinkComputation | ShowStatistics | SelectMode | ShowLumaChannel - };Q_DECLARE_FLAGS( HistogramOptions, HistogramOption ) - -public : + }; + Q_DECLARE_FLAGS( HistogramOptions, HistogramOption ) + public: /** * Constructor without image data. Needed to use @p updateData() method * after to create instance. @@ -104,7 +103,7 @@ public : * @param height of the widget * @param parent the histogram widget parent */ - HistogramWidget( Int width, Int height, QWidget *parent = 0 ); + HistogramWidget( Int width, Int height, QWidget* parent = 0 ); ~HistogramWidget(); @@ -112,7 +111,7 @@ public : Void stopHistogramComputation(); /** Update full image histogram data. */ - Void updateData( PlaYUVerFrame *pcFrame, PlaYUVerFrame *pcFrameSelection ); + Void updateData( PlaYUVerFrame* pcFrame, PlaYUVerFrame* pcFrameSelection ); /** @see @p HistogramOption */ Void setOptions( HistogramOptions options = AllOptions ); @@ -123,7 +122,7 @@ public : Void reset(); -public: + public: /** Channel type to draw */ Int m_channelType; /** Scale to use for drawing */ @@ -135,40 +134,40 @@ public: /** Full image */ HistogramWorker* m_imageWorker; - //PlaYUVerFrameStats* m_imageHistogram; + // PlaYUVerFrameStats* m_imageHistogram; PlaYUVerFrame* m_fullImage; /** Histogram area selection */ HistogramWorker* m_selectionWorker; - //PlaYUVerFrameStats* m_selectionHistogram; + // PlaYUVerFrameStats* m_selectionHistogram; PlaYUVerFrame* m_selectionImage; - Q_SIGNALS: + Q_SIGNALS: void signalIntervalChanged( int min, int max ); void signalMaximumValueChanged( int ); void signalHistogramComputationDone( int ); void signalHistogramComputationFailed( void ); -public Q_SLOTS: + public Q_SLOTS: void slotMinValueChanged( int min ); void slotMaxValueChanged( int max ); -protected slots: + protected slots: void slotBlinkTimerDone( void ); -protected: - Void paintEvent( QPaintEvent * ); - Void mousePressEvent( QMouseEvent * e ); - Void mouseReleaseEvent( QMouseEvent * e ); - Void mouseMoveEvent( QMouseEvent * e ); + protected: + Void paintEvent( QPaintEvent* ); + Void mousePressEvent( QMouseEvent* e ); + Void mouseReleaseEvent( QMouseEvent* e ); + Void mouseMoveEvent( QMouseEvent* e ); -private: - Void customEvent( QEvent *event ); + private: + Void customEvent( QEvent* event ); Void notifyValuesChanged(); -private: + private: HistogramWidgetPrivate* d; }; Q_DECLARE_OPERATORS_FOR_FLAGS( HistogramWidget::HistogramOptions ) -#endif // __HISTOGRAMWIDGET_H__ +#endif // __HISTOGRAMWIDGET_H__ diff --git a/app/ModuleHandleDock.cpp b/app/ModuleHandleDock.cpp index e39fab2..ca2cc6a 100644 --- a/app/ModuleHandleDock.cpp +++ b/app/ModuleHandleDock.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -27,9 +27,8 @@ #include "PlaYUVerAppModuleIf.h" #include "ModulesHandle.h" -ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ) : - QWidget( parent ), - m_pcCurrModuleIf( moduleIf ) +ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ) + : QWidget( parent ), m_pcCurrModuleIf( moduleIf ) { // ----------------- Dock definition ----------------- @@ -42,7 +41,7 @@ ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* module labelModulueReturnValue = new QLabel; labelModulueReturnValue->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QGridLayout *modulesPropertiesLayout = new QGridLayout; + QGridLayout* modulesPropertiesLayout = new QGridLayout; Int layout_line = 0; modulesPropertiesLayout->addWidget( labelModulueValueLabel, layout_line, 0 ); modulesPropertiesLayout->addWidget( labelModulueReturnValue, layout_line, 1 ); @@ -52,12 +51,10 @@ ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* module setLayout( modulesPropertiesLayout ); setEnabled( true ); - } ModuleHandleDock::~ModuleHandleDock() { - } Void ModuleHandleDock::setModulueReturnValue( Double value ) @@ -86,4 +83,3 @@ QSize ModuleHandleDock::sizeHint() const else return currSize; } - diff --git a/app/ModuleHandleDock.h b/app/ModuleHandleDock.h index 0103451..f86a7a0 100644 --- a/app/ModuleHandleDock.h +++ b/app/ModuleHandleDock.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,10 +36,10 @@ class PlaYUVerAppModuleIf; -class ModuleHandleDock: public QWidget +class ModuleHandleDock : public QWidget { Q_OBJECT - public: + public: ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ); ~ModuleHandleDock(); @@ -47,17 +47,15 @@ class ModuleHandleDock: public QWidget QSize sizeHint() const; -private: - + private: PlaYUVerAppModuleIf* m_pcCurrModuleIf; Bool m_bIsVisible; QLabel* labelModulueValueLabel; QLabel* labelModulueReturnValue; -public Q_SLOTS: + public Q_SLOTS: void visibilityChangedSlot( bool ); - }; -#endif // __MODULEHANDLEDOCK_H__ +#endif // __MODULEHANDLEDOCK_H__ diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index c6798b7..f430c9f 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -32,11 +32,8 @@ #include "ModulesHandleOptDialog.h" #include "modules/PlaYUVerModuleFactory.h" -ModulesHandle::ModulesHandle( QWidget* parent, PlaYUVerSubWindowHandle *windowManager, VideoHandle *moduleVideo ) : - QWidget( parent ), - m_pcParent( parent ), - m_pcMainWindowManager( windowManager ), - m_appModuleVideo( moduleVideo ) +ModulesHandle::ModulesHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager, VideoHandle* moduleVideo ) + : QWidget( parent ), m_pcParent( parent ), m_pcMainWindowManager( windowManager ), m_appModuleVideo( moduleVideo ) { setParent( m_pcParent ); } @@ -50,7 +47,7 @@ Void ModulesHandle::createActions() m_arrayActions.resize( MODULES_TOTAL_ACT ); m_pcActionMapper = new QSignalMapper( this ); - connect( m_pcActionMapper, SIGNAL( mapped(int) ), this, SLOT( processOpt(int) ) ); + connect( m_pcActionMapper, SIGNAL( mapped( int ) ), this, SLOT( processOpt( int ) ) ); // m_arrayActions[FORCE_PLAYING_REFRESH_ACT] = new QAction( "Refresh while playing", parent() ); // m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setStatusTip( "Force module refreshing while playing" ); @@ -77,9 +74,9 @@ Void ModulesHandle::createActions() connect( m_arrayActions[DISABLE_ALL_ACT], SIGNAL( triggered() ), this, SLOT( destroyAllModulesIf() ) ); m_arrayActions[FORCE_NEW_WINDOW_ACT] = new QAction( "Use New Window", parent() ); - m_arrayActions[FORCE_NEW_WINDOW_ACT]->setStatusTip( "Show module result in a new window. Some modules already force this feature" ); + m_arrayActions[FORCE_NEW_WINDOW_ACT]->setStatusTip( + "Show module result in a new window. Some modules already force this feature" ); m_arrayActions[FORCE_NEW_WINDOW_ACT]->setCheckable( true ); - } QMenu* ModulesHandle::createMenu() @@ -155,7 +152,7 @@ Void ModulesHandle::buildMenu() Void ModulesHandle::updateMenus() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcSubWindow ? true : false; QAction* currModuleAction; @@ -209,7 +206,7 @@ Void ModulesHandle::writeSettings() Void ModulesHandle::processOpt( Int index ) { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { PlaYUVerAppModuleIf* pcCurrentModule = pcSubWindow->getDisplayModule(); @@ -218,16 +215,16 @@ Void ModulesHandle::processOpt( Int index ) PlaYUVerAppModuleIf* pcCurrModule = pcCurrentModule; switch( index ) { - case INVALID_OPT: - break; - case SWAP_FRAMES_ACT: - swapModulesWindowsIf( pcCurrModule ); - break; - case APPLY_ALL_ACT: - applyAllModuleIf( pcCurrModule ); - break; - default: - Q_ASSERT( 0 ); + case INVALID_OPT: + break; + case SWAP_FRAMES_ACT: + swapModulesWindowsIf( pcCurrModule ); + break; + case APPLY_ALL_ACT: + applyAllModuleIf( pcCurrModule ); + break; + default: + Q_ASSERT( 0 ); } } emit changed(); @@ -241,10 +238,9 @@ Void ModulesHandle::loadExternalModule() QStringList formatsList; formatsList << "Shared Libraries (*.so)"; QStringList filter; - filter << supported - << formatsList - << tr( "All Files (*)" ); - QStringList fileNames = QFileDialog::getOpenFileNames( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) ); + filter << supported << formatsList << tr( "All Files (*)" ); + QStringList fileNames = + QFileDialog::getOpenFileNames( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) ); for( Int i = 0; i < fileNames.size(); i++ ) { @@ -256,11 +252,11 @@ Void ModulesHandle::loadExternalModule() Void ModulesHandle::activateModule() { - QAction *pcAction = qobject_cast( sender() ); + QAction* pcAction = qobject_cast( sender() ); Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers(); Bool bTmpForceNewWindow = false; - VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( !pcVideoSubWindow ) { return; @@ -272,7 +268,8 @@ Void ModulesHandle::activateModule() } QString ModuleIfName = pcAction->data().toString(); - PlaYUVerModuleIf* pcCurrModuleIf = PlaYUVerModuleFactory::Get()->CreateModule( ModuleIfName.toLocal8Bit().constData() ); + PlaYUVerModuleIf* pcCurrModuleIf = + PlaYUVerModuleFactory::Get()->CreateModule( ModuleIfName.toLocal8Bit().constData() ); PlaYUVerAppModuleIf* pcCurrAppModuleIf = new PlaYUVerAppModuleIf( this, pcAction, pcCurrModuleIf ); QList videoSubWindowList; @@ -286,10 +283,11 @@ Void ModulesHandle::activateModule() minNumFrames = 0; maxNumFrames = 255; } - DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, SubWindowAbstract::VIDEO_SUBWINDOW, minNumFrames, maxNumFrames ); + DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, + SubWindowAbstract::VIDEO_SUBWINDOW, minNumFrames, maxNumFrames ); QList windowsList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); - if( windowsList.size() == minNumFrames && windowsList.size() == maxNumFrames ) + if( windowsList.size() == minNumFrames && windowsList.size() == maxNumFrames ) { for( Int i = 0; i < windowsList.size(); i++ ) { @@ -311,7 +309,7 @@ Void ModulesHandle::activateModule() } if( dialogWindowsSelection.exec() == QDialog::Accepted ) { - VideoSubWindow *videoSubWindow; + VideoSubWindow* videoSubWindow; QList subWindowList = dialogWindowsSelection.getSelectedWindows(); for( Int i = 0; i < subWindowList.size(); i++ ) { @@ -342,7 +340,8 @@ Void ModulesHandle::activateModule() if( videoSubWindowList.size() == 0 ) { - qobject_cast( m_pcParent )->printMessage( "Error! There is no windows to apply the module", LOG_ERROR ); + qobject_cast( m_pcParent ) + ->printMessage( "Error! There is no windows to apply the module", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } @@ -370,16 +369,19 @@ Void ModulesHandle::activateModule() VideoSubWindow* pcModuleSubWindow = NULL; if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == FRAME_PROCESSING_MODULE ) { - if( ( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & MODULE_REQUIRES_NEW_WINDOW ) || bShowModulesNewWindow ) + if( ( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & MODULE_REQUIRES_NEW_WINDOW ) || + bShowModulesNewWindow ) { pcModuleSubWindow = new VideoSubWindow( VideoSubWindow::MODULE_SUBWINDOW ); windowName.append( QStringLiteral( "Module " ) ); windowName.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); - connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), m_appModuleVideo, SLOT( updateSelectionArea( QRect ) ) ); + connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), m_appModuleVideo, + SLOT( updateSelectionArea( QRect ) ) ); connect( pcModuleSubWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, - SLOT( zoomToFactorAll( double, QPoint ) ) ); - connect( pcModuleSubWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, SLOT( moveAllScrollBars( const QPoint ) ) ); + SLOT( zoomToFactorAll( double, QPoint ) ) ); + connect( pcModuleSubWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, + SLOT( moveAllScrollBars( const QPoint ) ) ); pcCurrAppModuleIf->m_pcDisplaySubWindow = pcModuleSubWindow; } @@ -395,7 +397,8 @@ Void ModulesHandle::activateModule() pcCurrAppModuleIf->m_pcDockWidget->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable ); pcCurrAppModuleIf->m_pcDockWidget->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); pcCurrAppModuleIf->m_pcDockWidget->setWidget( pcCurrAppModuleIf->m_pcModuleDock ); - qobject_cast( m_pcParent )->addDockWidget( Qt::RightDockWidgetArea, pcCurrAppModuleIf->m_pcDockWidget ); + qobject_cast( m_pcParent ) + ->addDockWidget( Qt::RightDockWidgetArea, pcCurrAppModuleIf->m_pcDockWidget ); } // Associate module with subwindows @@ -459,7 +462,7 @@ Void ModulesHandle::activateModule() emit changed(); } -Void ModulesHandle::destroyModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) +Void ModulesHandle::destroyModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) { if( pcCurrModuleIf ) { @@ -469,7 +472,7 @@ Void ModulesHandle::destroyModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) Void ModulesHandle::destroyWindowModules() { - VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcVideoSubWindow ) { pcVideoSubWindow->disableModule(); @@ -494,7 +497,7 @@ Void ModulesHandle::applyModuleIf( QList pcCurrModuleIfLis } } -Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) +Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) { if( pcCurrModuleIf ) { @@ -521,9 +524,7 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) supported.append( " )" ); QStringList filter; - filter << supported - << formatsList - << tr( "All Files (*)" ); + filter << supported << formatsList << tr( "All Files (*)" ); QString fileName = QFileDialog::getSaveFileName( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) ); @@ -534,7 +535,8 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate(); pcCurrModuleIf->m_pcModuleStream = new PlaYUVerStream; - if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, PLAYUVER_LITTLE_ENDIAN, FrameRate, false ) ) + if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, + PLAYUVER_LITTLE_ENDIAN, FrameRate, false ) ) { delete pcCurrModuleIf->m_pcModuleStream; pcCurrModuleIf->m_pcModuleStream = NULL; @@ -574,7 +576,7 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) } } -Void ModulesHandle::swapModulesWindowsIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) +Void ModulesHandle::swapModulesWindowsIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) { if( pcCurrModuleIf->m_pcModule->m_uiNumberOfFrames == MODULE_REQUIRES_TWO_FRAMES ) { @@ -585,16 +587,15 @@ Void ModulesHandle::swapModulesWindowsIf( PlaYUVerAppModuleIf *pcCurrModuleIf ) } } -Void ModulesHandle::customEvent( QEvent *event ) +Void ModulesHandle::customEvent( QEvent* event ) { if( !event ) { return; } - PlaYUVerAppModuleIf::EventData *eventData = ( PlaYUVerAppModuleIf::EventData* )event; + PlaYUVerAppModuleIf::EventData* eventData = (PlaYUVerAppModuleIf::EventData*)event; if( eventData->m_bSuccess ) { eventData->m_pcModule->show(); } } - diff --git a/app/ModulesHandle.h b/app/ModulesHandle.h index 9b98540..aebd565 100644 --- a/app/ModulesHandle.h +++ b/app/ModulesHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -44,16 +44,16 @@ class PlaYUVerSubWindowHandle; class PlaYUVerAppModuleIf; class SubWindowHandle; -class ModulesHandle: public QWidget +class ModulesHandle : public QWidget { -Q_OBJECT - public: + Q_OBJECT + public: ModulesHandle( QWidget*, PlaYUVerSubWindowHandle*, VideoHandle* ); ~ModulesHandle(); Void createActions(); QMenu* createMenu(); - //QDockWidget* createDock(); + // QDockWidget* createDock(); Void buildMenu(); Void updateMenus(); @@ -61,9 +61,11 @@ Q_OBJECT Void writeSettings(); static Void destroyModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ); - static Void applyModuleIf( QList pcCurrModuleIfList, Bool isPlaying = false, Bool disableThreads = false ); + static Void applyModuleIf( QList pcCurrModuleIfList, + Bool isPlaying = false, + Bool disableThreads = false ); -private: + private: QWidget* m_pcParent; PlaYUVerSubWindowHandle* m_pcMainWindowManager; VideoHandle* m_appModuleVideo; @@ -84,7 +86,7 @@ private: enum MODULES_ACTION_LIST { LOAD_EXTERNAL_ACT, - //FORCE_PLAYING_REFRESH_ACT, + // FORCE_PLAYING_REFRESH_ACT, APPLY_ALL_ACT, SWAP_FRAMES_ACT, DISABLE_ACT, @@ -97,21 +99,19 @@ private: Void enableModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ); Void applyAllModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ); - Void swapModulesWindowsIf( PlaYUVerAppModuleIf *pcCurrModuleIf ); + Void swapModulesWindowsIf( PlaYUVerAppModuleIf* pcCurrModuleIf ); - Void customEvent( QEvent *event ); + Void customEvent( QEvent* event ); -Q_SIGNALS: + Q_SIGNALS: void changed(); -private Q_SLOTS: + private Q_SLOTS: void loadExternalModule(); void activateModule(); void processOpt( int index ); void destroyWindowModules(); void destroyAllModulesIf(); - }; -#endif // __MODULESHANDLE_H__ - +#endif // __MODULESHANDLE_H__ diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index 94a9530..fecb4fe 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -32,9 +32,9 @@ #include "lib/PlaYUVerOptions.h" -class OpionConfiguration: public QWidget +class OpionConfiguration : public QWidget { -public: + public: OpionConfiguration( OptionBase* option ) { m_pcChecked = NULL; @@ -67,20 +67,16 @@ public: } return m_pcValue->text(); } - const String& getName() - { - return m_cName; - } -private: + const String& getName() { return m_cName; } + private: QLineEdit* m_pcValue; QCheckBox* m_pcChecked; QLabel* m_pcDescription; String m_cName; }; -ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget *parent, PlaYUVerAppModuleIf *pcCurrModuleIf ) : - QDialog( parent ), - m_pcCurrModuleIf( pcCurrModuleIf ) +ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget* parent, PlaYUVerAppModuleIf* pcCurrModuleIf ) + : QDialog( parent ), m_pcCurrModuleIf( pcCurrModuleIf ) { resize( 400, 10 ); setWindowTitle( "Select module parameters" ); @@ -145,4 +141,3 @@ Int ModulesHandleOptDialog::runConfiguration() } return QDialog::Accepted; } - diff --git a/app/ModulesHandleOptDialog.h b/app/ModulesHandleOptDialog.h index e20ca7f..48973ca 100644 --- a/app/ModulesHandleOptDialog.h +++ b/app/ModulesHandleOptDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,16 +36,17 @@ class OpionConfiguration; /** * */ -class ModulesHandleOptDialog: public QDialog +class ModulesHandleOptDialog : public QDialog { -Q_OBJECT + Q_OBJECT -public: - ModulesHandleOptDialog( QWidget *parent, PlaYUVerAppModuleIf *pcCurrModuleIf ); + public: + ModulesHandleOptDialog( QWidget* parent, PlaYUVerAppModuleIf* pcCurrModuleIf ); Int runConfiguration(); - private: - PlaYUVerAppModuleIf *m_pcCurrModuleIf; + + private: + PlaYUVerAppModuleIf* m_pcCurrModuleIf; QVector m_apcOptionList; }; -#endif // __MODULEHANDLEOPTDIALOG_H__ +#endif // __MODULEHANDLEOPTDIALOG_H__ diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index ad25214..6b018c7 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -46,16 +46,12 @@ #define SYNCHRONISED_ZOON 1 -PlaYUVerApp::PlaYUVerApp() : - m_pcCurrentSubWindow( NULL ), - m_pcCurrentVideoSubWindow( NULL ), - m_pcAboutDialog( NULL ) +PlaYUVerApp::PlaYUVerApp() : m_pcCurrentSubWindow( NULL ), m_pcCurrentVideoSubWindow( NULL ), m_pcAboutDialog( NULL ) { - setWindowModality( Qt::ApplicationModal ); setWindowModality( Qt::NonModal ); - // DBus +// DBus #ifdef USE_QTDBUS m_pDBusAdaptor = new PlaYUVerAppAdaptor( this ); #endif @@ -87,10 +83,9 @@ PlaYUVerApp::PlaYUVerApp() : connect( m_appModuleVideo, SIGNAL( changed() ), this, SLOT( update() ) ); connect( m_appModuleQuality, SIGNAL( changed() ), this, SLOT( update() ) ); connect( m_appModuleExtensions, SIGNAL( changed() ), this, SLOT( update() ) ); - } -Bool PlaYUVerApp::parseArgs( Int argc, Char *argv[] ) +Bool PlaYUVerApp::parseArgs( Int argc, Char* argv[] ) { Bool bRet = false; PlaYUVerOptions pcCmdParser; @@ -99,10 +94,10 @@ Bool PlaYUVerApp::parseArgs( Int argc, Char *argv[] ) String strResolution( "" ); String strPelFmt( "" ); - pcCmdParser.addOptions()/**/ - ( "input,i", m_apcInputs, "input file" ) /**/ - ( "size,s", strResolution, "size (WxH)" ) /**/ - ( "pel_fmt", strPelFmt, "pixel format" ); + pcCmdParser.addOptions() /**/ + ( "input,i", m_apcInputs, "input file" ) /**/ + ( "size,s", strResolution, "size (WxH)" ) /**/ + ( "pel_fmt", strPelFmt, "pixel format" ); if( !pcCmdParser.parse( argc, argv ) ) { @@ -139,7 +134,7 @@ Void PlaYUVerApp::about() m_pcAboutDialog->exec(); } -Void PlaYUVerApp::closeEvent( QCloseEvent *event ) +Void PlaYUVerApp::closeEvent( QCloseEvent* event ) { Int mayCloseAll = true; Int msgBoxCloseRet = QMessageBox::Yes; @@ -147,35 +142,36 @@ Void PlaYUVerApp::closeEvent( QCloseEvent *event ) QList subWindowList = m_pcWindowHandle->findSubWindow(); if( subWindowList.size() >= 1 ) { - QMessageBox msgBoxClose( QMessageBox::Question, "PlaYUVer", "There are open files!", QMessageBox::Yes | QMessageBox::No, this ); + QMessageBox msgBoxClose( QMessageBox::Question, "PlaYUVer", "There are open files!", + QMessageBox::Yes | QMessageBox::No, this ); msgBoxClose.setDefaultButton( QMessageBox::No ); msgBoxClose.setInformativeText( "Close all?" ); msgBoxCloseRet = msgBoxClose.exec(); } switch( msgBoxCloseRet ) { - case QMessageBox::Yes: - mayCloseAll = true; - for( Int i = 0; i < subWindowList.size(); i++ ) - { - mayCloseAll &= subWindowList.at( i )->mayClose(); - } + case QMessageBox::Yes: + mayCloseAll = true; + for( Int i = 0; i < subWindowList.size(); i++ ) + { + mayCloseAll &= subWindowList.at( i )->mayClose(); + } - if( mayCloseAll ) - { - //m_pcPlayingTimer->stop(); - closeAll(); - writeSettings(); - event->accept(); - } - else - { - event->ignore(); - } - break; - case QMessageBox::No: + if( mayCloseAll ) + { + // m_pcPlayingTimer->stop(); + closeAll(); + writeSettings(); + event->accept(); + } + else + { + event->ignore(); + } + break; + case QMessageBox::No: default: - event->ignore(); + event->ignore(); } } @@ -191,18 +187,18 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) printMessage( "File " + fileName + " do not exist!", LOG_ERROR ); return; } - VideoSubWindow *videoSubWindow = PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); + VideoSubWindow* videoSubWindow = PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); if( videoSubWindow ) { m_pcWindowHandle->setActiveSubWindow( videoSubWindow ); return; } - videoSubWindow = new VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW ); //createSubWindow(); - SubWindowAbstract *subWindow = videoSubWindow; + videoSubWindow = new VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW ); // createSubWindow(); + SubWindowAbstract* subWindow = videoSubWindow; if( !pStreamInfo ) { Int idx = findPlaYUVerStreamInfo( m_aRecentFileStreamInfo, fileName ); - pStreamInfo = ( PlaYUVerStreamInfo* )( idx >= 0 ? &m_aRecentFileStreamInfo.at( idx ) : NULL ); + pStreamInfo = (PlaYUVerStreamInfo*)( idx >= 0 ? &m_aRecentFileStreamInfo.at( idx ) : NULL ); } try @@ -220,9 +216,12 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) m_pcWindowHandle->addSubWindow( videoSubWindow ); videoSubWindow->show(); - connect( subWindow, SIGNAL( aboutToClose( SubWindowAbstract* ) ), m_appModuleVideo, SLOT( closeSubWindow( SubWindowAbstract* ) ) ); - connect( subWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, SLOT( zoomToFactorAll( double, QPoint ) ) ); - connect( subWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, SLOT( moveAllScrollBars( const QPoint ) ) ); + connect( subWindow, SIGNAL( aboutToClose( SubWindowAbstract* ) ), m_appModuleVideo, + SLOT( closeSubWindow( SubWindowAbstract* ) ) ); + connect( subWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, + SLOT( zoomToFactorAll( double, QPoint ) ) ); + connect( subWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, + SLOT( moveAllScrollBars( const QPoint ) ) ); videoSubWindow->zoomToFit(); updateZoomFactorSBox(); @@ -242,7 +241,8 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) catch( PlaYUVerFailure& e ) { videoSubWindow->close(); - QString warningMsg = "Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); + QString warningMsg = + "Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); } @@ -270,11 +270,10 @@ Void PlaYUVerApp::open() supported.append( " )" ); QStringList filter; - filter << supported - << formatsList - << tr( "All Files (*)" ); + filter << supported << formatsList << tr( "All Files (*)" ); - QStringList fileNameList = QFileDialog::getOpenFileNames( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); + QStringList fileNameList = + QFileDialog::getOpenFileNames( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); for( Int i = 0; i < fileNameList.size(); i++ ) { @@ -287,7 +286,7 @@ Void PlaYUVerApp::open() Void PlaYUVerApp::openRecent() { - QAction *action = qobject_cast( sender() ); + QAction* action = qobject_cast( sender() ); PlaYUVerStreamInfo recentFile = action->data().value(); if( action ) loadFile( recentFile.m_cFilename, &recentFile ); @@ -297,7 +296,7 @@ Void PlaYUVerApp::save() { if( m_pcCurrentVideoSubWindow ) { - VideoSubWindow *saveWindow = m_pcCurrentVideoSubWindow; + VideoSubWindow* saveWindow = m_pcCurrentVideoSubWindow; QString supported = tr( "Supported Files (" ); QStringList formatsList; @@ -316,9 +315,7 @@ Void PlaYUVerApp::save() supported.append( " )" ); QStringList filter; - filter << supported - << formatsList - << tr( "All Files (*)" ); + filter << supported << formatsList << tr( "All Files (*)" ); QString fileName = QFileDialog::getSaveFileName( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); @@ -332,7 +329,8 @@ Void PlaYUVerApp::save() catch( PlaYUVerFailure& e ) { QApplication::restoreOverrideCursor(); - QString warningMsg = "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); + QString warningMsg = + "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); return; @@ -355,10 +353,11 @@ Void PlaYUVerApp::format() } catch( PlaYUVerFailure& e ) { - QString warningMsg = "Cannot change format of " + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + " with the following error: \n" + e.what(); + QString warningMsg = "Cannot change format of " + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); - qDebug( ) << warningMsg; + qDebug() << warningMsg; m_pcCurrentSubWindow->close(); } m_pcCurrentSubWindow = NULL; @@ -378,12 +377,10 @@ Void PlaYUVerApp::reload() Void PlaYUVerApp::reloadAll() { - UInt windowCategoryOrder[] = - { - SubWindowAbstract::VIDEO_STREAM_SUBWINDOW, - SubWindowAbstract::MODULE_SUBWINDOW, - SubWindowAbstract::MODULE_SUBWINDOW, - }; + UInt windowCategoryOrder[] = { + SubWindowAbstract::VIDEO_STREAM_SUBWINDOW, SubWindowAbstract::MODULE_SUBWINDOW, + SubWindowAbstract::MODULE_SUBWINDOW, + }; for( UInt c = 0; c < 3; c++ ) { @@ -429,13 +426,12 @@ Void PlaYUVerApp::zoomToFit() Void PlaYUVerApp::zoomToFitAll() { - VideoSubWindow *videoSubWindow; + VideoSubWindow* videoSubWindow; QList subWindowList = m_pcWindowHandle->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { videoSubWindow = qobject_cast( subWindowList.at( i ) ); videoSubWindow->zoomToFit(); - } if( m_pcCurrentSubWindow ) updateZoomFactorSBox(); @@ -452,7 +448,7 @@ Void PlaYUVerApp::scaleFrame( int ratio ) Void PlaYUVerApp::zoomFromSBox( double zoom ) { - SubWindowAbstract *activeSubWindow = m_pcWindowHandle->activeSubWindow(); + SubWindowAbstract* activeSubWindow = m_pcWindowHandle->activeSubWindow(); Double factor = zoom / 100; if( activeSubWindow ) { @@ -472,16 +468,16 @@ Void PlaYUVerApp::updateZoomFactorSBox() // ----------------------- Drag and drop functions ---------------------- -Void PlaYUVerApp::dragEnterEvent( QDragEnterEvent *event ) +Void PlaYUVerApp::dragEnterEvent( QDragEnterEvent* event ) { - //setText(tr("")); - //mdiArea->setBackgroundRole( QPalette::Highlight ); + // setText(tr("")); + // mdiArea->setBackgroundRole( QPalette::Highlight ); event->acceptProposedAction(); } -Void PlaYUVerApp::dropEvent( QDropEvent *event ) +Void PlaYUVerApp::dropEvent( QDropEvent* event ) { - const QMimeData *mimeData = event->mimeData(); + const QMimeData* mimeData = event->mimeData(); QList urlList = mimeData->urls(); if( urlList.size() == 1 ) { @@ -493,7 +489,8 @@ Void PlaYUVerApp::dropEvent( QDropEvent *event ) // ----------------------- Sub Window Functions ----------------------- -VideoSubWindow* PlaYUVerApp::findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, const QString& fileName ) +VideoSubWindow* PlaYUVerApp::findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, + const QString& fileName ) { QString canonicalFilePath = QFileInfo( fileName ).canonicalFilePath(); VideoSubWindow* pcSubWindow; @@ -511,9 +508,9 @@ VideoSubWindow* PlaYUVerApp::findVideoStreamSubWindow( const PlaYUVerSubWindowHa Void PlaYUVerApp::update() { - SubWindowAbstract *activeSubWindow = m_pcWindowHandle->activeSubWindow(); + SubWindowAbstract* activeSubWindow = m_pcWindowHandle->activeSubWindow(); QCoreApplication::processEvents(); -//if( activeSubWindow() != m_pcCurrentSubWindow ) + // if( activeSubWindow() != m_pcCurrentSubWindow ) { m_pcCurrentSubWindow = NULL; m_pcCurrentVideoSubWindow = NULL; @@ -656,7 +653,7 @@ Void PlaYUVerApp::createActions() // ------------ View ------------ mapperZoom = new QSignalMapper( this ); - connect( mapperZoom, SIGNAL( mapped(int) ), this, SLOT( scaleFrame(int) ) ); + connect( mapperZoom, SIGNAL( mapped( int ) ), this, SLOT( scaleFrame( int ) ) ); m_arrayActions[ZOOM_IN_ACT] = new QAction( tr( "Zoom &In (+25%)" ), this ); m_arrayActions[ZOOM_IN_ACT]->setIcon( QIcon::fromTheme( "zoom-in", QIcon( ":/images/zoomin.png" ) ) ); @@ -684,7 +681,8 @@ Void PlaYUVerApp::createActions() connect( m_arrayActions[ZOOM_FIT_ACT], SIGNAL( triggered() ), this, SLOT( zoomToFit() ) ); m_arrayActions[ZOOM_FIT_ALL_ACT] = new QAction( tr( "Zoom to Fit All" ), this ); -//m_arrayActions[ZOOM_FIT_ALL_ACT]->setIcon( QIcon::fromTheme( "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) ); + // m_arrayActions[ZOOM_FIT_ALL_ACT]->setIcon( QIcon::fromTheme( "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) + // ); m_arrayActions[ZOOM_FIT_ALL_ACT]->setStatusTip( tr( "Apply zoom to fit to all windows" ) ); connect( m_arrayActions[ZOOM_FIT_ALL_ACT], SIGNAL( triggered() ), this, SLOT( zoomToFitAll() ) ); @@ -698,7 +696,8 @@ Void PlaYUVerApp::createActions() #ifdef USE_FERVOR m_arrayActions[UPDATE_ACT] = new QAction( tr( "&Update" ), this ); m_arrayActions[UPDATE_ACT]->setStatusTip( tr( "Check for updates" ) ); - connect( m_arrayActions[UPDATE_ACT], SIGNAL( triggered() ), FvUpdater::sharedUpdater(), SLOT( CheckForUpdatesNotSilent() ) ); + connect( m_arrayActions[UPDATE_ACT], SIGNAL( triggered() ), FvUpdater::sharedUpdater(), + SLOT( CheckForUpdatesNotSilent() ) ); #endif m_arrayActions[ABOUT_ACT] = new QAction( tr( "&About" ), this ); @@ -742,12 +741,12 @@ Void PlaYUVerApp::createMenus() m_arrayMenu[VIEW_MENU]->addSeparator(); -// createPopupMenu() Returns a popup menu containing checkable entries for -// the toolbars and dock widgets present in the main window. + // createPopupMenu() Returns a popup menu containing checkable entries for + // the toolbars and dock widgets present in the main window. m_arrayMenu[DOCK_VIEW_MENU] = createPopupMenu(); if( m_arrayMenu[DOCK_VIEW_MENU] ) { - QAction *actionPopupMenu = m_arrayMenu[VIEW_MENU]->addMenu( m_arrayMenu[DOCK_VIEW_MENU] ); + QAction* actionPopupMenu = m_arrayMenu[VIEW_MENU]->addMenu( m_arrayMenu[DOCK_VIEW_MENU] ); actionPopupMenu->setText( tr( "&Toolbars/Docks" ) ); } @@ -769,7 +768,6 @@ Void PlaYUVerApp::createMenus() m_arrayMenu[ABOUT_MENU]->addSeparator(); m_arrayMenu[ABOUT_MENU]->addAction( m_arrayActions[ABOUT_ACT] ); m_arrayMenu[ABOUT_MENU]->addAction( m_arrayActions[ABOUTQT_ACT] ); - } Void PlaYUVerApp::createToolBars() @@ -793,7 +791,7 @@ Void PlaYUVerApp::createToolBars() m_pcZoomFactorSBox->setSingleStep( 10.0 ); m_pcZoomFactorSBox->setValue( 100.0 ); m_pcZoomFactorSBox->setSuffix( "%" ); - connect( m_pcZoomFactorSBox, SIGNAL( valueChanged(double) ), this, SLOT( zoomFromSBox(double) ) ); + connect( m_pcZoomFactorSBox, SIGNAL( valueChanged( double ) ), this, SLOT( zoomFromSBox( double ) ) ); m_arrayToolBars[VIEW_TOOLBAR]->addWidget( m_pcZoomFactorSBox ); m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_IN_ACT] ); m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_OUT_ACT] ); @@ -804,12 +802,11 @@ Void PlaYUVerApp::createToolBars() addToolBar( Qt::TopToolBarArea, m_arrayToolBars[VIEW_TOOLBAR] ); addToolBar( Qt::TopToolBarArea, m_appModuleVideo->createToolBar() ); - } Void PlaYUVerApp::createDockWidgets() { -// Properties Dock Window + // Properties Dock Window m_arraySideBars.resize( TOTAL_DOCK ); addDockWidget( Qt::RightDockWidgetArea, m_appModuleVideo->createDock() ); addDockWidget( Qt::RightDockWidgetArea, m_appModuleQuality->createDock() ); @@ -844,7 +841,8 @@ Void PlaYUVerApp::updateRecentFileActions() m_arrayRecentFilesActions.at( actionIdx )->setText( QFileInfo( text ).fileName() ); m_arrayRecentFilesActions.at( actionIdx )->setToolTip( "Open File " + text ); m_arrayRecentFilesActions.at( actionIdx )->setStatusTip( "Open File " + text ); - m_arrayRecentFilesActions.at( actionIdx )->setData( QVariant::fromValue( m_aRecentFileStreamInfo.at( actionIdx ) ) ); + m_arrayRecentFilesActions.at( actionIdx ) + ->setData( QVariant::fromValue( m_aRecentFileStreamInfo.at( actionIdx ) ) ); m_arrayRecentFilesActions.at( actionIdx )->setVisible( true ); actionIdx++; } @@ -918,4 +916,3 @@ Void PlaYUVerApp::writeSettings() m_appModuleExtensions->writeSettings(); m_pcWindowHandle->writeSettings(); } - diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 6030c42..996ea2e 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -65,23 +65,23 @@ class VideoSubWindow; class SubWindowAbstract; class AboutDialog; -class PlaYUVerApp: public QMainWindow +class PlaYUVerApp : public QMainWindow { -Q_OBJECT + Q_OBJECT -public: + public: PlaYUVerApp(); - Bool parseArgs( Int argc, Char *argv[] ); + Bool parseArgs( Int argc, Char* argv[] ); Void loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo = NULL ); -public Q_SLOTS: + public Q_SLOTS: void printMessage( const QString& msg ); void printMessage( const QString& msg, UInt logLevel ); -protected: - Void closeEvent( QCloseEvent *event ); + protected: + Void closeEvent( QCloseEvent* event ); -private Q_SLOTS: + private Q_SLOTS: void about(); @@ -108,14 +108,13 @@ private Q_SLOTS: void zoomToFit(); void zoomToFitAll(); - void dragEnterEvent( QDragEnterEvent *event ); - void dropEvent( QDropEvent *event ); + void dragEnterEvent( QDragEnterEvent* event ); + void dropEvent( QDropEvent* event ); void update(); void updateZoomFactorSBox(); -private: - + private: PlaYUVerAppAdaptor* m_pDBusAdaptor; PlaYUVerOptions* m_pcCmdParser; /** @@ -126,7 +125,8 @@ private: QString m_cLastOpenPath; - static VideoSubWindow* findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, const QString& fileName ); + static VideoSubWindow* findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, + const QString& fileName ); Void updateMenus(); @@ -143,10 +143,10 @@ private: Void readSettings(); Void writeSettings(); - QDoubleSpinBox *m_pcZoomFactorSBox; + QDoubleSpinBox* m_pcZoomFactorSBox; - QSignalMapper *mapperZoom; - QSignalMapper *mapperWindow; + QSignalMapper* mapperZoom; + QSignalMapper* mapperWindow; /** * App modules @@ -156,7 +156,7 @@ private: */ VideoHandle* m_appModuleVideo; QualityHandle* m_appModuleQuality; - ModulesHandle *m_appModuleExtensions; + ModulesHandle* m_appModuleExtensions; PlaYUVerSubWindowHandle* m_pcWindowHandle; /** @@ -234,5 +234,4 @@ private: AboutDialog* m_pcAboutDialog; }; -#endif // __PLAYUVERAPP_H__ - +#endif // __PLAYUVERAPP_H__ diff --git a/app/PlaYUVerAppAdaptor.cpp b/app/PlaYUVerAppAdaptor.cpp index dd5b795..806089a 100644 --- a/app/PlaYUVerAppAdaptor.cpp +++ b/app/PlaYUVerAppAdaptor.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -26,12 +26,11 @@ #include "PlaYUVerAppAdaptor.h" #include "PlaYUVerApp.h" -PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp *app ) : - QDBusAbstractAdaptor( app ), - m_app( app ) +PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp* app ) : QDBusAbstractAdaptor( app ), m_app( app ) { // application dbus interface - QDBusConnection::sessionBus().registerObject( QStringLiteral( PLAYUVER_DBUS_PATH ), this, QDBusConnection::ExportAllSlots ); + QDBusConnection::sessionBus().registerObject( QStringLiteral( PLAYUVER_DBUS_PATH ), this, + QDBusConnection::ExportAllSlots ); } PlaYUVerAppAdaptor::~PlaYUVerAppAdaptor() @@ -46,12 +45,11 @@ void PlaYUVerAppAdaptor::activate() return; } m_app->raise(); - } QString PlaYUVerAppAdaptor::activeSession() { - //return m_app->sessionManager()->activeSession()->name(); + // return m_app->sessionManager()->activeSession()->name(); return QString( "PlaYUVer" ); } @@ -60,4 +58,3 @@ bool PlaYUVerAppAdaptor::loadFile( const QString& filename ) m_app->loadFile( filename ); return true; } - diff --git a/app/PlaYUVerAppAdaptor.h b/app/PlaYUVerAppAdaptor.h index a4e9779..8853485 100644 --- a/app/PlaYUVerAppAdaptor.h +++ b/app/PlaYUVerAppAdaptor.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -37,20 +37,20 @@ class PlaYUVerApp; -class PlaYUVerAppAdaptor: public QDBusAbstractAdaptor +class PlaYUVerAppAdaptor : public QDBusAbstractAdaptor { -Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.pixlra.PlaYUVer.application") -Q_PROPERTY(QString activeSession READ activeSession) -public: - PlaYUVerAppAdaptor( PlaYUVerApp *app ); + Q_OBJECT + Q_CLASSINFO( "D-Bus Interface", "org.pixlra.PlaYUVer.application" ) + Q_PROPERTY( QString activeSession READ activeSession ) + public: + PlaYUVerAppAdaptor( PlaYUVerApp* app ); ~PlaYUVerAppAdaptor(); /** * emit the exiting signal */ - //void emitExiting(); - //void emitDocumentClosed(const QString &token); -public Q_SLOTS: + // void emitExiting(); + // void emitDocumentClosed(const QString &token); + public Q_SLOTS: /** * open a file with given url and encoding * will get view created @@ -65,18 +65,18 @@ public Q_SLOTS: */ void activate(); -Q_SIGNALS: + Q_SIGNALS: /** * Notify the world that this kate instance is exiting. * All apps should stop using the dbus interface of this instance after this signal got emitted. */ - //void exiting(); - //void documentClosed(const QString &token); -public: + // void exiting(); + // void documentClosed(const QString &token); + public: QString activeSession(); - private: - PlaYUVerApp *m_app; + + private: + PlaYUVerApp* m_app; }; -#endif // __PlaYUVerAppAdaptor_H__ - +#endif // __PlaYUVerAppAdaptor_H__ diff --git a/app/PlaYUVerAppDefs.h b/app/PlaYUVerAppDefs.h index 48a86af..656ce56 100644 --- a/app/PlaYUVerAppDefs.h +++ b/app/PlaYUVerAppDefs.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -35,7 +35,7 @@ // fallback, return a temporary QString // source code is assumed to be encoded in UTF-8 -# define QStringLiteral(str) QString::fromUtf8("" str "", sizeof(str) - 1) +#define QStringLiteral( str ) QString::fromUtf8( "" str "", sizeof( str ) - 1 ) #endif -#endif // __PLAYUVERAPPDEFS_H__ +#endif // __PLAYUVERAPPDEFS_H__ diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index fb4d85e..5d334a6 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -26,16 +26,16 @@ #include "VideoSubWindow.h" #include "VideoSubWindow.h" -PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ) : - m_bIsRunning( false ), - m_pcModuleAction( action ), - m_pcModule( module ), - m_pcDisplaySubWindow( NULL ), - m_pcDockWidget( NULL ), - m_pcModuleDock( NULL ), - m_pcModuleStream( NULL ), - m_pcProcessedFrame( NULL ), - m_dMeasurementResult( 0 ) +PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ) + : m_bIsRunning( false ), + m_pcModuleAction( action ), + m_pcModule( module ), + m_pcDisplaySubWindow( NULL ), + m_pcDockWidget( NULL ), + m_pcModuleDock( NULL ), + m_pcModuleStream( NULL ), + m_pcProcessedFrame( NULL ), + m_dMeasurementResult( 0 ) { setParent( parent ); for( Int i = 0; i < MODULE_REQUIRES_MAX_NUM_FRAMES; i++ ) @@ -139,9 +139,9 @@ Void PlaYUVerAppModuleIf::run() m_bSuccess = true; m_bIsRunning = false; #ifdef PLAYUVER_THREADED_MODULES - EventData *eventData = new EventData( m_bSuccess, this ); + EventData* eventData = new EventData( m_bSuccess, this ); if( parent() ) - QCoreApplication::postEvent( parent(), eventData ); + QCoreApplication::postEvent( parent(), eventData ); #endif return; } @@ -150,23 +150,23 @@ Void PlaYUVerAppModuleIf::show() { switch( m_pcModule->m_iModuleType ) { - case FRAME_PROCESSING_MODULE: - if( m_pcDisplaySubWindow ) - { - m_pcDisplaySubWindow->setCurrFrame( m_pcProcessedFrame ); - m_pcDisplaySubWindow->setFillWindow( false ); - m_pcDisplaySubWindow->clearWindowBusy(); - } - else - { - m_pcSubWindow[0]->setCurrFrame( m_pcProcessedFrame ); - m_pcSubWindow[0]->setFillWindow( false ); - m_pcSubWindow[0]->clearWindowBusy(); - } - break; - case FRAME_MEASUREMENT_MODULE: - m_pcModuleDock->setModulueReturnValue( m_dMeasurementResult ); - break; + case FRAME_PROCESSING_MODULE: + if( m_pcDisplaySubWindow ) + { + m_pcDisplaySubWindow->setCurrFrame( m_pcProcessedFrame ); + m_pcDisplaySubWindow->setFillWindow( false ); + m_pcDisplaySubWindow->clearWindowBusy(); + } + else + { + m_pcSubWindow[0]->setCurrFrame( m_pcProcessedFrame ); + m_pcSubWindow[0]->setFillWindow( false ); + m_pcSubWindow[0]->clearWindowBusy(); + } + break; + case FRAME_MEASUREMENT_MODULE: + m_pcModuleDock->setModulueReturnValue( m_dMeasurementResult ); + break; } } @@ -214,6 +214,4 @@ Void PlaYUVerAppModuleIf::destroy() m_pcModule->Delete(); m_pcModule = NULL; } - } - diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index 7536f18..c5dbc9a 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -42,7 +42,7 @@ class QAction; class VideoSubWindow; class PlaYUVerAppModuleIf - #ifdef PLAYUVER_THREADED_MODULES +#ifdef PLAYUVER_THREADED_MODULES : public QThread #else : public QObject @@ -52,8 +52,7 @@ class PlaYUVerAppModuleIf friend class ModuleHandleDock; friend class ModulesHandleOptDialog; -private: - + private: Bool m_bIsRunning; Bool m_bSuccess; @@ -71,12 +70,11 @@ private: PlaYUVerFrame* m_pcProcessedFrame; Double m_dMeasurementResult; -public: - class EventData: public QEvent + public: + class EventData : public QEvent { - public: - EventData( bool success, PlaYUVerAppModuleIf* module ) : - QEvent( QEvent::User ) + public: + EventData( bool success, PlaYUVerAppModuleIf* module ) : QEvent( QEvent::User ) { m_bSuccess = success; m_pcModule = module; @@ -86,10 +84,7 @@ public: }; PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ); - virtual ~PlaYUVerAppModuleIf() - { - } - + virtual ~PlaYUVerAppModuleIf() {} QList getSubWindowList() { QList arraySubWindows; @@ -99,23 +94,15 @@ public: return arraySubWindows; } - PlaYUVerModuleIf* getModule() - { - return m_pcModule; - } - - UInt getModuleRequirements() - { - return m_pcModule->m_uiModuleRequirements; - } - + PlaYUVerModuleIf* getModule() { return m_pcModule; } + UInt getModuleRequirements() { return m_pcModule->m_uiModuleRequirements; } Void update(); Bool apply( Bool isPlaying = false, Bool disableThreads = false ); Void show(); Void destroy(); - protected: + + protected: virtual void run(); }; -#endif // __PLAYUVERAPPMODULESIF_H__ - +#endif // __PLAYUVERAPPMODULESIF_H__ diff --git a/app/PlaYUVerMdiSubWindow.cpp b/app/PlaYUVerMdiSubWindow.cpp index d30c06f..efac05e 100644 --- a/app/PlaYUVerMdiSubWindow.cpp +++ b/app/PlaYUVerMdiSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -26,8 +26,7 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" -PlaYUVerMdiSubWindow::PlaYUVerMdiSubWindow( QWidget *parent ) : - QMdiSubWindow( parent ) +PlaYUVerMdiSubWindow::PlaYUVerMdiSubWindow( QWidget* parent ) : QMdiSubWindow( parent ) { setAttribute( Qt::WA_DeleteOnClose ); setBackgroundRole( QPalette::Background ); @@ -42,9 +41,8 @@ QSize PlaYUVerMdiSubWindow::sizeHint() const return sizeHint; } -Void PlaYUVerMdiSubWindow::closeEvent( QCloseEvent *event ) +Void PlaYUVerMdiSubWindow::closeEvent( QCloseEvent* event ) { emit aboutToClose( this ); event->accept(); } - diff --git a/app/PlaYUVerMdiSubWindow.h b/app/PlaYUVerMdiSubWindow.h index 440225a..6a74a4a 100644 --- a/app/PlaYUVerMdiSubWindow.h +++ b/app/PlaYUVerMdiSubWindow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -29,20 +29,19 @@ #include "PlaYUVerAppDefs.h" #include -class PlaYUVerMdiSubWindow: public QMdiSubWindow +class PlaYUVerMdiSubWindow : public QMdiSubWindow { -Q_OBJECT + Q_OBJECT -public: - PlaYUVerMdiSubWindow( QWidget *parent = 0 ); + public: + PlaYUVerMdiSubWindow( QWidget* parent = 0 ); -Q_SIGNALS: + Q_SIGNALS: void aboutToClose( PlaYUVerMdiSubWindow* ); -protected: + protected: QSize sizeHint() const; - void closeEvent( QCloseEvent *event ); + void closeEvent( QCloseEvent* event ); }; -#endif // __PLAYUVERMDISUBWINDOW_H__ - +#endif // __PLAYUVERMDISUBWINDOW_H__ diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index 78850ce..e351e12 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -40,12 +40,10 @@ #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" -class PlaYUVerMdiArea: public QMdiArea +class PlaYUVerMdiArea : public QMdiArea { -public: - PlaYUVerMdiArea( QWidget *parent = 0 ) : - QMdiArea( parent ), - m_pixmapLogo( ":/images/playuver-backgroud-logo.png" ) + public: + PlaYUVerMdiArea( QWidget* parent = 0 ) : QMdiArea( parent ), m_pixmapLogo( ":/images/playuver-backgroud-logo.png" ) { setBackgroundRole( QPalette::Background ); } @@ -57,8 +55,9 @@ public: m_acLogMessages.remove( m_acLogMessages.size() - 1 ); update(); } -protected: - void paintEvent( QPaintEvent *event ) + + protected: + void paintEvent( QPaintEvent* event ) { QMdiArea::paintEvent( event ); QPainter painter( viewport() ); @@ -68,19 +67,19 @@ protected: int y = height() / 2 - pixFinalLogo.height() / 2; painter.drawPixmap( x, y, pixFinalLogo ); -// for( Int i = 0; i < m_acLogMessages.size(); i++ ) -// { -// painter.drawText( 5, height() - 5 - i * 15, m_acLogMessages.at( i ) ); -// } -// QPoint bottomLeftCorner( 0, viewport()->height() ); + // for( Int i = 0; i < m_acLogMessages.size(); i++ ) + // { + // painter.drawText( 5, height() - 5 - i * 15, m_acLogMessages.at( i ) ); + // } + // QPoint bottomLeftCorner( 0, viewport()->height() ); } -private: + + private: QVector m_acLogMessages; QPixmap m_pixmapLogo; }; -PlaYUVerSubWindowHandle::PlaYUVerSubWindowHandle( QWidget *parent ) : - QWidget( parent ) +PlaYUVerSubWindowHandle::PlaYUVerSubWindowHandle( QWidget* parent ) : QWidget( parent ) { m_iWindowMode = -1; m_pcWindowManagerLayout = NULL; @@ -90,7 +89,7 @@ PlaYUVerSubWindowHandle::PlaYUVerSubWindowHandle( QWidget *parent ) : m_apcMdiSubWindowList.clear(); m_pcApp = qobject_cast( parentWidget() ); - //setWindowMode( DETACHEDSUBWINDOWMODE ); + // setWindowMode( DETACHEDSUBWINDOWMODE ); setWindowMode( MDISUBWINDOWMODE ); } @@ -108,7 +107,6 @@ Void PlaYUVerSubWindowHandle::resetWindowMode() if( m_iWindowMode == DETACHEDSUBWINDOWMODE ) { - } if( m_iWindowMode == MDISUBWINDOWMODE ) { @@ -120,7 +118,8 @@ Void PlaYUVerSubWindowHandle::resetWindowMode() } for( Int i = 0; i < m_apcMdiSubWindowList.size(); i++ ) { - disconnect( m_apcMdiSubWindowList.at( i ), SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), this, SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); + disconnect( m_apcMdiSubWindowList.at( i ), SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), this, + SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); m_apcMdiSubWindowList.at( i )->close(); } m_apcMdiSubWindowList.clear(); @@ -129,7 +128,6 @@ Void PlaYUVerSubWindowHandle::resetWindowMode() m_pcMdiArea = NULL; if( m_pcWindowManagerLayout ) delete m_pcWindowManagerLayout; - } } @@ -163,7 +161,7 @@ Void PlaYUVerSubWindowHandle::setWindowMode( Int iWindowMode ) setVisible( true ); m_pcMdiArea = new PlaYUVerMdiArea; m_pcMdiArea->setActivationOrder( QMdiArea::ActivationHistoryOrder ); - connect( m_pcMdiArea, SIGNAL( subWindowActivated(QMdiSubWindow*) ), this, SLOT( updateActiveSubWindow() ) ); + connect( m_pcMdiArea, SIGNAL( subWindowActivated( QMdiSubWindow* ) ), this, SLOT( updateActiveSubWindow() ) ); m_pcWindowManagerLayout = new QHBoxLayout( this ); m_pcWindowManagerLayout->addWidget( m_pcMdiArea ); setLayout( m_pcWindowManagerLayout ); @@ -172,20 +170,20 @@ Void PlaYUVerSubWindowHandle::setWindowMode( Int iWindowMode ) addMdiSubWindow( m_apcSubWindowList.at( i ) ); m_apcSubWindowList.at( i )->resize( m_apcSubWindowList.at( i )->sizeHint() ); } - //m_pcApp->move( m_cMdiModeWindowPosition ); - //m_pcApp->resize( m_cMdiModeWindowSize ); + // m_pcApp->move( m_cMdiModeWindowPosition ); + // m_pcApp->resize( m_cMdiModeWindowSize ); if( m_pcActiveWindow ) { m_pcApp->setWindowTitle( QApplication::applicationName() + " :: " + m_pcActiveWindow->getWindowName() ); } } m_iWindowMode = iWindowMode; - //tileSubWindows(); - //parentWidget()->update(); - //qApp->processEvents(); + // tileSubWindows(); + // parentWidget()->update(); + // qApp->processEvents(); } -Void PlaYUVerSubWindowHandle::updateActiveSubWindow( SubWindowAbstract *window ) +Void PlaYUVerSubWindowHandle::updateActiveSubWindow( SubWindowAbstract* window ) { if( m_iWindowMode == DETACHEDSUBWINDOWMODE ) { @@ -217,26 +215,30 @@ Void PlaYUVerSubWindowHandle::updateActiveSubWindow( SubWindowAbstract *window ) } } -Void PlaYUVerSubWindowHandle::addMdiSubWindow( SubWindowAbstract *window ) +Void PlaYUVerSubWindowHandle::addMdiSubWindow( SubWindowAbstract* window ) { PlaYUVerMdiSubWindow* mdiSubWindow = new PlaYUVerMdiSubWindow; mdiSubWindow->setWidget( window ); m_pcMdiArea->addSubWindow( mdiSubWindow ); m_apcMdiSubWindowList.append( mdiSubWindow ); window->setSubWindow( mdiSubWindow ); - connect( mdiSubWindow, SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), this, SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); + connect( mdiSubWindow, SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), this, + SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); } -Void PlaYUVerSubWindowHandle::addSubWindow( SubWindowAbstract *window, Qt::WindowFlags flags ) +Void PlaYUVerSubWindowHandle::addSubWindow( SubWindowAbstract* window, Qt::WindowFlags flags ) { if( window ) { connect( window, SIGNAL( updateStatusBar( const QString& ) ), m_pcApp, SLOT( printMessage( const QString& ) ) ); - connect( window, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_pcApp, SLOT( updateZoomFactorSBox() ) ); + connect( window, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_pcApp, + SLOT( updateZoomFactorSBox() ) ); if( m_iWindowMode == DETACHEDSUBWINDOWMODE ) { - connect( window, SIGNAL( aboutToActivate( SubWindowAbstract* ) ), this, SLOT( updateActiveSubWindow( SubWindowAbstract* ) ) ); - connect( window, SIGNAL( aboutToClose( SubWindowAbstract* ) ), this, SLOT( removeSubWindow( SubWindowAbstract* ) ) ); + connect( window, SIGNAL( aboutToActivate( SubWindowAbstract* ) ), this, + SLOT( updateActiveSubWindow( SubWindowAbstract* ) ) ); + connect( window, SIGNAL( aboutToClose( SubWindowAbstract* ) ), this, + SLOT( removeSubWindow( SubWindowAbstract* ) ) ); } if( m_iWindowMode == MDISUBWINDOWMODE ) { @@ -304,7 +306,7 @@ SubWindowAbstract* PlaYUVerSubWindowHandle::activeSubWindow() const } QList PlaYUVerSubWindowHandle::findSubWindow( const UInt uiCategory ) const - { +{ QList apcSubWindowList; if( uiCategory == 0 ) { @@ -321,8 +323,9 @@ QList PlaYUVerSubWindowHandle::findSubWindow( const UInt uiC return apcSubWindowList; } -QList PlaYUVerSubWindowHandle::findSubWindow( const QString &windowName, const UInt uiCategory ) const - { +QList PlaYUVerSubWindowHandle::findSubWindow( const QString& windowName, + const UInt uiCategory ) const +{ QList subWindowList = findSubWindow( uiCategory ); QList apcSubWindowList; if( !windowName.isEmpty() ) @@ -337,7 +340,7 @@ QList PlaYUVerSubWindowHandle::findSubWindow( const QString } SubWindowAbstract* PlaYUVerSubWindowHandle::findSubWindow( const SubWindowAbstract* subWindow ) const - { +{ QList subWindowList = findSubWindow(); for( Int i = 0; i < subWindowList.size(); i++ ) { @@ -347,12 +350,12 @@ SubWindowAbstract* PlaYUVerSubWindowHandle::findSubWindow( const SubWindowAbstra return 0; } -Void PlaYUVerSubWindowHandle::setActiveSubWindow( QWidget *window ) +Void PlaYUVerSubWindowHandle::setActiveSubWindow( QWidget* window ) { if( !window ) return; - m_pcActiveWindow = qobject_cast( window ); + m_pcActiveWindow = qobject_cast( window ); if( m_iWindowMode == DETACHEDSUBWINDOWMODE ) { @@ -384,7 +387,7 @@ Void PlaYUVerSubWindowHandle::tileSubWindows() m_pcApp->resize( screenSize.width(), 5 ); QSize appSize = m_pcApp->size(); QPoint topLeftCornerWindow( 0, appSize.height() ); - //Select the arrangement based on the number of windows + // Select the arrangement based on the number of windows if( numberOfWindows % 2 != 0 && numberOfWindows > minWindowsInRow ) { @@ -429,7 +432,6 @@ Void PlaYUVerSubWindowHandle::tileSubWindows() { m_pcMdiArea->tileSubWindows(); } - } Void PlaYUVerSubWindowHandle::cascadeSubWindows() @@ -443,7 +445,7 @@ Void PlaYUVerSubWindowHandle::cascadeSubWindows() Void PlaYUVerSubWindowHandle::createActions() { m_mapperWindow = new QSignalMapper( this ); - connect( m_mapperWindow, SIGNAL( mapped(QWidget*) ), this, SLOT( setActiveSubWindow(QWidget*) ) ); + connect( m_mapperWindow, SIGNAL( mapped( QWidget* ) ), this, SLOT( setActiveSubWindow( QWidget* ) ) ); m_arrayActions.resize( TOTAL_ACT ); @@ -452,7 +454,7 @@ Void PlaYUVerSubWindowHandle::createActions() m_actionGroupWindowMode->setExclusive( true ); m_mapperWindowMode = new QSignalMapper( this ); - connect( m_mapperWindowMode, SIGNAL( mapped(int) ), this, SLOT( setWindowMode(int) ) ); + connect( m_mapperWindowMode, SIGNAL( mapped( int ) ), this, SLOT( setWindowMode( int ) ) ); m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT] = new QAction( tr( "&Detached SubWindows" ), this ); m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT]->setCheckable( true ); @@ -486,7 +488,7 @@ Void PlaYUVerSubWindowHandle::createActions() m_arrayActions[TILE_WINDOWS_ACT]->setIcon( QIcon( ":images/windowstile.png" ) ); m_arrayActions[TILE_WINDOWS_ACT]->setStatusTip( tr( "Tile the windows" ) ); m_arrayActions[TILE_WINDOWS_ACT]->setShortcut( tr( "Ctrl+T" ) ); -//connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), mdiArea, SLOT( tileSubWindows() ) ); + // connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), mdiArea, SLOT( tileSubWindows() ) ); connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( tileSubWindows() ) ); m_arrayActions[CASCADE_WINDOWS_ACT] = new QAction( tr( "Cascade" ), this ); @@ -498,17 +500,16 @@ Void PlaYUVerSubWindowHandle::createActions() m_arrayActions[NEXT_WINDOWS_ACT]->setShortcuts( QKeySequence::NextChild ); m_arrayActions[NEXT_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowRight ) ) ); m_arrayActions[NEXT_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the next window" ) ); -// connect( m_arrayActions[NEXT_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activateNextSubWindow() ) ); + // connect( m_arrayActions[NEXT_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activateNextSubWindow() ) ); m_arrayActions[PREVIOUS_WINDOWS_ACT] = new QAction( tr( "Pre&vious" ), this ); m_arrayActions[PREVIOUS_WINDOWS_ACT]->setShortcuts( QKeySequence::PreviousChild ); m_arrayActions[PREVIOUS_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowLeft ) ) ); m_arrayActions[PREVIOUS_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the previous window" ) ); -// connect( m_arrayActions[PREVIOUS_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activatePreviousSubWindow() ) ); + // connect( m_arrayActions[PREVIOUS_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activatePreviousSubWindow() ) ); m_arrayActions[SEPARATOR_ACT] = new QAction( this ); m_arrayActions[SEPARATOR_ACT]->setSeparator( true ); - } QMenu* PlaYUVerSubWindowHandle::createMenu() @@ -531,9 +532,9 @@ Void PlaYUVerSubWindowHandle::updateMenu() m_pcMenuWindow->addAction( m_arrayActions[TILE_WINDOWS_ACT] ); m_pcMenuWindow->addAction( m_arrayActions[CASCADE_WINDOWS_ACT] ); m_pcMenuWindow->addSeparator(); -// m_pcMenuWindow->addAction( m_arrayActions[NEXT_WINDOWS_ACT] ); -// m_pcMenuWindow->addAction( m_arrayActions[PREVIOUS_WINDOWS_ACT] ); -// m_pcMenuWindow->addSeparator(); + // m_pcMenuWindow->addAction( m_arrayActions[NEXT_WINDOWS_ACT] ); + // m_pcMenuWindow->addAction( m_arrayActions[PREVIOUS_WINDOWS_ACT] ); + // m_pcMenuWindow->addSeparator(); Int number_windows = m_apcSubWindowList.size(); if( number_windows > 1 ) @@ -551,7 +552,7 @@ Void PlaYUVerSubWindowHandle::updateMenu() for( Int i = 0; i < number_windows; ++i ) { - SubWindowAbstract *subWindow = m_apcSubWindowList.at( i ); + SubWindowAbstract* subWindow = m_apcSubWindowList.at( i ); QString text; if( i < 9 ) @@ -562,7 +563,7 @@ Void PlaYUVerSubWindowHandle::updateMenu() { text = tr( "%1 %2" ).arg( i + 1 ).arg( subWindow->getWindowName() ); } - QAction *action = m_pcMenuWindow->addAction( text ); + QAction* action = m_pcMenuWindow->addAction( text ); action->setCheckable( true ); action->setChecked( subWindow == activeSubWindow() ); connect( action, SIGNAL( triggered() ), m_mapperWindow, SLOT( map() ) ); @@ -587,4 +588,3 @@ Void PlaYUVerSubWindowHandle::writeSettings() appSettings.setValue( "SubWindowManager/LastMdiSize", m_cMdiModeWindowSize ); appSettings.setValue( "SubWindowManager/SubWindowMode", m_iWindowMode ); } - diff --git a/app/PlaYUVerSubWindowHandle.h b/app/PlaYUVerSubWindowHandle.h index de36a61..240f160 100644 --- a/app/PlaYUVerSubWindowHandle.h +++ b/app/PlaYUVerSubWindowHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -42,21 +42,21 @@ class SubWindowAbstract; class PlaYUVerMdiArea; class PlaYUVerMdiSubWindow; -class PlaYUVerSubWindowHandle: public QWidget +class PlaYUVerSubWindowHandle : public QWidget { -Q_OBJECT + Q_OBJECT -public: - PlaYUVerSubWindowHandle( QWidget *parent ); + public: + PlaYUVerSubWindowHandle( QWidget* parent ); Void processLogMsg( const QString& msg ); - Void addSubWindow( SubWindowAbstract *widget, Qt::WindowFlags flags = 0 ); + Void addSubWindow( SubWindowAbstract* widget, Qt::WindowFlags flags = 0 ); - SubWindowAbstract *activeSubWindow() const; + SubWindowAbstract* activeSubWindow() const; QList findSubWindow( const UInt uiCategory = 0 ) const; - QList findSubWindow( const QString &aName, const UInt uiCategory = 0 ) const; + QList findSubWindow( const QString& aName, const UInt uiCategory = 0 ) const; SubWindowAbstract* findSubWindow( const SubWindowAbstract* subWindow ) const; Void createActions(); @@ -71,7 +71,7 @@ public: MDISUBWINDOWMODE = 1, }; -private: + private: PlaYUVerApp* m_pcApp; Int m_iWindowMode; QList m_apcSubWindowList; @@ -107,15 +107,15 @@ private: /** * Internal functions */ - Void addMdiSubWindow( SubWindowAbstract *window ); + Void addMdiSubWindow( SubWindowAbstract* window ); Void resetWindowMode(); Void removeSubWindow( Int windowIdx ); -public Q_SLOTS: + public Q_SLOTS: void setWindowMode( int iWindowMode ); - void updateActiveSubWindow( SubWindowAbstract *window = 0 ); - void setActiveSubWindow( QWidget *window ); - void removeSubWindow( SubWindowAbstract *window ); + void updateActiveSubWindow( SubWindowAbstract* window = 0 ); + void setActiveSubWindow( QWidget* window ); + void removeSubWindow( SubWindowAbstract* window ); void removeMdiSubWindow( PlaYUVerMdiSubWindow* window ); void removeActiveSubWindow(); void removeAllSubWindow(); @@ -123,10 +123,9 @@ public Q_SLOTS: void cascadeSubWindows(); void updateMenu(); -Q_SIGNALS: + Q_SIGNALS: void changed(); void windowActivated(); - }; -#endif // __PLAYUVERSUBWINDOWHANDLE_H__ +#endif // __PLAYUVERSUBWINDOWHANDLE_H__ diff --git a/app/PlotSubWindow.cpp b/app/PlotSubWindow.cpp index ddd7411..9cfb771 100644 --- a/app/PlotSubWindow.cpp +++ b/app/PlotSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -44,10 +44,9 @@ Void PlotSubWindow::definePlotColors() m_arrayColorList.append( Qt::darkYellow ); } -PlotSubWindow::PlotSubWindow( const QString& windowTitle, QWidget * parent ) : - SubWindowAbstract( parent, SubWindowAbstract::PLOT_SUBWINDOW ) +PlotSubWindow::PlotSubWindow( const QString& windowTitle, QWidget* parent ) + : SubWindowAbstract( parent, SubWindowAbstract::PLOT_SUBWINDOW ) { - definePlotColors(); m_iNumberPlots = 0; m_dScaleFactor = 1; @@ -94,10 +93,10 @@ PlotSubWindow::PlotSubWindow( const QString& windowTitle, QWidget * parent ) : m_cPlotArea->yAxis2->setVisible( true ); m_cPlotArea->yAxis2->setTickLabels( false ); // make left and bottom axes always transfer their ranges to right and top axes: - connect( m_cPlotArea->xAxis, SIGNAL( rangeChanged(QCPRange) ), m_cPlotArea->xAxis2, SLOT( setRange(QCPRange) ) ); - connect( m_cPlotArea->yAxis, SIGNAL( rangeChanged(QCPRange) ), m_cPlotArea->yAxis2, SLOT( setRange(QCPRange) ) ); + connect( m_cPlotArea->xAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->xAxis2, SLOT( setRange( QCPRange ) ) ); + connect( m_cPlotArea->yAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->yAxis2, SLOT( setRange( QCPRange ) ) ); - QFont legendFont = font(); // start out with MainWindow's font.. + QFont legendFont = font(); // start out with MainWindow's font.. legendFont.setPointSize( 9 ); // and make a bit smaller for legend m_cPlotArea->legend->setFont( legendFont ); m_cPlotArea->legend->setBrush( backgroundBrush ); @@ -105,7 +104,7 @@ PlotSubWindow::PlotSubWindow( const QString& windowTitle, QWidget * parent ) : m_cPlotArea->legend->setBorderPen( QPen( palette().brush( QPalette::Active, QPalette::Shadow ), 1 ) ); m_cPlotArea->legend->setVisible( false ); - m_cPlotArea->setInteractions( QCP::iRangeZoom | QCP::iRangeDrag ); //QCP::iSelectPlottables + m_cPlotArea->setInteractions( QCP::iRangeZoom | QCP::iRangeDrag ); // QCP::iSelectPlottables m_cPlotPen.setStyle( Qt::SolidLine ); m_cPlotPen.setColor( Qt::black ); @@ -134,7 +133,6 @@ Void PlotSubWindow::zoomToFit() Void PlotSubWindow::zoomToFactor( Double factor, QPoint center ) { - } Void PlotSubWindow::scaleView( Double scale, QPoint center ) @@ -144,14 +142,14 @@ Void PlotSubWindow::scaleView( Double scale, QPoint center ) scale += 1; m_dScaleFactor *= scale; -// -// UInt aNewAxisRange[2][2]; -// for( UInt axis = 0; axis < 2; axis++ ) -// for( UInt dim = 0; dim < 2; dim++ ) -// aNewAxisRange[axis][dim] = m_aAxisRange[axis][dim] / m_dScaleFactor; -// -// m_cPlotArea->xAxis->setRange( aNewAxisRange[HORIZONTAL][0], aNewAxisRange[HORIZONTAL][1] ); -// m_cPlotArea->yAxis->setRange( aNewAxisRange[VERTICAL][0], aNewAxisRange[VERTICAL][1] ); + // + // UInt aNewAxisRange[2][2]; + // for( UInt axis = 0; axis < 2; axis++ ) + // for( UInt dim = 0; dim < 2; dim++ ) + // aNewAxisRange[axis][dim] = m_aAxisRange[axis][dim] / m_dScaleFactor; + // + // m_cPlotArea->xAxis->setRange( aNewAxisRange[HORIZONTAL][0], aNewAxisRange[HORIZONTAL][1] ); + // m_cPlotArea->yAxis->setRange( aNewAxisRange[VERTICAL][0], aNewAxisRange[VERTICAL][1] ); m_cPlotArea->xAxis->scaleRange( scale, 0 ); m_cPlotArea->yAxis->scaleRange( scale, 0 ); @@ -161,7 +159,7 @@ Void PlotSubWindow::scaleView( Double scale, QPoint center ) QSize PlotSubWindow::sizeHint() const { QSize maxSize; - QWidget *p = parentWidget(); + QWidget* p = parentWidget(); if( p ) { maxSize = p->size(); @@ -173,8 +171,8 @@ QSize PlotSubWindow::sizeHint() const return sizeHint( maxSize ); } -QSize PlotSubWindow::sizeHint( const QSize & maxSize ) const - { +QSize PlotSubWindow::sizeHint( const QSize& maxSize ) const +{ return maxSize * 2 / 3; } @@ -195,23 +193,23 @@ Void PlotSubWindow::setAxisRange( PlotSubWindow::Axis eAxis, const Int& axisStar if( eAxis == HORIZONTAL ) { m_cPlotArea->xAxis->setRange( axisStart, axisEnd ); - //horizontalScrollBar()->setRange( axisStart * 100, axisEnd * 100 ); + // horizontalScrollBar()->setRange( axisStart * 100, axisEnd * 100 ); m_aAxisRange[HORIZONTAL][0] = axisStart; m_aAxisRange[HORIZONTAL][1] = axisEnd; } if( eAxis == VERTICAL ) { m_cPlotArea->yAxis->setRange( axisStart, axisEnd ); - //verticalScrollBar()->setRange( axisStart * 100, axisEnd * 100 ); + // verticalScrollBar()->setRange( axisStart * 100, axisEnd * 100 ); m_aAxisRange[VERTICAL][0] = axisStart; m_aAxisRange[VERTICAL][1] = axisEnd; } m_cPlotArea->replot(); } -Void PlotSubWindow::addPlot( const QVector &arrayX, const QVector &arrayY, const QString& key ) +Void PlotSubWindow::addPlot( const QVector& arrayX, const QVector& arrayY, const QString& key ) { - QCPGraph *newPlot = m_cPlotArea->addGraph(); + QCPGraph* newPlot = m_cPlotArea->addGraph(); QColor plotColor = m_arrayColorList.at( 0 ); if( m_iNumberPlots < m_arrayColorList.size() ) { @@ -237,4 +235,3 @@ Void PlotSubWindow::addPlot( const QVector &arrayX, const QVector m_arrayColorList; @@ -55,18 +55,13 @@ private: Double m_dScaleFactor; Int m_iNumberPlots; -public: - - PlotSubWindow( const QString& windowTitle, QWidget * parent = NULL ); + public: + PlotSubWindow( const QString& windowTitle, QWidget* parent = NULL ); ~PlotSubWindow(); Void definePlotColors(); - Void refreshSubWindow() - { - - } - + Void refreshSubWindow() {} /** * Virtual functions from SubWindowAbstract */ @@ -75,16 +70,12 @@ public: Void zoomToFactor( Double factor, QPoint center = QPoint() ); Void scaleView( Double scale, QPoint center = QPoint() ); - Double getScaleFactor() - { - return m_dScaleFactor; - } - + Double getScaleFactor() { return m_dScaleFactor; } /** * Size related functions */ QSize sizeHint() const; - QSize sizeHint( const QSize & ) const; + QSize sizeHint( const QSize& ) const; Void setAxisName( const QString& nameAxisX, const QString& nameAxisY ); @@ -93,9 +84,7 @@ public: Void setKey( const QString& key ); - Void addPlot( const QVector &arrayX, const QVector &arrayY, const QString& key = QString() ); - + Void addPlot( const QVector& arrayX, const QVector& arrayY, const QString& key = QString() ); }; -#endif // __PLOTWINDOWHANDLE_H__ - +#endif // __PLOTWINDOWHANDLE_H__ diff --git a/app/ProgressBar.cpp b/app/ProgressBar.cpp index 9240dca..b37c06d 100644 --- a/app/ProgressBar.cpp +++ b/app/ProgressBar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -29,10 +29,8 @@ #include #include -ProgressBar::ProgressBar( QWidget *parent, UInt maxValue ) : - QWidget( parent ), - m_uiTotalProgress( maxValue ), - m_uiProgress( 0 ) +ProgressBar::ProgressBar( QWidget* parent, UInt maxValue ) + : QWidget( parent ), m_uiTotalProgress( maxValue ), m_uiProgress( 0 ) { QVBoxLayout* mainLayout = new QVBoxLayout( this ); m_pcProgressBar = new QProgressBar; @@ -42,8 +40,8 @@ ProgressBar::ProgressBar( QWidget *parent, UInt maxValue ) : setLayout( mainLayout ); setWindowTitle( QStringLiteral( "Progress" ) ); -// QSize appSize = QApplication::desktop()->availableGeometry().size(); -// QPoint appCenter = QApplication::desktop()->availableGeometry().center(); + // QSize appSize = QApplication::desktop()->availableGeometry().size(); + // QPoint appCenter = QApplication::desktop()->availableGeometry().center(); QSize appSize = parent->size(); QPoint appPos = parent->pos(); QPoint appCenter = QPoint( appPos.x() + appSize.width() / 2, appPos.y() + appSize.height() / 2 ); @@ -58,4 +56,3 @@ Void ProgressBar::incrementProgress( UInt increment ) m_pcProgressBar->setValue( m_uiProgress ); update(); } - diff --git a/app/ProgressBar.h b/app/ProgressBar.h index 4cbe919..7a10a21 100644 --- a/app/ProgressBar.h +++ b/app/ProgressBar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,19 +31,19 @@ class QProgressBar; -class ProgressBar: public QWidget +class ProgressBar : public QWidget { -Q_OBJECT + Q_OBJECT -public: - ProgressBar( QWidget *parent, UInt maxValue ); + public: + ProgressBar( QWidget* parent, UInt maxValue ); Void incrementProgress( UInt ); -private: + private: UInt m_uiTotalProgress; UInt m_uiProgress; QProgressBar* m_pcProgressBar; }; -#endif // __PROGRESSBAR_H__ +#endif // __PROGRESSBAR_H__ diff --git a/app/QualityHandle.cpp b/app/QualityHandle.cpp index d9fd426..03f6dbe 100644 --- a/app/QualityHandle.cpp +++ b/app/QualityHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,16 +34,13 @@ #include "QtConcurrent/qtconcurrentrun.h" #endif -QualityHandle::QualityHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : - m_pcParet( parent ), - m_pcMainWindowManager( windowManager ) +QualityHandle::QualityHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) + : m_pcParet( parent ), m_pcMainWindowManager( windowManager ) { - } QualityHandle::~QualityHandle() { - } Void QualityHandle::createActions() @@ -93,8 +90,9 @@ QDockWidget* QualityHandle::createDock() m_pcQualityHandleDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); m_pcQualityHandleDock->setWidget( m_pcQualityHandleSideBar ); - connect( m_pcQualityHandleSideBar, SIGNAL( signalQualityMetricChanged(int) ), this, SLOT( slotQualityMetricChanged(int) ) ); - connect( m_mapperQualityMetric, SIGNAL( mapped(int) ), this, SLOT( slotQualityMetricChanged(int) ) ); + connect( m_pcQualityHandleSideBar, SIGNAL( signalQualityMetricChanged( int ) ), this, + SLOT( slotQualityMetricChanged( int ) ) ); + connect( m_mapperQualityMetric, SIGNAL( mapped( int ) ), this, SLOT( slotQualityMetricChanged( int ) ) ); slotQualityMetricChanged( 0 ); @@ -103,7 +101,7 @@ QDockWidget* QualityHandle::createDock() Void QualityHandle::updateMenus() { - VideoSubWindow* pcCurrentVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcCurrentVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcCurrentVideoSubWindow ? true : false; Bool hasReference = false; Bool isReference = false; @@ -114,10 +112,11 @@ Void QualityHandle::updateMenus() if( hasSubWindow && !hasReference ) { VideoSubWindow* pcVideoSubWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { - pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); + pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); if( pcVideoSubWindow->getRefSubWindow() == pcCurrentVideoSubWindow ) { isReference = true; @@ -186,7 +185,7 @@ Void QualityHandle::measureQuality( QVector apcWindowList ) ProgressBar* pcProgressBar = new ProgressBar( m_pcParet, numberOfFrames ); - padQualityValues = new QVector [numberOfWindows + 1]; + padQualityValues = new QVector[ numberOfWindows + 1 ]; PlaYUVerFrame* pcReferenceFrame; PlaYUVerFrame* pcCurrFrame; @@ -215,7 +214,8 @@ Void QualityHandle::measureQuality( QVector apcWindowList ) plotWindowTitle += " - " + apcWindowList.at( 0 )->getWindowName(); } PlotSubWindow* pcPlotWindow = new PlotSubWindow( plotWindowTitle ); - pcPlotWindow->setAxisName( "Frame Number", QString::fromStdString( PlaYUVerFrame::supportedQualityMetricsList()[m_iQualityMetricIdx] ) ); + pcPlotWindow->setAxisName( + "Frame Number", QString::fromStdString( PlaYUVerFrame::supportedQualityMetricsList()[m_iQualityMetricIdx] ) ); if( apcWindowList.size() > 1 ) { @@ -235,7 +235,6 @@ Void QualityHandle::measureQuality( QVector apcWindowList ) pcPlotWindow->show(); pcProgressBar->close(); - } Void QualityHandle::slotQualityMetricChanged( Int idx ) @@ -252,7 +251,8 @@ Void QualityHandle::slotSelectCurrentAsReference() if( pcRefSubWindow ) { VideoSubWindow* pcVideoSubWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); @@ -267,7 +267,7 @@ Void QualityHandle::slotSelectCurrentAsReference() Void QualityHandle::slotPlotQualitySingle() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { if( pcSubWindow->getRefSubWindow() ) @@ -275,14 +275,14 @@ Void QualityHandle::slotPlotQualitySingle() QVector apcWindowList; apcWindowList.append( pcSubWindow ); -//#ifndef QT_NO_CONCURRENT -// m_cMeasurementResult.waitForFinished(); -// m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); -//#else + //#ifndef QT_NO_CONCURRENT + // m_cMeasurementResult.waitForFinished(); + // m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); + //#else QApplication::setOverrideCursor( Qt::WaitCursor ); measureQuality( apcWindowList ); QApplication::restoreOverrideCursor(); -//#endif + //#endif emit changed(); } } @@ -290,7 +290,7 @@ Void QualityHandle::slotPlotQualitySingle() Void QualityHandle::slotPlotQualitySeveral() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { QVector apcWindowList; @@ -302,10 +302,11 @@ Void QualityHandle::slotPlotQualitySeveral() } VideoSubWindow* pcVideoSubWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { - pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); + pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); if( pcVideoSubWindow->getRefSubWindow() == pcRefSubWindow ) { apcWindowList.append( pcVideoSubWindow ); @@ -314,16 +315,15 @@ Void QualityHandle::slotPlotQualitySeveral() if( apcWindowList.size() > 0 ) { -//#ifndef QT_NO_CONCURRENT -// m_cMeasurementResult.waitForFinished(); -// m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); -//#else + //#ifndef QT_NO_CONCURRENT + // m_cMeasurementResult.waitForFinished(); + // m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); + //#else QApplication::setOverrideCursor( Qt::WaitCursor ); measureQuality( apcWindowList ); QApplication::restoreOverrideCursor(); -//#endif + //#endif emit changed(); } } } - diff --git a/app/QualityHandle.h b/app/QualityHandle.h index 7df0c03..9b14912 100644 --- a/app/QualityHandle.h +++ b/app/QualityHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -39,11 +39,11 @@ class PlaYUVerSubWindowHandle; class VideoSubWindow; -class QualityHandle: public QWidget +class QualityHandle : public QWidget { -Q_OBJECT - public: - QualityHandle( QWidget*, PlaYUVerSubWindowHandle * ); + Q_OBJECT + public: + QualityHandle( QWidget*, PlaYUVerSubWindowHandle* ); ~QualityHandle(); Void createActions(); @@ -56,7 +56,7 @@ Q_OBJECT Void update( VideoSubWindow* currSubWindow ); -private: + private: QWidget* m_pcParet; PlaYUVerSubWindowHandle* m_pcMainWindowManager; @@ -81,14 +81,14 @@ private: QFuture m_cMeasurementResult; Void measureQuality( QVector apcWindowList ); -Q_SIGNALS: + Q_SIGNALS: void changed(); -private Q_SLOTS: + private Q_SLOTS: void slotQualityMetricChanged( int ); void slotSelectCurrentAsReference(); void slotPlotQualitySingle(); void slotPlotQualitySeveral(); }; -#endif // __QUALITYMEASUREMENTSIDEBAR_H__ +#endif // __QUALITYMEASUREMENTSIDEBAR_H__ diff --git a/app/QualityMeasurementSidebar.cpp b/app/QualityMeasurementSidebar.cpp index b96cb4a..2e72f0f 100644 --- a/app/QualityMeasurementSidebar.cpp +++ b/app/QualityMeasurementSidebar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -27,21 +27,18 @@ #include "QualityMeasurementSidebar.h" #include "VideoSubWindow.h" -QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerSubWindowHandle *windowManager ) : - QWidget( parent ), - m_pcMainWindowManager( windowManager ), - m_pcCurrentVideoSubWindow( NULL ) +QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) + : QWidget( parent ), m_pcMainWindowManager( windowManager ), m_pcCurrentVideoSubWindow( NULL ) { - // Side bar area ----------------------------------------------------- - QLabel *MetricLabel = new QLabel( tr( "Metric:" ) ); + QLabel* MetricLabel = new QLabel( tr( "Metric:" ) ); MetricLabel->setAlignment( Qt::AlignVCenter | Qt::AlignRight ); - QLabel *RefLabel = new QLabel( tr( "Ref:" ) ); + QLabel* RefLabel = new QLabel( tr( "Ref:" ) ); RefLabel->setAlignment( Qt::AlignVCenter | Qt::AlignRight ); - QLabel *RecLabel = new QLabel( tr( "Rec:" ) ); + QLabel* RecLabel = new QLabel( tr( "Rec:" ) ); RecLabel->setAlignment( Qt::AlignVCenter | Qt::AlignRight ); m_comboBoxMetric = new QComboBox; @@ -58,7 +55,7 @@ QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerS m_comboBoxRef->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); updateSubWindowList(); - QGridLayout *mainLayout = new QGridLayout; + QGridLayout* mainLayout = new QGridLayout; mainLayout->addWidget( MetricLabel, 0, 0, Qt::AlignLeft ); mainLayout->addWidget( m_comboBoxMetric, 0, 1, Qt::AlignLeft ); mainLayout->addItem( spaceQuality, 0, 2, Qt::AlignRight ); @@ -80,7 +77,7 @@ QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerS m_ppcLabelQualityValue[CHROMA_V] = new QLabel; m_ppcLabelQualityValue[CHROMA_V]->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); - QGridLayout *qualityResultsLayout = new QGridLayout; + QGridLayout* qualityResultsLayout = new QGridLayout; qualityResultsLayout->addWidget( m_ppcLabelQualityLabel[LUMA], 0, 0 ); qualityResultsLayout->addWidget( m_ppcLabelQualityValue[LUMA], 0, 1 ); qualityResultsLayout->addWidget( m_ppcLabelQualityLabel[CHROMA_U], 1, 0 ); @@ -88,25 +85,24 @@ QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerS qualityResultsLayout->addWidget( m_ppcLabelQualityLabel[CHROMA_V], 2, 0 ); qualityResultsLayout->addWidget( m_ppcLabelQualityValue[CHROMA_V], 2, 1 ); - //QGroupBox *statisticsGroup = new QGroupBox( tr( "Quality" ) ); - QGroupBox *statisticsGroup = new QGroupBox; + // QGroupBox *statisticsGroup = new QGroupBox( tr( "Quality" ) ); + QGroupBox* statisticsGroup = new QGroupBox; statisticsGroup->setLayout( qualityResultsLayout ); - statisticsGroup->setWhatsThis( tr( "

Here you can see the quality results calculated for the " - "selected windows." ) ); + statisticsGroup->setWhatsThis( + tr( "

Here you can see the quality results calculated for the " + "selected windows." ) ); mainLayout->addWidget( statisticsGroup, 4, 0, 3, 3 ); mainLayout->setRowStretch( 8, 10 ); setLayout( mainLayout ); - connect( m_comboBoxRef, SIGNAL( activated(int) ), this, SLOT( slotReferenceChanged(int) ) ); - connect( m_comboBoxMetric, SIGNAL( currentIndexChanged(int) ), this, SLOT( slotQualityMetricChanged(int) ) ); - + connect( m_comboBoxRef, SIGNAL( activated( int ) ), this, SLOT( slotReferenceChanged( int ) ) ); + connect( m_comboBoxMetric, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotQualityMetricChanged( int ) ) ); } QualityMeasurementSidebar::~QualityMeasurementSidebar() { - } QSize QualityMeasurementSidebar::sizeHint() const @@ -163,10 +159,10 @@ Void QualityMeasurementSidebar::updateSubWindowList() m_comboBoxRef->setCurrentIndex( index ); } } -// m_comboBoxRef->setSizeAdjustPolicy( QComboBox::AdjustToContents ); + // m_comboBoxRef->setSizeAdjustPolicy( QComboBox::AdjustToContents ); } -Void QualityMeasurementSidebar::updateCurrentWindow( VideoSubWindow *subWindow ) +Void QualityMeasurementSidebar::updateCurrentWindow( VideoSubWindow* subWindow ) { m_pcCurrentVideoSubWindow = subWindow; if( m_pcCurrentVideoSubWindow ) @@ -216,7 +212,6 @@ Void QualityMeasurementSidebar::updateSidebarData() { m_ppcLabelQualityValue[component]->setText( zeroValue ); } - } Void QualityMeasurementSidebar::updateQualityMetric( Int idx ) @@ -233,7 +228,7 @@ Void QualityMeasurementSidebar::slotReferenceChanged( Int index ) { if( index > -1 && m_pcCurrentVideoSubWindow ) { - VideoSubWindow *pcRefSubWindow = m_pcVideoWindowList.at( index ); + VideoSubWindow* pcRefSubWindow = m_pcVideoWindowList.at( index ); if( pcRefSubWindow ) { if( m_pcCurrentVideoSubWindow->getCurrFrame()->haveSameFmt( pcRefSubWindow->getCurrFrame() ) ) @@ -254,6 +249,5 @@ Void QualityMeasurementSidebar::slotReferenceChanged( Int index ) Void QualityMeasurementSidebar::slotQualityMetricChanged( Int idx ) { emit signalQualityMetricChanged( idx ); - //updateQualityMetric( idx ); + // updateQualityMetric( idx ); } - diff --git a/app/QualityMeasurementSidebar.h b/app/QualityMeasurementSidebar.h index 8785507..9fb4e1b 100644 --- a/app/QualityMeasurementSidebar.h +++ b/app/QualityMeasurementSidebar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -40,11 +40,11 @@ class PlaYUVerSubWindowHandle; class VideoSubWindow; -class QualityMeasurementSidebar: public QWidget +class QualityMeasurementSidebar : public QWidget { -Q_OBJECT - public: - QualityMeasurementSidebar( QWidget*, PlaYUVerSubWindowHandle * ); + Q_OBJECT + public: + QualityMeasurementSidebar( QWidget*, PlaYUVerSubWindowHandle* ); ~QualityMeasurementSidebar(); QSize sizeHint() const; @@ -52,36 +52,35 @@ Q_OBJECT Void updateSideBar( Bool hasSubWindow ); Void updateSubWindowList(); - Void updateCurrentWindow( VideoSubWindow * ); + Void updateCurrentWindow( VideoSubWindow* ); Void updateSidebarData(); Void updateQualityMetric( Int ); -private: + private: PlaYUVerSubWindowHandle* m_pcMainWindowManager; QVector m_pcVideoWindowList; QStringList m_pcWindowListNames; QStringList m_pcSelectedWindowListNames; - VideoSubWindow *m_pcCurrentVideoSubWindow; + VideoSubWindow* m_pcCurrentVideoSubWindow; - QComboBox *m_comboBoxMetric; + QComboBox* m_comboBoxMetric; - QComboBox *m_comboBoxRef; - QComboBox *m_comboBoxRec; + QComboBox* m_comboBoxRef; + QComboBox* m_comboBoxRec; QLabel* m_ppcLabelQualityLabel[3]; QLabel* m_ppcLabelQualityValue[3]; - HistogramWidget *histogramWidget; + HistogramWidget* histogramWidget; -Q_SIGNALS: + Q_SIGNALS: void signalQualityMetricChanged( int ); -private Q_SLOTS: + private Q_SLOTS: void slotReferenceChanged( int ); void slotQualityMetricChanged( int ); - }; -#endif // __QUALITYMEASUREMENTSIDEBAR_H__ +#endif // __QUALITYMEASUREMENTSIDEBAR_H__ diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index 31b1f72..f165cfb 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,11 +30,9 @@ #include #include -SeekStreamDialog::SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *parent ) : - QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ), - m_iSelectedFrameNum() +SeekStreamDialog::SeekStreamDialog( PlaYUVerStream* pcCurrStream, QWidget* parent ) + : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ), m_iSelectedFrameNum() { - m_iSelectedFrameNum = pcCurrStream->getCurrFrameNum(); setWindowModality( Qt::ApplicationModal ); @@ -79,4 +77,3 @@ Int SeekStreamDialog::runDialog() m_iSelectedFrameNum = m_spinFrameNum->value(); return m_iSelectedFrameNum; } - diff --git a/app/SeekStreamDialog.h b/app/SeekStreamDialog.h index 6542605..b74bb5d 100644 --- a/app/SeekStreamDialog.h +++ b/app/SeekStreamDialog.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,16 +34,17 @@ /** * */ -class SeekStreamDialog: public QDialog +class SeekStreamDialog : public QDialog { -Q_OBJECT + Q_OBJECT -public: - SeekStreamDialog( PlaYUVerStream *pcCurrStream, QWidget *parent = 0 ); + public: + SeekStreamDialog( PlaYUVerStream* pcCurrStream, QWidget* parent = 0 ); Int runDialog(); - private: + + private: QSpinBox* m_spinFrameNum; Int m_iSelectedFrameNum; }; -#endif // __MODULEHANDLEOPTDIALOG_H__ +#endif // __MODULEHANDLEOPTDIALOG_H__ diff --git a/app/SubWindowAbstract.cpp b/app/SubWindowAbstract.cpp index d4832ea..e58b559 100644 --- a/app/SubWindowAbstract.cpp +++ b/app/SubWindowAbstract.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,20 +30,18 @@ #include "SubWindowAbstract.h" #include "PlaYUVerMdiSubWindow.h" -SubWindowAbstract::SubWindowAbstract( QWidget * parent, UInt category ) : - QWidget( parent ), - m_cSubWindow( NULL ) +SubWindowAbstract::SubWindowAbstract( QWidget* parent, UInt category ) : QWidget( parent ), m_cSubWindow( NULL ) { setParent( parent ); setVisible( false ); - //setFocusPolicy( Qt::WheelFocus ); + // setFocusPolicy( Qt::WheelFocus ); setFocusPolicy( Qt::StrongFocus ); setAttribute( Qt::WA_DeleteOnClose ); setBackgroundRole( QPalette::Background ); setWindowIcon( QIcon( ":/images/playuver.png" ) ); - //setWidgetResizable( true ); + // setWidgetResizable( true ); m_pcLayout = NULL; m_uiCategory = category; m_cWindowName = QString( " " ); @@ -58,7 +56,7 @@ SubWindowAbstract::~SubWindowAbstract() Void SubWindowAbstract::setWidget( QWidget* widget ) { - QGridLayout *layout = new QGridLayout( this ); + QGridLayout* layout = new QGridLayout( this ); layout->setContentsMargins( 0, 0, 0, 0 ); layout->addWidget( widget, 0, 0 ); } @@ -89,17 +87,17 @@ QSize SubWindowAbstract::sizeHint() const return QSize(); } -QSize SubWindowAbstract::sizeHint( const QSize & ) const - { +QSize SubWindowAbstract::sizeHint( const QSize& ) const +{ return QSize(); } -Void SubWindowAbstract::focusInEvent( QFocusEvent * event ) +Void SubWindowAbstract::focusInEvent( QFocusEvent* event ) { emit aboutToActivate( this ); } -Void SubWindowAbstract::closeEvent( QCloseEvent *event ) +Void SubWindowAbstract::closeEvent( QCloseEvent* event ) { emit aboutToClose( this ); event->accept(); @@ -111,4 +109,3 @@ Void SubWindowAbstract::closeSubWindow() if( m_cSubWindow ) m_cSubWindow->close(); } - diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index 3d2ea4f..04b06cc 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -50,18 +50,18 @@ class QCloseEvent; class PlaYUVerMdiSubWindow; -class SubWindowAbstract: public QWidget +class SubWindowAbstract : public QWidget { -Q_OBJECT + Q_OBJECT -private: + private: QHBoxLayout* m_pcLayout; UInt m_uiCategory; QString m_cWindowName; PlaYUVerMdiSubWindow* m_cSubWindow; -public: + public: enum SubWindowCategory { SUBWINDOW = 0, @@ -69,9 +69,10 @@ public: VIDEO_STREAM_SUBWINDOW = 2, MODULE_SUBWINDOW = 4, PLOT_SUBWINDOW = 8, - };Q_DECLARE_FLAGS( SubWindowCategories, SubWindowCategory ) + }; + Q_DECLARE_FLAGS( SubWindowCategories, SubWindowCategory ) -SubWindowAbstract ( QWidget *, UInt ); + SubWindowAbstract( QWidget*, UInt ); ~SubWindowAbstract(); /** @@ -104,7 +105,7 @@ SubWindowAbstract ( QWidget *, UInt ); * Size related functions */ virtual QSize sizeHint() const; - virtual QSize sizeHint( const QSize & ) const; + virtual QSize sizeHint( const QSize& ) const; /** * Window name @@ -121,36 +122,24 @@ SubWindowAbstract ( QWidget *, UInt ); * @note This function should be used with enum SubWindowCategories * with an & operation and it may belong to several categories */ - UInt getCategory() - { - return m_uiCategory; - } - + UInt getCategory() { return m_uiCategory; } /** * Check category of the SubWindow * @param checkCateory SubWindow category to check against; * it should be enum SubWindowCategories type * @return true when SubWindow belong to checkCateory */ - Bool checkCategory( UInt checkCateory ) - { - return m_uiCategory & checkCateory; - } - - Void setSubWindow( PlaYUVerMdiSubWindow* subWindow ) - { - m_cSubWindow = subWindow; - } - + Bool checkCategory( UInt checkCateory ) { return m_uiCategory & checkCateory; } + Void setSubWindow( PlaYUVerMdiSubWindow* subWindow ) { m_cSubWindow = subWindow; } Void closeSubWindow(); -protected: + protected: void focusInEvent( QFocusEvent* event ); void closeEvent( QCloseEvent* event ); Void setWidget( QWidget* widget ); - Q_SIGNALS: + Q_SIGNALS: /** * Notify that zoom factor was changed by internal event (e.g. by mouse wheel) */ @@ -167,10 +156,8 @@ protected: void aboutToActivate( SubWindowAbstract* ); void aboutToClose( SubWindowAbstract* ); -public Q_SLOTS: + public Q_SLOTS: void onDestroyed(); - }; -#endif // __SUBWINDOWABSTRACT_H__ - +#endif // __SUBWINDOWABSTRACT_H__ diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index 098e5db..a7dcd08 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -41,9 +41,8 @@ #include #endif -VideoHandle::VideoHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) : - m_pcParet( parent ), - m_pcMainWindowManager( windowManager ) +VideoHandle::VideoHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) + : m_pcParet( parent ), m_pcMainWindowManager( windowManager ) { m_pcCurrentVideoSubWindow = NULL; m_bIsPlaying = false; @@ -57,7 +56,6 @@ VideoHandle::VideoHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManage VideoHandle::~VideoHandle() { - } Void VideoHandle::createActions() @@ -75,7 +73,7 @@ Void VideoHandle::createActions() connect( m_arrayActions[STOP_ACT], SIGNAL( triggered() ), this, SLOT( stop() ) ); m_mapperVideoSeek = new QSignalMapper( this ); - connect( m_mapperVideoSeek, SIGNAL( mapped(int) ), this, SLOT( seekEvent(int) ) ); + connect( m_mapperVideoSeek, SIGNAL( mapped( int ) ), this, SLOT( seekEvent( int ) ) ); m_arrayActions[VIDEO_BACKWARD_ACT] = new QAction( "Video Backward", this ); m_arrayActions[VIDEO_BACKWARD_ACT]->setStatusTip( "Seek backward" ); @@ -119,14 +117,14 @@ Void VideoHandle::createActions() m_pcFrameSlider->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) ); m_pcFrameSlider->setEnabled( false ); m_pcFrameSlider->setTracking( false ); - connect( m_pcFrameSlider, SIGNAL( valueChanged(int) ), this, SLOT( seekSliderEvent(int) ) ); + connect( m_pcFrameSlider, SIGNAL( valueChanged( int ) ), this, SLOT( seekSliderEvent( int ) ) ); // ------------ Tools ------------ actionGroupTools = new QActionGroup( this ); actionGroupTools->setExclusive( true ); m_mapperTools = new QSignalMapper( this ); - connect( m_mapperTools, SIGNAL( mapped(int) ), this, SLOT( setTool(int) ) ); + connect( m_mapperTools, SIGNAL( mapped( int ) ), this, SLOT( setTool( int ) ) ); m_uiViewTool = ViewArea::NavigationView; @@ -157,7 +155,7 @@ Void VideoHandle::createActions() m_arrayActions[SHOW_GRID_ACT] = new QAction( "Show grid", this ); m_arrayActions[SHOW_GRID_ACT]->setCheckable( true ); m_arrayActions[SHOW_GRID_ACT]->setChecked( false ); - connect( m_arrayActions[SHOW_GRID_ACT], SIGNAL( toggled(bool) ), this, SLOT( toggleGrid(bool) ) ); + connect( m_arrayActions[SHOW_GRID_ACT], SIGNAL( toggled( bool ) ), this, SLOT( toggleGrid( bool ) ) ); } QMenu* VideoHandle::createVideoMenu() @@ -214,7 +212,7 @@ QDockWidget* VideoHandle::createDock() m_pcFramePropertiesDock = new QDockWidget( tr( "Frame Information" ), this ); m_pcFramePropertiesDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); m_pcFramePropertiesDock->setWidget( m_pcFramePropertiesSideBar ); - connect( m_pcFramePropertiesDock, SIGNAL( visibilityChanged(bool) ), this, SLOT( update() ) ); + connect( m_pcFramePropertiesDock, SIGNAL( visibilityChanged( bool ) ), this, SLOT( update() ) ); return m_pcFramePropertiesDock; } @@ -245,11 +243,11 @@ QWidget* VideoHandle::createStatusBarMessage() Void VideoHandle::updateMenus() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcSubWindow ? true : false; m_arrayActions[PLAY_ACT]->setEnabled( hasSubWindow ); - //m_arrayActions[PAUSE_ACT]->setEnabled( hasSubWindow ); + // m_arrayActions[PAUSE_ACT]->setEnabled( hasSubWindow ); m_arrayActions[STOP_ACT]->setEnabled( hasSubWindow ); m_arrayActions[VIDEO_BACKWARD_ACT]->setEnabled( hasSubWindow ); m_arrayActions[VIDEO_FORWARD_ACT]->setEnabled( hasSubWindow ); @@ -385,7 +383,7 @@ Void VideoHandle::openSubWindow( VideoSubWindow* subWindow ) Void VideoHandle::closeSubWindow( SubWindowAbstract* subWindow ) { - VideoSubWindow* videoSubWindow = qobject_cast( subWindow ); + VideoSubWindow* videoSubWindow = qobject_cast( subWindow ); if( m_acPlayingSubWindows.contains( videoSubWindow ) ) { @@ -405,11 +403,11 @@ Void VideoHandle::zoomToFactorAll( const Double scale, const QPoint center ) if( m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() ) { - factor = m_pcCurrentVideoSubWindow->getScaleFactor(); - SubWindowAbstract *subWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + SubWindowAbstract* subWindow; + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { subWindow = subWindowList.at( i ); @@ -428,10 +426,11 @@ Void VideoHandle::moveAllScrollBars( const QPoint offset ) QPoint newOffset = offset; if( m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() && m_pcCurrentVideoSubWindow ) { - VideoSubWindow *videoSubWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + VideoSubWindow* videoSubWindow; + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); - QScrollBar *scrollBar; + QScrollBar* scrollBar; scrollBar = m_pcCurrentVideoSubWindow->getScroll()->horizontalScrollBar(); // Do not move other images, if current image reached maximum or minimum scroll position @@ -448,7 +447,7 @@ Void VideoHandle::moveAllScrollBars( const QPoint offset ) for( Int i = 0; i < subWindowList.size(); i++ ) { - videoSubWindow = qobject_cast( subWindowList.at( i ) ); + videoSubWindow = qobject_cast( subWindowList.at( i ) ); if( m_pcCurrentVideoSubWindow == videoSubWindow ) continue; else @@ -512,10 +511,7 @@ Void VideoHandle::setTimerStatus() #if( _CONTROL_PLAYING_TIME_ == 1 ) if( m_pcPlayControlTimer && m_pcPlayingTimer->interval() > 0 ) { - qDebug( ) << "Desired Fps: " - << 1000 / m_pcPlayingTimer->interval() - << "Real Fps: " - << 1000 / m_dAverageFps; + qDebug() << "Desired Fps: " << 1000 / m_pcPlayingTimer->interval() << "Real Fps: " << 1000 / m_dAverageFps; delete m_pcPlayControlTimer; m_pcPlayControlTimer = NULL; @@ -574,7 +570,7 @@ Void VideoHandle::play() } setTimerStatus(); emit changed(); - //update(); + // update(); } Void VideoHandle::stop() @@ -603,7 +599,8 @@ Void VideoHandle::playEvent() { Bool bEndOfSequence = false; #if( _CONTROL_PLAYING_TIME_ == 1 ) - m_dAverageFps = Double( m_dAverageFps * m_uiNumberPlayedFrames + m_pcPlayControlTimer->elapsed() ) / Double( m_uiNumberPlayedFrames + 1 ); + m_dAverageFps = Double( m_dAverageFps * m_uiNumberPlayedFrames + m_pcPlayControlTimer->elapsed() ) / + Double( m_uiNumberPlayedFrames + 1 ); m_uiNumberPlayedFrames++; m_pcPlayControlTimer->restart(); #endif @@ -622,12 +619,13 @@ Void VideoHandle::playEvent() m_acPlayingSubWindows.at( i )->seekAbsoluteEvent( 0 ); } } - catch( const char *msg ) + catch( const char* msg ) { - QString warningMsg = "Error while playing " + QFileInfo( m_pcCurrentVideoSubWindow->getCurrentFileName() ).fileName() + " with the following error: \n" - + msg; + QString warningMsg = "Error while playing " + + QFileInfo( m_pcCurrentVideoSubWindow->getCurrentFileName() ).fileName() + + " with the following error: \n" + msg; QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); - qDebug( ) << warningMsg; + qDebug() << warningMsg; stop(); m_pcCurrentVideoSubWindow->close(); } @@ -640,7 +638,8 @@ Void VideoHandle::seekEvent( Int direction ) { if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) ) { - if( !( ( UInt )( m_pcCurrentVideoSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= getMaxFrameNumber() && direction > 0 ) ) + if( !( ( UInt )( m_pcCurrentVideoSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= getMaxFrameNumber() && + direction > 0 ) ) { for( Int i = 0; i < m_acPlayingSubWindows.size(); i++ ) { @@ -653,7 +652,7 @@ Void VideoHandle::seekEvent( Int direction ) m_pcCurrentVideoSubWindow->seekRelativeEvent( direction > 0 ? true : false ); } emit changed(); - //update(); + // update(); } } @@ -671,12 +670,12 @@ Void VideoHandle::seekVideo() { for( Int i = 0; i < m_acPlayingSubWindows.size(); i++ ) { - m_acPlayingSubWindows.at( i )->seekAbsoluteEvent( ( UInt )newFrameNum ); + m_acPlayingSubWindows.at( i )->seekAbsoluteEvent( (UInt)newFrameNum ); } } else { - m_pcCurrentVideoSubWindow->seekAbsoluteEvent( ( UInt )newFrameNum ); + m_pcCurrentVideoSubWindow->seekAbsoluteEvent( (UInt)newFrameNum ); } emit changed(); } @@ -692,26 +691,27 @@ Void VideoHandle::seekSliderEvent( Int new_frame_num ) { for( Int i = 0; i < m_acPlayingSubWindows.size(); i++ ) { - m_acPlayingSubWindows.at( i )->seekAbsoluteEvent( ( UInt )new_frame_num ); + m_acPlayingSubWindows.at( i )->seekAbsoluteEvent( (UInt)new_frame_num ); } } else { - m_pcCurrentVideoSubWindow->seekAbsoluteEvent( ( UInt )new_frame_num ); + m_pcCurrentVideoSubWindow->seekAbsoluteEvent( (UInt)new_frame_num ); } emit changed(); - //update(); + // update(); } } Void VideoHandle::videoSelectionButtonEvent() { - VideoSubWindow *videoSubWindow; + VideoSubWindow* videoSubWindow; Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers(); if( keyModifiers & Qt::ControlModifier ) { - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { videoSubWindow = qobject_cast( subWindowList.at( i ) ); @@ -720,7 +720,8 @@ Void VideoHandle::videoSelectionButtonEvent() } else { - DialogSubWindowSelector dialogWindowsSelection( this, m_pcMainWindowManager, SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); + DialogSubWindowSelector dialogWindowsSelection( this, m_pcMainWindowManager, + SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); QStringList cWindowListNames; for( Int i = 0; i < m_acPlayingSubWindows.size(); i++ ) { @@ -783,4 +784,3 @@ Void VideoHandle::toggleGrid( Bool checked ) qobject_cast( subWindowList.at( i ) )->getViewArea()->setGridVisible( checked ); } } - diff --git a/app/VideoHandle.h b/app/VideoHandle.h index 81d5285..9add246 100644 --- a/app/VideoHandle.h +++ b/app/VideoHandle.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -48,11 +48,11 @@ class VideoSubWindow; class FramePropertiesDock; class WidgetFrameNumber; -class VideoHandle: public QWidget +class VideoHandle : public QWidget { -Q_OBJECT - public: - VideoHandle( QWidget*, PlaYUVerSubWindowHandle * ); + Q_OBJECT + public: + VideoHandle( QWidget*, PlaYUVerSubWindowHandle* ); ~VideoHandle(); Void createActions(); @@ -70,7 +70,7 @@ Q_OBJECT Void openSubWindow( VideoSubWindow* subWindow ); -private: + private: QWidget* m_pcParet; PlaYUVerSubWindowHandle* m_pcMainWindowManager; enum @@ -97,8 +97,8 @@ private: WidgetFrameNumber* m_pcFrameNumInfo; // Tools Actions; - QActionGroup *actionGroupTools; - QSignalMapper *m_mapperTools; + QActionGroup* actionGroupTools; + QSignalMapper* m_mapperTools; UInt m_uiViewTool; QMenu* m_pcMenuVideo; @@ -114,7 +114,7 @@ private: VideoSubWindow* m_pcCurrentVideoSubWindow; QVector m_acPlayingSubWindows; - QTimer *m_pcPlayingTimer; + QTimer* m_pcPlayingTimer; Bool m_bIsPlaying; #if( _CONTROL_PLAYING_TIME_ == 1 ) @@ -126,10 +126,10 @@ private: UInt64 getMaxFrameNumber(); Void setTimerStatus(); -Q_SIGNALS: + Q_SIGNALS: void changed(); -private Q_SLOTS: + private Q_SLOTS: void update(); void updateSelectionArea( QRect area ); void closeSubWindow( SubWindowAbstract* subWindow ); @@ -144,7 +144,6 @@ private Q_SLOTS: void videoSelectionButtonEvent(); void setTool( int tool ); void toggleGrid( bool checked ); - }; -#endif // __VIDEOHANDLE_H__ +#endif // __VIDEOHANDLE_H__ diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 2a0bf15..1fc9474 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -43,14 +43,8 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStreamInfoVector& array for( Int i = 0; i < array.size(); i++ ) { d = array.at( i ); - out << d.m_cFilename - << d.m_uiWidth - << d.m_uiHeight - << d.m_iPelFormat - << d.m_uiBitsPelPixel - << d.m_iEndianness - << d.m_uiFrameRate - << d.m_uiFileSize; + out << d.m_cFilename << d.m_uiWidth << d.m_uiHeight << d.m_iPelFormat << d.m_uiBitsPelPixel << d.m_iEndianness + << d.m_uiFrameRate << d.m_uiFileSize; } return out; } @@ -88,17 +82,16 @@ Int findPlaYUVerStreamInfo( PlaYUVerStreamInfoVector array, QString filename ) * \brief Shows information about video sub window */ -class VideoInformation: public QWidget +class VideoInformation : public QWidget { -private: + private: QList m_cTopLeftTextList; QFont m_cTopLeftTextFont; QFont m_cCenterTextFont; Bool m_bBusyWindow; - public: - VideoInformation( QWidget *parent ) : - QWidget( parent ), - m_bBusyWindow( false ) + + public: + VideoInformation( QWidget* parent ) : QWidget( parent ), m_bBusyWindow( false ) { setPalette( Qt::transparent ); setAttribute( Qt::WA_TransparentForMouseEvents ); @@ -113,12 +106,9 @@ private: m_cTopLeftTextList.append( textLines.at( i ) ); } } - Void setBusyWindow( Bool bFlag ) - { - m_bBusyWindow = bFlag; - } -protected: - void paintEvent( QPaintEvent *event ) + Void setBusyWindow( Bool bFlag ) { m_bBusyWindow = bFlag; } + protected: + void paintEvent( QPaintEvent* event ) { QPainter painter( this ); painter.setFont( m_cTopLeftTextFont ); @@ -140,31 +130,35 @@ protected: } }; -VideoSubWindow::VideoSubWindow( enum VideoSubWindowCategories category, QWidget * parent ) : - SubWindowAbstract( parent, SubWindowAbstract::VIDEO_SUBWINDOW | category ), - m_bWindowBusy( false ), - m_pCurrStream( NULL ), - m_pcCurrFrame( NULL ), - m_pcCurrentDisplayModule( NULL ), - m_pcReferenceSubWindow( NULL ), - m_bIsPlaying( false ) +VideoSubWindow::VideoSubWindow( enum VideoSubWindowCategories category, QWidget* parent ) + : SubWindowAbstract( parent, SubWindowAbstract::VIDEO_SUBWINDOW | category ), + m_bWindowBusy( false ), + m_pCurrStream( NULL ), + m_pcCurrFrame( NULL ), + m_pcCurrentDisplayModule( NULL ), + m_pcReferenceSubWindow( NULL ), + m_bIsPlaying( false ) { - // Create a new scroll area inside the sub-window m_pcScrollArea = new QScrollArea; - connect( m_pcScrollArea->horizontalScrollBar(), SIGNAL( actionTriggered( int ) ), this, SLOT( updateCurScrollValues() ) ); - connect( m_pcScrollArea->verticalScrollBar(), SIGNAL( actionTriggered( int ) ), this, SLOT( updateCurScrollValues() ) ); + connect( m_pcScrollArea->horizontalScrollBar(), SIGNAL( actionTriggered( int ) ), this, + SLOT( updateCurScrollValues() ) ); + connect( m_pcScrollArea->verticalScrollBar(), SIGNAL( actionTriggered( int ) ), this, + SLOT( updateCurScrollValues() ) ); // Create a new interface to show images m_cViewArea = new ViewArea; - connect( m_cViewArea, SIGNAL( zoomFactorChanged_byWheel( double , QPoint) ), this, SLOT( adjustScrollBarByScale( double, QPoint ) ) ); - connect( m_cViewArea, SIGNAL( zoomFactorChanged_byWheel( double , QPoint) ), this, SIGNAL( zoomFactorChanged_SWindow( double, QPoint ) ) ); + connect( m_cViewArea, SIGNAL( zoomFactorChanged_byWheel( double, QPoint ) ), this, + SLOT( adjustScrollBarByScale( double, QPoint ) ) ); + connect( m_cViewArea, SIGNAL( zoomFactorChanged_byWheel( double, QPoint ) ), this, + SIGNAL( zoomFactorChanged_SWindow( double, QPoint ) ) ); connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, SLOT( adjustScrollBarByOffset( QPoint ) ) ); connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, SIGNAL( scrollBarMoved_SWindow( QPoint ) ) ); connect( m_cViewArea, SIGNAL( selectionChanged( QRect ) ), this, SLOT( updateSelectedArea( QRect ) ) ); - connect( m_cViewArea, SIGNAL( positionChanged( const QPoint & ) ), this, SLOT( updatePixelValueStatusBar( const QPoint & ) ) ); + connect( m_cViewArea, SIGNAL( positionChanged( const QPoint& ) ), this, + SLOT( updatePixelValueStatusBar( const QPoint& ) ) ); m_pcScrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_pcScrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); @@ -209,18 +203,18 @@ Void VideoSubWindow::keyPressEvent( QKeyEvent* event ) Bool bRet = false; switch( event->key() ) { - case Qt::Key_A: - bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_LEFT ); - break; - case Qt::Key_D: - bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_RIGHT ); - break; - case Qt::Key_W: - bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_UP ); - break; - case Qt::Key_S: - bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_DOWN ); - break; + case Qt::Key_A: + bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_LEFT ); + break; + case Qt::Key_D: + bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_RIGHT ); + break; + case Qt::Key_W: + bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_UP ); + break; + case Qt::Key_S: + bRet = m_pcCurrentDisplayModule->getModule()->keyPressed( MODULE_KEY_DOWN ); + break; } if( bRet ) { @@ -245,7 +239,7 @@ QSize VideoSubWindow::sizeHint() const { QSize maxSize; - QWidget *p = parentWidget(); + QWidget* p = parentWidget(); if( p ) { maxSize = p->size(); @@ -257,16 +251,16 @@ QSize VideoSubWindow::sizeHint() const return sizeHint( maxSize ); } -QSize VideoSubWindow::sizeHint( const QSize & maxSize ) const - { +QSize VideoSubWindow::sizeHint( const QSize& maxSize ) const +{ QSize isize; if( m_pcCurrFrame ) isize = QSize( m_pcCurrFrame->getWidth() + 50, m_pcCurrFrame->getHeight() + 50 ); else if( m_pCurrStream ) isize = QSize( m_pCurrStream->getWidth() + 50, m_pCurrStream->getHeight() + 50 ); -// If the VideoSubWindow needs more space that the avaiable, we'll give -// to the subwindow a reasonable size preserving the image aspect ratio. + // If the VideoSubWindow needs more space that the avaiable, we'll give + // to the subwindow a reasonable size preserving the image aspect ratio. if( !( isize.width() < maxSize.width() && isize.height() < maxSize.height() ) ) { isize.scale( maxSize, Qt::KeepAspectRatio ); @@ -296,7 +290,7 @@ Void VideoSubWindow::refreshSubWindow() close(); return; } - //seekAbsoluteEvent( currFrameNum ); + // seekAbsoluteEvent( currFrameNum ); } updateVideoWindowInfo(); refreshFrame(); @@ -319,8 +313,8 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) if( guessFormat( cFilename, Width, Height, InputFormat, BitsPel, Endianness ) || bForceDialog ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) - == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, + Endianness, FrameRate ) == QDialog::Rejected ) { return false; } @@ -332,8 +326,8 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) } catch( ... ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate ) - == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, + Endianness, FrameRate ) == QDialog::Rejected ) { return false; } @@ -367,8 +361,9 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) m_pCurrStream = new PlaYUVerStream; } - if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, streamInfo->m_iPelFormat, - streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate, true ) ) + if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, + streamInfo->m_iPelFormat, streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, + streamInfo->m_uiFrameRate, true ) ) { return false; } @@ -403,7 +398,7 @@ Void VideoSubWindow::updateVideoWindowInfo() } } } - //qDebug( ) << sourceWindowList; + // qDebug( ) << sourceWindowList; if( sourceWindowList.size() > 0 ) { m_pcVideoInfo->setInformationTopLeft( sourceWindowList ); @@ -415,20 +410,25 @@ Void VideoSubWindow::updateVideoWindowInfo() QString m_cCodedName = QString::fromStdString( m_pCurrStream->getCodecName() ); m_cStreamInformation = m_cFormatName + " | " + m_cCodedName; } -//#if 0 + //#if 0 if( m_pcCurrFrame ) { QString m_cPelFmtName = QString::fromStdString( m_pcCurrFrame->getPelFmtName() ); m_cStreamInformation += " | " + m_cPelFmtName; } -//#endif + //#endif if( m_cStreamInformation.isEmpty() ) { m_cStreamInformation = " "; } } -Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel, Int& rEndianness ) +Bool VideoSubWindow::guessFormat( QString filename, + UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBitsPerPixel, + Int& rEndianness ) { std::vector stdResList = PlaYUVerStream::stdResolutionSizes(); Bool bGuessed = true; @@ -504,7 +504,8 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int count = 0, module, frame_bytes, match; for( UInt i = 0; i < stdResList.size(); i++ ) { - frame_bytes = PlaYUVerFrame::getBytesPerFrame( stdResList[i].uiWidth, stdResList[i].uiHeight, rInputFormat, 8 ); + frame_bytes = + PlaYUVerFrame::getBytesPerFrame( stdResList[i].uiWidth, stdResList[i].uiHeight, rInputFormat, 8 ); module = uiFileSize % frame_bytes; if( module == 0 ) { @@ -521,7 +522,7 @@ Bool VideoSubWindow::guessFormat( QString filename, UInt& rWidth, UInt& rHeight, } } - // Guess bits per pixel - match %dbpp +// Guess bits per pixel - match %dbpp #if( QT_VERSION_PLAYUVER == 5 ) QRegularExpressionMatch BppMatch = QRegularExpression( "_\\d*bpp" ).match( FilenameShort ); if( BppMatch.hasMatch() ) @@ -668,7 +669,7 @@ Void VideoSubWindow::refreshFrame( Bool bThreaded ) m_cRefreshResult = QtConcurrent::run( this, &VideoSubWindow::refreshFrameOperation ); } else - #endif +#endif { refreshFrameOperation(); } @@ -682,7 +683,8 @@ Bool VideoSubWindow::save( QString filename ) PlaYUVerFrame* saveFrame = m_pcCurrFrame; if( m_cSelectedArea.isValid() ) { - saveFrame = new PlaYUVerFrame( m_pcCurrFrame, m_cSelectedArea.x(), m_cSelectedArea.y(), m_cSelectedArea.width(), m_cSelectedArea.height() ); + saveFrame = new PlaYUVerFrame( m_pcCurrFrame, m_cSelectedArea.x(), m_cSelectedArea.y(), m_cSelectedArea.width(), + m_cSelectedArea.height() ); } if( !saveFrame ) { @@ -792,7 +794,7 @@ Void VideoSubWindow::adjustScrollBarByOffset( QPoint Offset ) valueY = scrollBarV->minimum(); m_cCurrScroll.setY( valueY ); -// Update window scroll + // Update window scroll scrollBarH->setValue( m_cCurrScroll.x() ); scrollBarV->setValue( m_cCurrScroll.y() ); } @@ -836,15 +838,14 @@ Void VideoSubWindow::adjustScrollBarByScale( Double scale, QPoint center ) m_cCurrScroll.setY( value ); } -// Update window scroll + // Update window scroll scrollBarH->setValue( m_cCurrScroll.x() ); scrollBarV->setValue( m_cCurrScroll.y() ); - } Void VideoSubWindow::updateCurScrollValues() { - QScrollBar *scrollBar = m_pcScrollArea->horizontalScrollBar(); + QScrollBar* scrollBar = m_pcScrollArea->horizontalScrollBar(); m_cCurrScroll.setX( scrollBar->value() ); scrollBar = m_pcScrollArea->verticalScrollBar(); m_cCurrScroll.setY( scrollBar->value() ); @@ -852,7 +853,7 @@ Void VideoSubWindow::updateCurScrollValues() Void VideoSubWindow::setCurScrollValues() { - QScrollBar *scrollBar = m_pcScrollArea->horizontalScrollBar(); + QScrollBar* scrollBar = m_pcScrollArea->horizontalScrollBar(); scrollBar->setValue( m_cCurrScroll.x() ); scrollBar = m_pcScrollArea->verticalScrollBar(); scrollBar->setValue( m_cCurrScroll.y() ); @@ -872,7 +873,7 @@ Void VideoSubWindow::normalSize() Void VideoSubWindow::zoomToFit() { -// Scale to a smaller size that the real to a nicer look + // Scale to a smaller size that the real to a nicer look scaleView( getScrollSize() ); } @@ -899,7 +900,7 @@ Void VideoSubWindow::scaleView( Double scale, QPoint center ) } } -Void VideoSubWindow::scaleView( const QSize & size, QPoint center ) +Void VideoSubWindow::scaleView( const QSize& size, QPoint center ) { QSize imgViewSize; if( m_pcCurrFrame ) @@ -909,13 +910,13 @@ Void VideoSubWindow::scaleView( const QSize & size, QPoint center ) QSize newSize = imgViewSize; newSize.scale( size, Qt::KeepAspectRatio ); -// Calc the zoom factor + // Calc the zoom factor Double wfactor = 1; Double hfactor = 1; Double factor; - wfactor = ( Double )newSize.width() / imgViewSize.width(); - hfactor = ( Double )newSize.height() / imgViewSize.height(); + wfactor = (Double)newSize.width() / imgViewSize.width(); + hfactor = (Double)newSize.height() / imgViewSize.height(); if( wfactor < hfactor ) factor = wfactor; @@ -957,13 +958,15 @@ Void VideoSubWindow::updatePixelValueStatusBar( const QPoint& pos ) if( ColorSpace == PlaYUVerPixel::COLOR_YUV ) { sPixelValue = m_pcCurrFrame->getPixelValue( pos.x(), pos.y() ); - strStatus.append( QString( "Y: %1 U: %2 V: %3" ).arg( sPixelValue.Y() ).arg( sPixelValue.Cb() ).arg( sPixelValue.Cr() ) ); + strStatus.append( + QString( "Y: %1 U: %2 V: %3" ).arg( sPixelValue.Y() ).arg( sPixelValue.Cb() ).arg( sPixelValue.Cr() ) ); } if( ( ColorSpace == PlaYUVerPixel::COLOR_RGB ) ) { sPixelValue = m_pcCurrFrame->getPixelValue( pos.x(), pos.y() ); - strStatus.append( QString( "R: %1 G: %2 B: %3" ).arg( sPixelValue.R() ).arg( sPixelValue.G() ).arg( sPixelValue.B() ) ); + strStatus.append( + QString( "R: %1 G: %2 B: %3" ).arg( sPixelValue.R() ).arg( sPixelValue.G() ).arg( sPixelValue.B() ) ); } emit updateStatusBar( strStatus ); } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index badbb44..78d1f39 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -59,12 +59,11 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStreamInfoVector& d ); QDataStream& operator>>( QDataStream& in, PlaYUVerStreamInfoVector& d ); Int findPlaYUVerStreamInfo( PlaYUVerStreamInfoVector array, QString filename ); -class VideoSubWindow: public SubWindowAbstract +class VideoSubWindow : public SubWindowAbstract { -Q_OBJECT - -private: + Q_OBJECT + private: Bool m_bWindowBusy; QScrollArea* m_pcScrollArea; @@ -88,7 +87,7 @@ private: VideoSubWindow* m_pcReferenceSubWindow; - //QString m_cWindowShortName; + // QString m_cWindowShortName; QString m_cCurrFileName; Bool m_bIsPlaying; @@ -103,24 +102,29 @@ private: Void refreshFrameOperation(); - static Bool guessFormat( QString filename, UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPixel, Int& rEndianness ); + static Bool guessFormat( QString filename, + UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBitsPerPixel, + Int& rEndianness ); /** * Private zoom function to handle * zoom to fit */ - Void scaleView( const QSize & size, QPoint center = QPoint() ); + Void scaleView( const QSize& size, QPoint center = QPoint() ); Void updateVideoWindowInfo(); QSize getScrollSize(); -public: + public: enum VideoSubWindowCategories { VIDEO_STREAM_SUBWINDOW = SubWindowAbstract::VIDEO_STREAM_SUBWINDOW, MODULE_SUBWINDOW = SubWindowAbstract::MODULE_SUBWINDOW, }; - VideoSubWindow( enum VideoSubWindowCategories category, QWidget * parent = 0 ); + VideoSubWindow( enum VideoSubWindowCategories category, QWidget* parent = 0 ); ~VideoSubWindow(); Bool loadFile( QString cFilename, Bool bForceDialog = false ); @@ -136,49 +140,19 @@ public: Bool playEvent(); Void stop(); - Bool isPlaying() - { - return m_bIsPlaying; - } - + Bool isPlaying() { return m_bIsPlaying; } Void seekAbsoluteEvent( UInt new_frame_num ); Void seekRelativeEvent( Bool bIsFoward ); Void setCurrFrame( PlaYUVerFrame* pcCurrFrame ); - QScrollArea* getScroll() - { - return m_pcScrollArea; - } - PlaYUVerStreamInfo getStreamInfo() - { - return m_sStreamInfo; - } - QString getStreamInformation() - { - return m_cStreamInformation; - } - - PlaYUVerStream* getInputStream() - { - return m_pCurrStream; - } - - PlaYUVerStream* getCurrStream() - { - return m_pCurrStream; - } - - PlaYUVerFrame* getCurrFrame() - { - return m_pcCurrFrame; - } - - ViewArea* getViewArea() - { - return m_cViewArea; - } - + QScrollArea* getScroll() { return m_pcScrollArea; } + PlaYUVerStreamInfo getStreamInfo() { return m_sStreamInfo; } + QString getStreamInformation() { return m_cStreamInformation; } + PlaYUVerStream* getInputStream() { return m_pCurrStream; } + PlaYUVerStream* getCurrStream() { return m_pCurrStream; } + PlaYUVerFrame* getCurrFrame() { return m_pcCurrFrame; } + ViewArea* getViewArea() { return m_cViewArea; } Void setRefSubWindow( VideoSubWindow* subWindow ) { m_pcReferenceSubWindow = NULL; @@ -187,11 +161,7 @@ public: m_pcReferenceSubWindow = subWindow; } - VideoSubWindow* getRefSubWindow() - { - return m_pcReferenceSubWindow; - } - + VideoSubWindow* getRefSubWindow() { return m_pcReferenceSubWindow; } /** * Functions to enable a module in the * current SubWindow @@ -200,11 +170,7 @@ public: Void disableModule( PlaYUVerAppModuleIf* pcModule = NULL ); Void associateModule( PlaYUVerAppModuleIf* pcModule ); - PlaYUVerAppModuleIf* getDisplayModule() - { - return m_pcCurrentDisplayModule; - } - + PlaYUVerAppModuleIf* getDisplayModule() { return m_pcCurrentDisplayModule; } QList getModuleArray() { QList apcModulesArray; @@ -222,40 +188,24 @@ public: Void scaleView( Double scale, QPoint center = QPoint() ); Void zoomToFactor( Double factor, QPoint center = QPoint() ); - Double getScaleFactor() - { - return m_cViewArea->getZoomFactor(); - } - + Double getScaleFactor() { return m_cViewArea->getZoomFactor(); } /** * Size related functions */ QSize sizeHint() const; - QSize sizeHint( const QSize & ) const; - - QString getCurrentFileName() - { - return m_cFilename; - } - - Bool getIsModule() - { - return getCategory() | SubWindowAbstract::MODULE_SUBWINDOW; - } - - Void clearWindowBusy() - { - m_bWindowBusy = false; - } + QSize sizeHint( const QSize& ) const; + QString getCurrentFileName() { return m_cFilename; } + Bool getIsModule() { return getCategory() | SubWindowAbstract::MODULE_SUBWINDOW; } + Void clearWindowBusy() { m_bWindowBusy = false; } Void setFillWindow( Bool bFlag ); -protected: + protected: Void keyPressEvent( QKeyEvent* event ); Void resizeEvent( QResizeEvent* event ); - //void closeEvent( QCloseEvent *event ); + // void closeEvent( QCloseEvent *event ); -public Q_SLOTS: + public Q_SLOTS: void updateWindowOnTimeout(); void adjustScrollBarByScale( double scale, QPoint center ); void adjustScrollBarByOffset( QPoint Offset ); @@ -268,5 +218,4 @@ public Q_SLOTS: Q_DECLARE_METATYPE( PlaYUVerStreamInfo ); Q_DECLARE_METATYPE( PlaYUVerStreamInfoVector ); -#endif // __VIDEOSUBWINDOW_H__ - +#endif // __VIDEOSUBWINDOW_H__ diff --git a/app/ViewArea.cpp b/app/ViewArea.cpp index de6428d..397802b 100644 --- a/app/ViewArea.cpp +++ b/app/ViewArea.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -43,8 +43,7 @@ static const QColor selectionColor = Qt::cyan; static const QColor imageMaskColor = Qt::green; static const QColor eraserColor = Qt::red; -ViewArea::ViewArea( QWidget *parent ) : - QWidget( parent ) +ViewArea::ViewArea( QWidget* parent ) : QWidget( parent ) { setMouseTracking( true ); @@ -73,11 +72,12 @@ Void ViewArea::setImage( PlaYUVerFrame* pcFrame ) m_pcCurrFrame = pcFrame; m_uiPixelHalfScale = 1 << ( m_pcCurrFrame->getBitsPel() - 1 ); m_pcCurrFrame->fillRGBBuffer(); - QImage qimg = QImage( m_pcCurrFrame->getRGBBuffer(), m_pcCurrFrame->getWidth(), m_pcCurrFrame->getHeight(), QImage::Format_RGB32 ); + QImage qimg = QImage( m_pcCurrFrame->getRGBBuffer(), m_pcCurrFrame->getWidth(), m_pcCurrFrame->getHeight(), + QImage::Format_RGB32 ); setImage( QPixmap::fromImage( qimg ) ); } -Void ViewArea::setImage( const QPixmap &pixmap ) +Void ViewArea::setImage( const QPixmap& pixmap ) { m_pixmap = pixmap; m_mask = QBitmap( pixmap.width(), pixmap.height() ); @@ -103,21 +103,21 @@ Void ViewArea::setTool( UInt view ) { switch( view ) { - case NavigationView: - m_eTool = NavigationTool; - m_snapToGrid = false; - m_blockTrackEnable = false; - break; - case NormalSelectionView: - m_eTool = SelectionTool; - m_snapToGrid = false; - m_blockTrackEnable = false; - break; - case BlockSelectionView: - m_eTool = SelectionTool; - m_snapToGrid = true; - m_blockTrackEnable = false; - break; + case NavigationView: + m_eTool = NavigationTool; + m_snapToGrid = false; + m_blockTrackEnable = false; + break; + case NormalSelectionView: + m_eTool = SelectionTool; + m_snapToGrid = false; + m_blockTrackEnable = false; + break; + case BlockSelectionView: + m_eTool = SelectionTool; + m_snapToGrid = true; + m_blockTrackEnable = false; + break; } if( m_eTool != SelectionTool ) @@ -225,7 +225,7 @@ Double ViewArea::scaleZoomFactor( Double scale, QPoint center, QSize minimumSize return new_scale; } -//Void ViewArea::setMode( Int mode ) +// Void ViewArea::setMode( Int mode ) //{ // if( m_mode == mode ) // return; @@ -234,44 +234,44 @@ Double ViewArea::scaleZoomFactor( Double scale, QPoint center, QSize minimumSize // update(); //} // -//Void ViewArea::setNormalMode() +// Void ViewArea::setNormalMode() //{ // setMode( NormalMode ); //} // -//Void ViewArea::setMaskMode() +// Void ViewArea::setMaskMode() //{ // setMode( MaskMode ); //} // -//Void ViewArea::setMaskColor( const QColor &color ) +// Void ViewArea::setMaskColor( const QColor &color ) //{ // m_maskColor = color; // update(); //} // -//Void ViewArea::setMaskTool() +// Void ViewArea::setMaskTool() //{ // setMode( MaskMode ); // setTool( MaskTool ); // m_blockTrackEnable = true; //} // -//Void ViewArea::setEraserTool() +// Void ViewArea::setEraserTool() //{ // setMode( MaskMode ); // setTool( EraserTool ); // m_blockTrackEnable = true; //} // -//Void ViewArea::setSelectionTool() +// Void ViewArea::setSelectionTool() //{ // setMode( NormalMode ); // setTool( SelectionTool ); // m_blockTrackEnable = false; //} // -//Void ViewArea::setBlockSelectionTool() +// Void ViewArea::setBlockSelectionTool() //{ // setMode( NormalMode ); // setTool( BlockSelectionTool ); @@ -283,7 +283,7 @@ Void ViewArea::setSnapToGrid( Bool enable ) m_snapToGrid = enable; } -//Void ViewArea::setSelectedArea( QRect &rect ) +// Void ViewArea::setSelectedArea( QRect &rect ) //{ // if( rect.isNull() ) // { @@ -323,33 +323,33 @@ Void ViewArea::initZoomWinRect() if( iHorizontalImg ) { - dSizeRatio = ( double )m_pixmap.width() / ( double )m_pixmap.height(); + dSizeRatio = (double)m_pixmap.width() / (double)m_pixmap.height(); } else { - dSizeRatio = ( double )m_pixmap.height() / ( double )m_pixmap.width(); + dSizeRatio = (double)m_pixmap.height() / (double)m_pixmap.width(); } if( dSizeRatio > 5.0 ) { if( iHorizontalImg ) { - dWinZoomRatio = ( double )( m_pixmap.width() * 1024 / iMaxX ) / 1000.0; + dWinZoomRatio = (double)( m_pixmap.width() * 1024 / iMaxX ) / 1000.0; } else { - dWinZoomRatio = ( double )( m_pixmap.height() * 1024 / iMaxY ) / 1000.0; + dWinZoomRatio = (double)( m_pixmap.height() * 1024 / iMaxY ) / 1000.0; } } else { if( iHorizontalImg ) { - dWinZoomRatio = ( double )( m_pixmap.height() * 1024 / iMinY ) / 1000.0; + dWinZoomRatio = (double)( m_pixmap.height() * 1024 / iMinY ) / 1000.0; } else { - dWinZoomRatio = ( double )( m_pixmap.width() * 1024 / iMinX ) / 1000.0; + dWinZoomRatio = (double)( m_pixmap.width() * 1024 / iMinX ) / 1000.0; } } @@ -365,7 +365,7 @@ Void ViewArea::updateSize() Int h = m_pixmap.height() * m_dZoomFactor; setMinimumSize( w, h ); - QWidget *p = parentWidget(); + QWidget* p = parentWidget(); if( p ) { // If the parent size is bigger than the minimum area to view the @@ -401,7 +401,7 @@ Void ViewArea::updateOffset() //////////////////////////////////////////////////////////////////////////////// // Resize Event //////////////////////////////////////////////////////////////////////////////// -Void ViewArea::resizeEvent( QResizeEvent *event ) +Void ViewArea::resizeEvent( QResizeEvent* event ) { if( size().isEmpty() || m_pixmap.isNull() ) return; @@ -414,7 +414,7 @@ Void ViewArea::resizeEvent( QResizeEvent *event ) // PaInt Event //////////////////////////////////////////////////////////////////////////////// -Void ViewArea::paintEvent( QPaintEvent *event ) +Void ViewArea::paintEvent( QPaintEvent* event ) { QRect winRect = event->rect(); @@ -471,7 +471,8 @@ Void ViewArea::paintEvent( QPaintEvent *event ) /* if( m_xOffset || m_yOffset ) { paInter.setPen( Qt::black ); - paInter.drawRect( m_xOffset - 1, m_yOffset - 1, m_pixmap.width() * m_dZoomFactor + 1, m_pixmap.height() * m_dZoomFactor + 1 ); + paInter.drawRect( m_xOffset - 1, m_yOffset - 1, m_pixmap.width() * m_dZoomFactor + 1, m_pixmap.height() * + m_dZoomFactor + 1 ); }*/ // Draw pixel values in grid @@ -507,9 +508,9 @@ Void ViewArea::paintEvent( QPaintEvent *event ) else paInter.setPen( QColor( Qt::black ) ); - paInter.drawText( pixelRect, Qt::AlignCenter, - "Y: " + QString::number( sPixelValue.Y() ) + "\n" + "U: " + QString::number( sPixelValue.Cb() ) + "\n" + "V: " - + QString::number( sPixelValue.Cr() ) ); + paInter.drawText( pixelRect, Qt::AlignCenter, "Y: " + QString::number( sPixelValue.Y() ) + "\n" + "U: " + + QString::number( sPixelValue.Cb() ) + "\n" + "V: " + + QString::number( sPixelValue.Cr() ) ); } if( frFormat == PlaYUVerPixel::COLOR_GRAY ) { @@ -532,9 +533,9 @@ Void ViewArea::paintEvent( QPaintEvent *event ) else paInter.setPen( QColor( Qt::black ) ); - paInter.drawText( pixelRect, Qt::AlignCenter, - "R: " + QString::number( sPixelValue.R() ) + "\n" + "G: " + QString::number( sPixelValue.G() ) + "\n" + "B: " - + QString::number( sPixelValue.B() ) ); + paInter.drawText( pixelRect, Qt::AlignCenter, "R: " + QString::number( sPixelValue.R() ) + "\n" + "G: " + + QString::number( sPixelValue.G() ) + "\n" + "B: " + + QString::number( sPixelValue.B() ) ); } } } @@ -558,7 +559,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) } } - // VISIBLE ZOOM RECT +// VISIBLE ZOOM RECT #if 0 if( m_visibleZoomRect && m_zoomWinTimer.isActive() ) { @@ -626,7 +627,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) paInter.setPen( Qt::darkCyan ); -// paInter.drawRect( sr/*m_selectedArea*/ ); + // paInter.drawRect( sr/*m_selectedArea*/ ); } else { @@ -641,18 +642,17 @@ Void ViewArea::paintEvent( QPaintEvent *event ) QRect imgr = viewToWindow( QRect( 0, 0, m_pixmap.width(), m_pixmap.height() ) ); myPath.addRect( imgr ); - myPath.addRect( sr ); //m_selectedArea + myPath.addRect( sr ); // m_selectedArea paInter.drawPath( myPath ); // 2) Draw the selection rectangle paInter.setBrush( Qt::NoBrush ); paInter.setPen( Qt::darkCyan ); -// paInter.drawRect( sr/*m_selectedArea*/ ); + // paInter.drawRect( sr/*m_selectedArea*/ ); } if( !ir.isNull() ) - paInter.drawRect( sr/*m_selectedArea*/); - + paInter.drawRect( sr /*m_selectedArea*/ ); } // Mask Mode ---------------------------------------------------------- @@ -684,22 +684,22 @@ Void ViewArea::paintEvent( QPaintEvent *event ) { switch( tool() ) { - case MaskTool: + case MaskTool: { - if( m_maskColor.isValid() ) - color = m_maskColor; - else - color = imageMaskColor; + if( m_maskColor.isValid() ) + color = m_maskColor; + else + color = imageMaskColor; - break; - } - case EraserTool: + break; + } + case EraserTool: { - color = eraserColor; - break; - } - default: - color = selectionColor; // ?Problems! + color = eraserColor; + break; + } + default: + color = selectionColor; // ?Problems! } color.setAlpha( 120 ); @@ -720,7 +720,7 @@ Void ViewArea::paintEvent( QPaintEvent *event ) //////////////////////////////////////////////////////////////////////////////// // Mouse Events //////////////////////////////////////////////////////////////////////////////// -Void ViewArea::wheelEvent( QWheelEvent *event ) +Void ViewArea::wheelEvent( QWheelEvent* event ) { Double scale; Double usedScale; @@ -733,7 +733,7 @@ Void ViewArea::wheelEvent( QWheelEvent *event ) else scale = 0.8; - QWidget *p = parentWidget(); + QWidget* p = parentWidget(); QSize minimumSize = QSize( p->size().width() - 5, p->size().height() - 5 ); usedScale = scaleZoomFactor( scale, event->pos(), minimumSize ); if( usedScale != 1.0 ) @@ -743,7 +743,7 @@ Void ViewArea::wheelEvent( QWheelEvent *event ) } } -Void ViewArea::mousePressEvent( QMouseEvent *event ) +Void ViewArea::mousePressEvent( QMouseEvent* event ) { event->accept(); @@ -751,7 +751,6 @@ Void ViewArea::mousePressEvent( QMouseEvent *event ) if( event->button() == Qt::MidButton ) { - } if( event->button() == Qt::LeftButton ) { @@ -802,7 +801,7 @@ Void ViewArea::mousePressEvent( QMouseEvent *event ) } // Block selection -// m_selectedArea = m_grid.rectContains( m_lastPos ); + // m_selectedArea = m_grid.rectContains( m_lastPos ); QRect updateRect = viewToWindow( m_selectedArea ); updateRect.adjust( 0, 0, 1, 1 ); @@ -810,15 +809,15 @@ Void ViewArea::mousePressEvent( QMouseEvent *event ) } } -Void ViewArea::mouseMoveEvent( QMouseEvent *event ) +Void ViewArea::mouseMoveEvent( QMouseEvent* event ) { event->accept(); #ifndef _MSC_VER // Add this code line to aVoid slow navigation with some specific mouses // This seems to always appear on windows - if( qApp->hasPendingEvents()) - return; + if( qApp->hasPendingEvents() ) + return; #endif QPoint actualPos = windowToView( event->pos() ); @@ -866,7 +865,7 @@ Void ViewArea::mouseMoveEvent( QMouseEvent *event ) // From left to right if( m_lastPos.x() < actualPos.x() ) { - QPoint bottomR = actualPos; // - QPoint( 1, 1 ); + QPoint bottomR = actualPos; // - QPoint( 1, 1 ); m_selectedArea = QRect( m_lastPos, bottomR ); } // From right to left @@ -891,7 +890,7 @@ Void ViewArea::mouseMoveEvent( QMouseEvent *event ) // From right to left else { - QPoint bottomR = m_lastPos; // - QPoint( 1, 1 ); + QPoint bottomR = m_lastPos; // - QPoint( 1, 1 ); m_selectedArea = QRect( actualPos, bottomR ); } } @@ -917,15 +916,15 @@ Void ViewArea::mouseMoveEvent( QMouseEvent *event ) m_selectedArea &= QRect( 0, 0, m_pixmap.width(), m_pixmap.height() ); // Update only the united area -// updateRect = updateRect.united( viewToWindow( m_selectedArea ) ); + // updateRect = updateRect.united( viewToWindow( m_selectedArea ) ); // "When rendering with a one pixel wide pen the QRect's // boundary line will be rendered to the right and below the // mathematical rectangle's boundary line.", in QT4 doc. // Our selection pen width is 1, let's adjust the rendering area. -// updateRect.adjust( 0, 0, 1, 1 ); + // updateRect.adjust( 0, 0, 1, 1 ); -// update( updateRect.normalized() ); + // update( updateRect.normalized() ); update(); } return; @@ -952,7 +951,7 @@ Void ViewArea::mouseMoveEvent( QMouseEvent *event ) } } -Void ViewArea::mouseReleaseEvent( QMouseEvent *event ) +Void ViewArea::mouseReleaseEvent( QMouseEvent* event ) { event->accept(); @@ -974,7 +973,6 @@ Void ViewArea::mouseReleaseEvent( QMouseEvent *event ) m_selectedArea = QRect(); } emit selectionChanged( m_selectedArea ); - } // Mask Mode ----------------------------------------------------------- @@ -997,9 +995,8 @@ Void ViewArea::mouseReleaseEvent( QMouseEvent *event ) //////////////////////////////////////////////////////////////////////////////// -Bool ViewArea::isPosValid( const QPoint &pos ) const - { - +Bool ViewArea::isPosValid( const QPoint& pos ) const +{ if( pos.x() < 0 || pos.y() < 0 || pos.x() >= m_pixmap.width() || pos.y() >= m_pixmap.height() ) return false; else @@ -1009,7 +1006,7 @@ Bool ViewArea::isPosValid( const QPoint &pos ) const //////////////////////////////////////////////////////////////////////////////// QPoint ViewArea::windowToView( const QPoint& pt ) const - { +{ QPoint p; p.setX( static_cast( ( pt.x() - m_xOffset ) / m_dZoomFactor ) ); p.setY( static_cast( ( pt.y() - m_yOffset ) / m_dZoomFactor ) ); @@ -1018,20 +1015,20 @@ QPoint ViewArea::windowToView( const QPoint& pt ) const } QRect ViewArea::windowToView( const QRect& rc ) const - { +{ QRect r; r.setTopLeft( windowToView( rc.topLeft() ) ); -// r.setRight ( (Int)( ceil(( rc.right() - m_xOffset)/m_dZoomFactor ))); -// r.setBottom( (Int)( ceil(( rc.bottom()- m_yOffset)/m_dZoomFactor ))); -// r.setRight ( static_cast(( rc.right() - m_xOffset ) / m_dZoomFactor +1)); -// r.setBottom( static_cast(( rc.bottom() - m_xOffset ) / m_dZoomFactor+1)); + // r.setRight ( (Int)( ceil(( rc.right() - m_xOffset)/m_dZoomFactor ))); + // r.setBottom( (Int)( ceil(( rc.bottom()- m_yOffset)/m_dZoomFactor ))); + // r.setRight ( static_cast(( rc.right() - m_xOffset ) / m_dZoomFactor +1)); + // r.setBottom( static_cast(( rc.bottom() - m_xOffset ) / m_dZoomFactor+1)); r.setBottomRight( windowToView( rc.bottomRight() ) ); return r; } QPoint ViewArea::viewToWindow( const QPoint& pt ) const - { +{ QPoint p; p.setX( static_cast( pt.x() * m_dZoomFactor + m_xOffset ) ); @@ -1041,17 +1038,17 @@ QPoint ViewArea::viewToWindow( const QPoint& pt ) const } QRect ViewArea::viewToWindow( const QRect& rc ) const - { +{ QRect r; r.setTopLeft( viewToWindow( rc.topLeft() ) ); -// r.setRight ( (Int)( ceil(( rc.right() +1+m_xOffset )*m_dZoomFactor ) - 1 )); -// r.setBottom( (Int)( ceil(( rc.bottom()+1+m_yOffset )*m_dZoomFactor ) - 1 )); -// r.setRight ( (Int)( ceil(( rc.right()+0.5)*m_dZoomFactor )+ m_xOffset )-1); -// r.setBottom( (Int)( ceil(( rc.bottom()+0.5)*m_dZoomFactor ) +m_yOffset )-1); -// qDebug()<<"Right = "<< r.right(); -// r.setRight ( static_cast(( rc.right()+1) * m_dZoomFactor + m_xOffset -1) ); -// r.setBottom( static_cast(( rc.bottom()+1) * m_dZoomFactor + m_yOffset -1)); + // r.setRight ( (Int)( ceil(( rc.right() +1+m_xOffset )*m_dZoomFactor ) - 1 )); + // r.setBottom( (Int)( ceil(( rc.bottom()+1+m_yOffset )*m_dZoomFactor ) - 1 )); + // r.setRight ( (Int)( ceil(( rc.right()+0.5)*m_dZoomFactor )+ m_xOffset )-1); + // r.setBottom( (Int)( ceil(( rc.bottom()+0.5)*m_dZoomFactor ) +m_yOffset )-1); + // qDebug()<<"Right = "<< r.right(); + // r.setRight ( static_cast(( rc.right()+1) * m_dZoomFactor + m_xOffset -1) ); + // r.setBottom( static_cast(( rc.bottom()+1) * m_dZoomFactor + m_yOffset -1)); r.setBottomRight( viewToWindow( rc.bottomRight() ) ); return r; @@ -1060,31 +1057,31 @@ QRect ViewArea::viewToWindow( const QRect& rc ) const //////////////////////////////////////////////////////////////////////////////// // Masks Management //////////////////////////////////////////////////////////////////////////////// -Void ViewArea::updateMask( const QRect &rect ) +Void ViewArea::updateMask( const QRect& rect ) { switch( tool() ) { - case MaskTool: + case MaskTool: { - // Add rect to the mask - QPainter paInter( &m_mask ); - paInter.setBrush( Qt::color1 ); - paInter.setPen( Qt::NoPen ); - paInter.drawRect( rect ); - paInter.end(); - break; - } - case EraserTool: + // Add rect to the mask + QPainter paInter( &m_mask ); + paInter.setBrush( Qt::color1 ); + paInter.setPen( Qt::NoPen ); + paInter.drawRect( rect ); + paInter.end(); + break; + } + case EraserTool: { - // Clears rect area in the mask - QPainter paInter( &m_mask ); - paInter.setBrush( Qt::color0 ); - paInter.setPen( Qt::NoPen ); - paInter.drawRect( rect ); - paInter.end(); - break; - } - default: /* Do Nothing */ - ; + // Clears rect area in the mask + QPainter paInter( &m_mask ); + paInter.setBrush( Qt::color0 ); + paInter.setPen( Qt::NoPen ); + paInter.drawRect( rect ); + paInter.end(); + break; + } + default: /* Do Nothing */ + ; } } diff --git a/app/ViewArea.h b/app/ViewArea.h index 31a5e17..1edd931 100644 --- a/app/ViewArea.h +++ b/app/ViewArea.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -41,12 +41,11 @@ class PlaYUVerStream; /** * */ -class ViewArea: public QWidget +class ViewArea : public QWidget { -Q_OBJECT - -public: + Q_OBJECT + public: enum ViewModes { NavigationView, @@ -54,13 +53,13 @@ public: BlockSelectionView, }; - ViewArea( QWidget *parent = 0 ); + ViewArea( QWidget* parent = 0 ); Void setImage( PlaYUVerFrame* pcFrame ); - Void setImage( const QPixmap &pixmap ); + Void setImage( const QPixmap& pixmap ); Void setMode( Int mode ); - Void setMaskColor( const QColor &color = QColor() ); + Void setMaskColor( const QColor& color = QColor() ); /** * Clears any contents. @@ -79,65 +78,43 @@ public: */ Void clearMask(); - QPixmap image() const - { - return m_pixmap; - } - QBitmap mask() const - { - return m_mask; - } - QRect selectedArea() const - { - return m_selectedArea; - } - GridManager gridManager() const - { - return m_grid; - } - - QColor maskColor() const - { - return m_maskColor; - } - - Double getZoomFactor() - { - return m_dZoomFactor; - } - + QPixmap image() const { return m_pixmap; } + QBitmap mask() const { return m_mask; } + QRect selectedArea() const { return m_selectedArea; } + GridManager gridManager() const { return m_grid; } + QColor maskColor() const { return m_maskColor; } + Double getZoomFactor() { return m_dZoomFactor; } // Scale function. Return used scale value (it may change when it touches the min or max zoom value) Double scaleZoomFactor( Double scale, QPoint center, QSize minimumSize ); -Q_SIGNALS: - void selectionChanged( const QRect &rect ); - void positionChanged( const QPoint &pos ); + Q_SIGNALS: + void selectionChanged( const QRect& rect ); + void positionChanged( const QPoint& pos ); void scrollBarMoved( QPoint offset ); void zoomFactorChanged_byWheel( const double factor, const QPoint center ); -public Q_SLOTS: -// Void setNormalMode(); -// Void setMaskMode(); -// Void setMaskTool(); -// Void setEraserTool(); -// Void setNormalSelectionTool(); -// Void setBlockSelectionTool(); + public Q_SLOTS: + // Void setNormalMode(); + // Void setMaskMode(); + // Void setMaskTool(); + // Void setEraserTool(); + // Void setNormalSelectionTool(); + // Void setBlockSelectionTool(); void setSnapToGrid( bool enable ); // void setSelectedArea( QRect &rect ); -protected: - Void paintEvent( QPaintEvent *event ); - Void resizeEvent( QResizeEvent * event ); - Void mousePressEvent( QMouseEvent *event ); - Void mouseMoveEvent( QMouseEvent *event ); - Void mouseReleaseEvent( QMouseEvent *event ); - Void wheelEvent( QWheelEvent *event ); + protected: + Void paintEvent( QPaintEvent* event ); + Void resizeEvent( QResizeEvent* event ); + Void mousePressEvent( QMouseEvent* event ); + Void mouseMoveEvent( QMouseEvent* event ); + Void mouseReleaseEvent( QMouseEvent* event ); + Void wheelEvent( QWheelEvent* event ); Void updateSize(); Void updateOffset(); -private: - + private: enum ViewMode { NormalMode, @@ -152,22 +129,14 @@ private: EraserTool }; - ViewMode mode() const - { - return m_mode; - } - - Tool tool() const - { - return m_eTool; - } - + ViewMode mode() const { return m_mode; } + Tool tool() const { return m_eTool; } Void initZoomWinRect(); Void startZoomWinTimer(); Void setZoomFactor( Double ); - Bool isPosValid( const QPoint &pos ) const; - Void updateMask( const QRect &rect ); + Bool isPosValid( const QPoint& pos ) const; + Void updateMask( const QRect& rect ); QPoint windowToView( const QPoint& pt ) const; QRect windowToView( const QRect& rc ) const; @@ -175,7 +144,7 @@ private: QPoint viewToWindow( const QPoint& pt ) const; QRect viewToWindow( const QRect& rc ) const; - PlaYUVerFrame *m_pcCurrFrame; + PlaYUVerFrame* m_pcCurrFrame; Pel m_uiPixelHalfScale; @@ -202,7 +171,6 @@ private: Bool m_snapToGrid; Bool m_cursorInGrid; Bool m_visibleZoomRect; - }; -#endif // __VIEWAREA_H__ +#endif // __VIEWAREA_H__ diff --git a/app/WidgetFrameNumber.cpp b/app/WidgetFrameNumber.cpp index 81d94ca..4b99e86 100644 --- a/app/WidgetFrameNumber.cpp +++ b/app/WidgetFrameNumber.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,8 +31,7 @@ #endif #include "WidgetFrameNumber.h" -WidgetFrameNumber::WidgetFrameNumber( QWidget *parent ) : - QWidget( parent ) +WidgetFrameNumber::WidgetFrameNumber( QWidget* parent ) : QWidget( parent ) { QHBoxLayout* mainlayout = new QHBoxLayout; m_pcCurrFrameNumLabel = new QLabel; @@ -40,7 +39,7 @@ WidgetFrameNumber::WidgetFrameNumber( QWidget *parent ) : m_pcCurrFrameNumLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) ); m_pcCurrFrameNumLabel->setMinimumWidth( 25 ); m_pcCurrFrameNumLabel->setAlignment( Qt::AlignRight ); - QLabel *forwardslash = new QLabel; + QLabel* forwardslash = new QLabel; forwardslash->setText( "/" ); m_pcTotalFrameNumLabel = new QLabel; m_pcTotalFrameNumLabel->setText( "-" ); @@ -65,4 +64,3 @@ Void WidgetFrameNumber::clear() m_pcCurrFrameNumLabel->setText( "-" ); m_pcTotalFrameNumLabel->setText( "-" ); } - diff --git a/app/WidgetFrameNumber.h b/app/WidgetFrameNumber.h index d9af7f9..495f0ef 100644 --- a/app/WidgetFrameNumber.h +++ b/app/WidgetFrameNumber.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,17 +34,17 @@ #include #endif -class WidgetFrameNumber: public QWidget +class WidgetFrameNumber : public QWidget { -public: - WidgetFrameNumber( QWidget *parent = 0 ); + public: + WidgetFrameNumber( QWidget* parent = 0 ); Void setCurrFrameNum( Int number ); Void setTotalFrameNum( Int number ); Void clear(); - private: - QLabel *m_pcCurrFrameNumLabel; - QLabel *m_pcTotalFrameNumLabel; + private: + QLabel* m_pcCurrFrameNumLabel; + QLabel* m_pcTotalFrameNumLabel; }; -#endif // __WIDGETFRAMENUMBER_H__ +#endif // __WIDGETFRAMENUMBER_H__ diff --git a/app/external/qcustomplot.cpp b/app/external/qcustomplot.cpp index ad267b6..41905a8 100644 --- a/app/external/qcustomplot.cpp +++ b/app/external/qcustomplot.cpp @@ -25,20 +25,17 @@ #include "qcustomplot.h" - - - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// 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 @@ -48,10 +45,7 @@ /*! Creates a new QCPPainter instance and sets default values */ -QCPPainter::QCPPainter() : - QPainter(), - mModes(pmDefault), - mIsAntialiasing(false) +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 @@ -60,17 +54,15 @@ QCPPainter::QCPPainter() : /*! 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) +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); +#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 } @@ -81,58 +73,58 @@ 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) +void QCPPainter::setPen( const QPen& pen ) { - QPainter::setPen(pen); - if (mModes.testFlag(pmNonCosmetic)) + 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) +void QCPPainter::setPen( const QColor& color ) { - QPainter::setPen(color); - if (mModes.testFlag(pmNonCosmetic)) + 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) +void QCPPainter::setPen( Qt::PenStyle penStyle ) { - QPainter::setPen(penStyle); - if (mModes.testFlag(pmNonCosmetic)) + 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) +void QCPPainter::drawLine( const QLineF& line ) { - if (mIsAntialiasing || mModes.testFlag(pmVectorized)) - QPainter::drawLine(line); + if( mIsAntialiasing || mModes.testFlag( pmVectorized ) ) + QPainter::drawLine( line ); else - QPainter::drawLine(line.toLine()); + QPainter::drawLine( line.toLine() ); } /*! @@ -141,18 +133,18 @@ void QCPPainter::drawLine(const QLineF &line) antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for AA/Non-AA painting). */ -void QCPPainter::setAntialiasing(bool enabled) +void QCPPainter::setAntialiasing( bool enabled ) { - setRenderHint(QPainter::Antialiasing, enabled); - if (mIsAntialiasing != enabled) + setRenderHint( QPainter::Antialiasing, enabled ); + if( mIsAntialiasing != enabled ) { mIsAntialiasing = enabled; - if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs + if( !mModes.testFlag( pmVectorized ) ) // antialiasing half-pixel shift only needed for rasterized outputs { - if (mIsAntialiasing) - translate(0.5, 0.5); + if( mIsAntialiasing ) + translate( 0.5, 0.5 ); else - translate(-0.5, -0.5); + translate( -0.5, -0.5 ); } } } @@ -161,7 +153,7 @@ void QCPPainter::setAntialiasing(bool enabled) 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) +void QCPPainter::setModes( QCPPainter::PainterModes modes ) { mModes = modes; } @@ -171,60 +163,61 @@ void QCPPainter::setModes(QCPPainter::PainterModes modes) 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 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); + 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) +void QCPPainter::setMode( QCPPainter::PainterMode mode, bool enabled ) { - if (!enabled && mModes.testFlag(mode)) + if( !enabled && mModes.testFlag( mode ) ) mModes &= ~mode; - else if (enabled && !mModes.testFlag(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); + 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()) + if( !mAntialiasingStack.isEmpty() ) mIsAntialiasing = mAntialiasingStack.pop(); else qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; @@ -237,32 +230,31 @@ void QCPPainter::restore() */ void QCPPainter::makeNonCosmetic() { - if (qFuzzyIsNull(pen().widthF())) + if( qFuzzyIsNull( pen().widthF() ) ) { QPen p = pen(); - p.setWidth(1); - QPainter::setPen(p); + 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: \code QCPScatterStyle myScatter; @@ -272,22 +264,22 @@ void QCPPainter::makeNonCosmetic() myScatter.setSize(5); customPlot->graph(0)->setScatterStyle(myScatter); \endcode - + 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: \code customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5)); \endcode - + \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: - + \code customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus); \endcode @@ -297,15 +289,15 @@ void QCPPainter::makeNonCosmetic() 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. @@ -314,21 +306,21 @@ void QCPPainter::makeNonCosmetic() /* 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 */ @@ -336,32 +328,24 @@ void QCPPainter::makeNonCosmetic() /*! 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) +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) +QCPScatterStyle::QCPScatterStyle( ScatterShape shape, double size ) + : mSize( size ), mShape( shape ), mPen( Qt::NoPen ), mBrush( Qt::NoBrush ), mPenDefined( false ) { } @@ -369,12 +353,8 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : 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) +QCPScatterStyle::QCPScatterStyle( ScatterShape shape, const QColor& color, double size ) + : mSize( size ), mShape( shape ), mPen( QPen( color ) ), mBrush( Qt::NoBrush ), mPenDefined( true ) { } @@ -382,19 +362,15 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double 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) +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 @@ -406,12 +382,8 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const 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) +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 ) { } @@ -419,67 +391,57 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBru 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) +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(false) +QCPScatterStyle::QCPScatterStyle( const QPainterPath& customPath, const QPen& pen, const QBrush& brush, double size ) + : mSize( size ), mShape( ssCustom ), mPen( pen ), mBrush( brush ), mCustomPath( customPath ), mPenDefined( false ) { } /*! Sets the size (pixel diameter) of the drawn scatter points to \a size. - + \see setShape */ -void QCPScatterStyle::setSize(double size) +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) +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) +void QCPScatterStyle::setPen( const QPen& pen ) { mPenDefined = true; mPen = pen; @@ -488,212 +450,212 @@ void QCPScatterStyle::setPen(const QPen &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) +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) +void QCPScatterStyle::setPixmap( const QPixmap& pixmap ) { - setShape(ssPixmap); + 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) +void QCPScatterStyle::setCustomPath( const QPainterPath& customPath ) { - setShape(ssCustom); + 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 +void QCPScatterStyle::applyTo( QCPPainter* painter, const QPen& defaultPen ) const { - painter->setPen(mPenDefined ? mPen : defaultPen); - painter->setBrush(mBrush); + 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 +void QCPScatterStyle::drawShape( QCPPainter* painter, QPointF pos ) const { - drawShape(painter, pos.x(), pos.y()); + 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 +void QCPScatterStyle::drawShape( QCPPainter* painter, double x, double y ) const { - double w = mSize/2.0; - switch (mShape) + double w = mSize / 2.0; + switch( mShape ) { - case ssNone: break; + case ssNone: + break; case ssDot: { - painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); + 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)); + 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)); + 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); + 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); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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); + 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); + 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); + 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); + 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); + 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 @@ -703,21 +665,21 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const 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. */ @@ -725,16 +687,16 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /* 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. */ @@ -742,18 +704,18 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /*! 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) +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. @@ -765,12 +727,13 @@ QCPLayer::~QCPLayer() // 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."; + + 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."; } /*! @@ -781,76 +744,76 @@ QCPLayer::~QCPLayer() QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the visibility of the parent layer into account. */ -void QCPLayer::setVisible(bool visible) +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) +void QCPLayer::addChild( QCPLayerable* layerable, bool prepend ) { - if (!mChildren.contains(layerable)) + if( !mChildren.contains( layerable ) ) { - if (prepend) - mChildren.prepend(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); + 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) +void QCPLayer::removeChild( QCPLayerable* layerable ) { - if (!mChildren.removeOne(layerable)) - qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(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. */ @@ -860,7 +823,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \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 @@ -868,7 +831,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) 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 @@ -876,7 +839,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) 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 @@ -889,10 +852,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \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. @@ -902,10 +865,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /* 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 */ @@ -913,44 +876,44 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! 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. */ -QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : - QObject(plot), - mVisible(true), - mParentPlot(plot), - mParentLayerable(parentLayerable), - mLayer(0), - mAntialiased(true) +QCPLayerable::QCPLayerable( QCustomPlot* plot, QString targetLayer, QCPLayerable* parentLayerable ) + : QObject( plot ), + mVisible( true ), + mParentPlot( plot ), + mParentLayerable( parentLayerable ), + mLayer( 0 ), + mAntialiased( true ) { - if (mParentPlot) + if( mParentPlot ) { - if (targetLayer.isEmpty()) - setLayer(mParentPlot->currentLayer()); - else if (!setLayer(targetLayer)) + 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) + if( mLayer ) { - mLayer->removeChild(this); + mLayer->removeChild( this ); mLayer = 0; } } @@ -960,7 +923,7 @@ QCPLayerable::~QCPLayerable() on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not possible. */ -void QCPLayerable::setVisible(bool on) +void QCPLayerable::setVisible( bool on ) { mVisible = on; } @@ -968,30 +931,31 @@ void QCPLayerable::setVisible(bool on) /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a layer. - + Returns true on success, i.e. if \a layer is a valid layer. */ -bool QCPLayerable::setLayer(QCPLayer *layer) +bool QCPLayerable::setLayer( QCPLayer* layer ) { - return moveToLayer(layer, false); + 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) +bool QCPLayerable::setLayer( const QString& layerName ) { - if (!mParentPlot) + if( !mParentPlot ) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } - if (QCPLayer *layer = mParentPlot->layer(layerName)) + if( QCPLayer* layer = mParentPlot->layer( layerName ) ) { - return setLayer(layer); - } else + return setLayer( layer ); + } + else { qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; return false; @@ -1000,11 +964,11 @@ bool QCPLayerable::setLayer(const QString &layerName) /*! 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) +void QCPLayerable::setAntialiased( bool enabled ) { mAntialiased = enabled; } @@ -1013,18 +977,19 @@ void QCPLayerable::setAntialiased(bool 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()); + return mVisible && ( !mLayer || mLayer->visible() ) && + ( !mParentLayerable || mParentLayerable.data()->realVisibility() ); } /*! @@ -1039,15 +1004,15 @@ bool QCPLayerable::realVisibility() const click inside the area returns a constant value greater zero (typically the selectionTolerance of the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function returns -1.0. - + 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 @@ -1056,96 +1021,96 @@ bool QCPLayerable::realVisibility() const 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 +double QCPLayerable::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(pos) - Q_UNUSED(onlySelectable) - Q_UNUSED(details) + 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) +void QCPLayerable::initializeParentPlot( QCustomPlot* parentPlot ) { - if (mParentPlot) + if( mParentPlot ) { qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; return; } - - if (!parentPlot) + + if( !parentPlot ) qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; - + mParentPlot = parentPlot; - parentPlotInitialized(mParentPlot); + 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) +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) +bool QCPLayerable::moveToLayer( QCPLayer* layer, bool prepend ) { - if (layer && !mParentPlot) + if( layer && !mParentPlot ) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } - if (layer && layer->parentPlot() != mParentPlot) + 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); + + QCPLayer* oldLayer = mLayer; + if( mLayer ) + mLayer->removeChild( this ); mLayer = layer; - if (mLayer) - mLayer->addChild(this, prepend); - if (mLayer != oldLayer) - emit layerChanged(mLayer); + if( mLayer ) + mLayer->addChild( this, prepend ); + if( mLayer != oldLayer ) + emit layerChanged( mLayer ); return true; } @@ -1156,14 +1121,16 @@ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) 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 +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); + if( mParentPlot && mParentPlot->notAntialiasedElements().testFlag( overrideElement ) ) + painter->setAntialiasing( false ); + else if( mParentPlot && mParentPlot->antialiasedElements().testFlag( overrideElement ) ) + painter->setAntialiasing( true ); else - painter->setAntialiasing(localAntialiased); + painter->setAntialiasing( localAntialiased ); } /*! \internal @@ -1171,20 +1138,20 @@ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialia 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) +void QCPLayerable::parentPlotInitialized( QCustomPlot* parentPlot ) { - Q_UNUSED(parentPlot) + Q_UNUSED( parentPlot ) } /*! \internal @@ -1192,10 +1159,10 @@ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) 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 @@ -1204,33 +1171,33 @@ QCP::Interaction QCPLayerable::selectionCategory() const } /*! \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) + 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 @@ -1238,51 +1205,53 @@ QRect QCPLayerable::clipRect() const 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) +void QCPLayerable::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { - Q_UNUSED(event) - Q_UNUSED(additive) - Q_UNUSED(details) - Q_UNUSED(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) +void QCPLayerable::deselectEvent( bool* selectionStateChanged ) { - Q_UNUSED(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 */ @@ -1307,18 +1276,14 @@ const double QCPRange::maxRange = 1e250; /*! Constructs a range with \a lower and \a upper set to zero. */ -QCPRange::QCPRange() : - lower(0), - upper(0) +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) +QCPRange::QCPRange( double lower, double upper ) : lower( lower ), upper( upper ) { normalize(); } @@ -1328,7 +1293,7 @@ QCPRange::QCPRange(double lower, double upper) : */ double QCPRange::size() const { - return upper-lower; + return upper - lower; } /*! @@ -1336,7 +1301,7 @@ double QCPRange::size() const */ double QCPRange::center() const { - return (upper+lower)*0.5; + return ( upper + lower ) * 0.5; } /*! @@ -1345,37 +1310,36 @@ double QCPRange::center() const */ void QCPRange::normalize() { - if (lower > upper) - qSwap(lower, upper); + 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) +void QCPRange::expand( const QCPRange& otherRange ) { - if (lower > otherRange.lower) + if( lower > otherRange.lower ) lower = otherRange.lower; - if (upper < otherRange.upper) + 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 QCPRange::expanded( const QCPRange& otherRange ) const { QCPRange result = *this; - result.expand(otherRange); + result.expand( otherRange ); return result; } @@ -1383,7 +1347,7 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const 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 @@ -1394,42 +1358,44 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const QCPRange QCPRange::sanitizedForLogScale() const { double rangeFac = 1e-3; - QCPRange sanitizedRange(lower, upper); + 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) + // 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) + 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) + 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) + if( -rangeFac > sanitizedRange.lower * rangeFac ) sanitizedRange.upper = -rangeFac; else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) + 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) + if( -sanitizedRange.lower > sanitizedRange.upper ) { // negative is wider, do same as in case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) + if( -rangeFac > sanitizedRange.lower * rangeFac ) sanitizedRange.upper = -rangeFac; else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + else { // positive is wider, do same as in case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) + if( rangeFac < sanitizedRange.upper * rangeFac ) sanitizedRange.lower = rangeFac; else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; + sanitizedRange.lower = sanitizedRange.upper * rangeFac; } } // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; } @@ -1463,7 +1429,7 @@ bool QCPRange::contains(double value) const \li range size above minRange \li range size below maxRange */ -bool QCPRange::validRange(double lower, double upper) +bool QCPRange::validRange( double lower, double upper ) { /* return (lower > -maxRange && @@ -1472,10 +1438,8 @@ bool QCPRange::validRange(double lower, double upper) (lower < -minRange || lower > minRange) && (upper < -minRange || upper > minRange)); */ - return (lower > -maxRange && - upper < maxRange && - qAbs(lower-upper) > minRange && - qAbs(lower-upper) < maxRange); + return ( lower > -maxRange && upper < maxRange && qAbs( lower - upper ) > minRange && + qAbs( lower - upper ) < maxRange ); } /*! @@ -1487,7 +1451,7 @@ bool QCPRange::validRange(double lower, double upper) \li range size above minRange \li range size below maxRange */ -bool QCPRange::validRange(const QCPRange &range) +bool QCPRange::validRange( const QCPRange& range ) { /* return (range.lower > -maxRange && @@ -1497,29 +1461,26 @@ bool QCPRange::validRange(const QCPRange &range) (range.lower < -minRange || range.lower > minRange) && (range.upper < -minRange || range.upper > minRange)); */ - return (range.lower > -maxRange && - range.upper < maxRange && - qAbs(range.lower-range.upper) > minRange && - qAbs(range.lower-range.upper) < maxRange); + return ( range.lower > -maxRange && range.upper < maxRange && qAbs( range.lower - range.upper ) > minRange && + qAbs( range.lower - range.upper ) < maxRange ); } - /*! \page thelayoutsystem The Layout System - + The layout system is responsible for positioning and scaling layout elements such as axis rects, legends and plot titles in a QCustomPlot. \section layoutsystem-classesandmechanisms Classes and mechanisms - + The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that take part in the layout system derive from this class, either directly or indirectly. - + Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own content. However, it is perfectly possible for a layout element to only serve as a structuring and/or positioning element, not drawing anything on its own. - + \subsection layoutsystem-rects Rects of a layout element - + A layout element is a rectangular object described by two rects: the inner rect (\ref QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward @@ -1527,9 +1488,9 @@ bool QCPRange::validRange(const QCPRange &range) left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels and tick labels are in the margin area. - + \subsection layoutsystem-margins Margins - + Each layout element may provide a mechanism to automatically determine its margins. Internally, this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref QCP::MarginSide and returns an integer value which represents the ideal margin for the specified @@ -1540,15 +1501,15 @@ bool QCPRange::validRange(const QCPRange &range) margins smaller than desired for a specific situation. If automatic margin calculation is unset for a specific side, the margin of that side can be controlled directy via \ref QCPLayoutElement::setMargins. - + If multiple layout ements are arranged next to or beneath each other, it may be desirable to align their inner rects on certain sides. Since they all might have different automatic margins, this usually isn't the case. The class \ref QCPMarginGroup and \ref QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the documentation there for details. - + \subsection layoutsystem-layout Layouts - + As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in princple can have the only purpose to manage/arrange those child elements. This is what the subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual @@ -1556,25 +1517,25 @@ bool QCPRange::validRange(const QCPRange &range) QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset which allows placing child elements freely inside its rect. - + Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way, complex hierarchies may be created, offering very flexible arrangements. - - \image html LayoutsystemSketch.png - + + \image html LayoutsystemSketch.png + Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. It shows how two child layout elements are placed inside the grid layout next to each other in cells (0, 0) and (0, 1). - + \subsection layoutsystem-plotlayout The top level plot layout - + Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout elements in the QCustomPlot. By default, this top level grid layout contains a single cell which holds the main axis rect. - + \subsection layoutsystem-examples Examples - + Adding a plot title is a typical and simple case to demonstrate basic workings of the layout system. \code // first we create and prepare a plot title layout element: @@ -1615,9 +1576,8 @@ bool QCPRange::validRange(const QCPRange &range) } \endcode \image html layoutsystem-multipleaxisrects.png - -*/ +*/ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPMarginGroup @@ -1625,27 +1585,27 @@ bool QCPRange::validRange(const QCPRange &range) /*! \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: \code QCPMarginGroup *group = new QCPMarginGroup(customPlot); @@ -1662,7 +1622,7 @@ bool QCPRange::validRange(const QCPRange &range) /* 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. */ @@ -1672,14 +1632,12 @@ bool QCPRange::validRange(const QCPRange &range) /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ -QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(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()); + mChildren.insert( QCP::msLeft, QList() ); + mChildren.insert( QCP::msRight, QList() ); + mChildren.insert( QCP::msTop, QList() ); + mChildren.insert( QCP::msBottom, QList() ); } QCPMarginGroup::~QCPMarginGroup() @@ -1693,11 +1651,11 @@ QCPMarginGroup::~QCPMarginGroup() */ bool QCPMarginGroup::isEmpty() const { - QHashIterator > it(mChildren); - while (it.hasNext()) + QHashIterator > it( mChildren ); + while( it.hasNext() ) { it.next(); - if (!it.value().isEmpty()) + if( !it.value().isEmpty() ) return false; } return true; @@ -1710,89 +1668,91 @@ bool QCPMarginGroup::isEmpty() const void QCPMarginGroup::clear() { // make all children remove themselves from this margin group: - QHashIterator > it(mChildren); - while (it.hasNext()) + 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 + 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 +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; i elements = mChildren.value( side ); + for( int i = 0; i < elements.size(); ++i ) { - if (!elements.at(i)->autoMargins().testFlag(side)) + if( !elements.at( i )->autoMargins().testFlag( side ) ) continue; - int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); - if (m > result) + 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) +void QCPMarginGroup::addChild( QCP::MarginSide side, QCPLayoutElement* element ) { - if (!mChildren[side].contains(element)) - mChildren[side].append(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); + 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) +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); + 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 @@ -1806,15 +1766,15 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /* 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 @@ -1824,30 +1784,30 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element */ /*! \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. */ @@ -1857,44 +1817,46 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /*! 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( 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 + 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); + 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) +void QCPLayoutElement::setOuterRect( const QRect& rect ) { - if (mOuterRect != rect) + if( mOuterRect != rect ) { mOuterRect = rect; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + mRect = mOuterRect.adjusted( mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom() ); } } @@ -1902,34 +1864,34 @@ void QCPLayoutElement::setOuterRect(const QRect &rect) 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) +void QCPLayoutElement::setMargins( const QMargins& margins ) { - if (mMargins != margins) + if( mMargins != margins ) { mMargins = margins; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + 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) +void QCPLayoutElement::setMinimumMargins( const QMargins& margins ) { - if (mMinimumMargins != margins) + if( mMinimumMargins != margins ) { mMinimumMargins = margins; } @@ -1939,13 +1901,13 @@ void QCPLayoutElement::setMinimumMargins(const QMargins &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) +void QCPLayoutElement::setAutoMargins( QCP::MarginSides sides ) { mAutoMargins = sides; } @@ -1953,89 +1915,94 @@ void QCPLayoutElement::setAutoMargins(QCP::MarginSides 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) +void QCPLayoutElement::setMinimumSize( const QSize& size ) { - if (mMinimumSize != size) + if( mMinimumSize != size ) { mMinimumSize = size; - if (mParentLayout) + 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) +void QCPLayoutElement::setMinimumSize( int width, int height ) { - setMinimumSize(QSize(width, 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) +void QCPLayoutElement::setMaximumSize( const QSize& size ) { - if (mMaximumSize != size) + if( mMaximumSize != size ) { mMaximumSize = size; - if (mParentLayout) + 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) +void QCPLayoutElement::setMaximumSize( int width, int height ) { - setMaximumSize(QSize(width, 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) +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 + QCPMarginGroup* oldGroup = marginGroup( side ); + if( oldGroup ) // unregister at old group + oldGroup->removeChild( 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.remove( side ); + } + else // setting to a new group { mMarginGroups[side] = group; - group->addChild(side, this); + group->addChild( side, this ); } } } @@ -2046,42 +2013,49 @@ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *gr 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) +void QCPLayoutElement::update( UpdatePhase phase ) { - if (phase == upMargins) + if( phase == upMargins ) { - if (mAutoMargins != QCP::msNone) + if( mAutoMargins != QCP::msNone ) { - // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + // set the margins of this layout element according to automatic margin calculation, either directly or via a + // margin group: QMargins newMargins = mMargins; - foreach (QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom) + foreach( QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop + << QCP::msBottom ) { - if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically + 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 + 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 + 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)); + if( QCP::getMarginValue( newMargins, side ) < QCP::getMarginValue( mMinimumMargins, side ) ) + QCP::setMarginValue( newMargins, side, QCP::getMarginValue( mMinimumMargins, side ) ); } } - setMargins(newMargins); + 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.) @@ -2093,7 +2067,7 @@ QSize QCPLayoutElement::minimumSizeHint() const /*! 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.) @@ -2106,13 +2080,13 @@ QSize QCPLayoutElement::maximumSizeHint() const /*! 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 +QList QCPLayoutElement::elements( bool recursive ) const { - Q_UNUSED(recursive) + Q_UNUSED( recursive ) return QList(); } @@ -2121,58 +2095,59 @@ QList QCPLayoutElement::elements(bool recursive) const 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 +double QCPLayoutElement::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - - if (onlySelectable) + Q_UNUSED( details ) + + if( onlySelectable ) return -1; - - if (QRectF(mOuterRect).contains(pos)) + + if( QRectF( mOuterRect ).contains( pos ) ) { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; + if( mParentPlot ) + return mParentPlot->selectionTolerance() * 0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } - } else + } + 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) +void QCPLayoutElement::parentPlotInitialized( QCustomPlot* parentPlot ) { - foreach (QCPLayoutElement* el, elements(false)) + foreach( QCPLayoutElement* el, elements( false ) ) { - if (!el->parentPlot()) - el->initializeParentPlot(parentPlot); + 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) +int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) { - return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); + return qMax( QCP::getMarginValue( mMargins, side ), QCP::getMarginValue( mMinimumMargins, side ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -2181,23 +2156,23 @@ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) /*! \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". */ @@ -2205,44 +2180,44 @@ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) /* 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 */ @@ -2259,44 +2234,44 @@ 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) +void QCPLayout::update( UpdatePhase phase ) { - QCPLayoutElement::update(phase); - + QCPLayoutElement::update( phase ); + // set child element rects according to layout: - if (phase == upLayout) + if( phase == upLayout ) updateLayout(); - + // propagate update call to child elements: const int elCount = elementCount(); - for (int i=0; iupdate(phase); + if( QCPLayoutElement* el = elementAt( i ) ) + el->update( phase ); } } /* inherits documentation from base class */ -QList QCPLayout::elements(bool recursive) const +QList QCPLayout::elements( bool recursive ) const { const int c = elementCount(); QList result; -#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(c); +#if QT_VERSION >= QT_VERSION_CHECK( 4, 7, 0 ) + result.reserve( c ); #endif - for (int i=0; ielements(recursive); + if( result.at( i ) ) + result << result.at( i )->elements( recursive ); } } return result; @@ -2305,7 +2280,7 @@ QList QCPLayout::elements(bool recursive) const /*! 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. */ @@ -2316,59 +2291,61 @@ 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. - + \see remove, takeAt */ -bool QCPLayout::removeAt(int index) +bool QCPLayout::removeAt( int index ) { - if (QCPLayoutElement *el = takeAt(index)) + if( QCPLayoutElement* el = takeAt( index ) ) { delete el; return true; - } else + } + 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. - + \see removeAt, take */ -bool QCPLayout::remove(QCPLayoutElement *element) +bool QCPLayout::remove( QCPLayoutElement* element ) { - if (take(element)) + if( take( element ) ) { delete element; return true; - } else + } + else return false; } /*! Removes and deletes all layout elements in this layout. - + \see remove, removeAt */ void QCPLayout::clear() { - for (int i=elementCount()-1; i>=0; --i) + for( int i = elementCount() - 1; i >= 0; --i ) { - if (elementAt(i)) - removeAt(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, @@ -2376,245 +2353,261 @@ void QCPLayout::clear() */ void QCPLayout::sizeConstraintsChanged() const { - if (QWidget *w = qobject_cast(parent())) + if( QWidget* w = qobject_cast( parent() ) ) w->updateGeometry(); - else if (QCPLayout *l = qobject_cast(parent())) + 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) +void QCPLayout::adoptElement( QCPLayoutElement* el ) { - if (el) + if( el ) { el->mParentLayout = this; - el->setParentLayerable(this); - el->setParent(this); - if (!el->parentPlot()) - el->initializeParentPlot(mParentPlot); - } else + 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) +void QCPLayout::releaseElement( QCPLayoutElement* el ) { - if (el) + if( el ) { el->mParentLayout = 0; - el->setParentLayerable(0); - el->setParent(mParentPlot); + el->setParentLayerable( 0 ); + el->setParent( mParentPlot ); // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot - } else + } + 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 +QVector QCPLayout::getSectionSizes( QVector maxSizes, + QVector minSizes, + QVector stretchFactors, + int totalSize ) const { - if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) + 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()) + if( stretchFactors.isEmpty() ) return QVector(); int sectionCount = stretchFactors.size(); - QVector sectionSizes(sectionCount); + 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 result( sectionCount ); + for( int i = 0; i < sectionCount; ++i ) + result[i] = qRound( sectionSizes.at( i ) ); return result; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutGrid \brief A layout that arranges child elements in a grid - + Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor, \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing). - + Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref hasElement, that element can be retrieved with \ref element. If rows and columns that only have empty cells shall be removed, call \ref simplify. Removal of elements is either done by just adding the element to a different layout or by using the QCPLayout interface \ref take or \ref remove. - + Row and column insertion can be performed with \ref insertRow and \ref insertColumn. */ /*! Creates an instance of QCPLayoutGrid and sets default values. */ -QCPLayoutGrid::QCPLayoutGrid() : - mColumnSpacing(5), - mRowSpacing(5) +QCPLayoutGrid::QCPLayoutGrid() : mColumnSpacing( 5 ), mRowSpacing( 5 ) { } @@ -2627,32 +2620,34 @@ QCPLayoutGrid::~QCPLayoutGrid() /*! Returns the element in the cell in \a row and \a column. - + Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. - + \see addElement, hasElement */ -QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const +QCPLayoutElement* QCPLayoutGrid::element( int row, int column ) const { - if (row >= 0 && row < mElements.size()) + if( row >= 0 && row < mElements.size() ) { - if (column >= 0 && column < mElements.first().size()) + if( column >= 0 && column < mElements.first().size() ) { - if (QCPLayoutElement *result = mElements.at(row).at(column)) + if( QCPLayoutElement* result = mElements.at( row ).at( column ) ) return result; else qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; - } else + } + else qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; - } else + } + 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 @@ -2662,12 +2657,12 @@ int QCPLayoutGrid::rowCount() const /*! Returns the number of columns in the layout. - + \see rowCount */ int QCPLayoutGrid::columnCount() const { - if (mElements.size() > 0) + if( mElements.size() > 0 ) return mElements.first().size(); else return 0; @@ -2677,27 +2672,29 @@ int QCPLayoutGrid::columnCount() const 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) +bool QCPLayoutGrid::addElement( int row, int column, QCPLayoutElement* element ) { - if (element) + if( element ) { - if (!hasElement(row, column)) + if( !hasElement( row, column ) ) { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - expandTo(row+1, column+1); + if( element->layout() ) // remove from old layout first + element->layout()->take( element ); + expandTo( row + 1, column + 1 ); mElements[row][column] = element; - adoptElement(element); + adoptElement( element ); return true; - } else + } + else qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; - } else + } + else qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; return false; } @@ -2705,135 +2702,139 @@ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) /*! 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) +bool QCPLayoutGrid::hasElement( int row, int column ) { - if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) - return mElements.at(row).at(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) +void QCPLayoutGrid::setColumnStretchFactor( int column, double factor ) { - if (column >= 0 && column < columnCount()) + if( column >= 0 && column < columnCount() ) { - if (factor > 0) + if( factor > 0 ) mColumnStretchFactors[column] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else + } + 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) +void QCPLayoutGrid::setColumnStretchFactors( const QList& factors ) { - if (factors.size() == mColumnStretchFactors.size()) + if( factors.size() == mColumnStretchFactors.size() ) { mColumnStretchFactors = factors; - for (int i=0; i= 0 && row < rowCount()) + if( row >= 0 && row < rowCount() ) { - if (factor > 0) + if( factor > 0 ) mRowStretchFactors[row] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else + } + 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) +void QCPLayoutGrid::setRowStretchFactors( const QList& factors ) { - if (factors.size() == mRowStretchFactors.size()) + if( factors.size() == mRowStretchFactors.size() ) { mRowStretchFactors = factors; - for (int i=0; i()); - mRowStretchFactors.append(1); + mElements.append( QList() ); + mRowStretchFactors.append( 1 ); } // go through rows and expand columns as necessary: - int newColCount = qMax(columnCount(), newColumnCount); - for (int i=0; i rowCount()) + if( newIndex > rowCount() ) newIndex = rowCount(); - - mRowStretchFactors.insert(newIndex, 1); + + mRowStretchFactors.insert( newIndex, 1 ); QList newRow; - for (int col=0; col columnCount()) + if( newIndex > 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); - + 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; + if( 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))); + if( 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 ) ) ); } } } @@ -2953,27 +2957,28 @@ void QCPLayoutGrid::updateLayout() /* inherits documentation from base class */ int QCPLayoutGrid::elementCount() const { - return rowCount()*columnCount(); + return rowCount() * columnCount(); } /* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const +QCPLayoutElement* QCPLayoutGrid::elementAt( int index ) const { - if (index >= 0 && index < elementCount()) - return mElements.at(index / columnCount()).at(index % columnCount()); + 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) +QCPLayoutElement* QCPLayoutGrid::takeAt( int index ) { - if (QCPLayoutElement *el = elementAt(index)) + if( QCPLayoutElement* el = elementAt( index ) ) { - releaseElement(el); + releaseElement( el ); mElements[index / columnCount()][index % columnCount()] = 0; return el; - } else + } + else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; @@ -2981,47 +2986,48 @@ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) } /* inherits documentation from base class */ -bool QCPLayoutGrid::take(QCPLayoutElement *element) +bool QCPLayoutGrid::take( QCPLayoutElement* element ) { - if (element) + if( element ) { - for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +QList 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); +#if QT_VERSION >= QT_VERSION_CHECK( 4, 7, 0 ) + result.reserve( colC * rowC ); #endif - for (int row=0; rowelements(recursive); + if( result.at( i ) ) + result << result.at( i )->elements( recursive ); } } return result; @@ -3033,43 +3039,44 @@ QList QCPLayoutGrid::elements(bool recursive) const void QCPLayoutGrid::simplify() { // remove rows with only empty cells: - for (int row=rowCount()-1; row>=0; --row) + for( int row = rowCount() - 1; row >= 0; --row ) { bool hasElements = false; - for (int col=0; col=0; --col) + for( int col = columnCount() - 1; 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 +void QCPLayoutGrid::getMinimumRowColSizes( QVector* minColWidths, QVector* minRowHeights ) const { - *minColWidths = QVector(columnCount(), 0); - *minRowHeights = QVector(rowCount(), 0); - for (int row=0; row( columnCount(), 0 ); + *minRowHeights = QVector( rowCount(), 0 ); + for( int row = 0; row < rowCount(); ++row ) { - for (int col=0; colminimumSizeHint(); - 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(); + QSize minHint = mElements.at( row ).at( col )->minimumSizeHint(); + 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 +void QCPLayoutGrid::getMaximumRowColSizes( QVector* maxColWidths, QVector* maxRowHeights ) const { - *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); - *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); - for (int row=0; row( columnCount(), QWIDGETSIZE_MAX ); + *maxRowHeights = QVector( rowCount(), QWIDGETSIZE_MAX ); + for( int row = 0; row < rowCount(); ++row ) { - for (int col=0; colmaximumSizeHint(); - 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(); + QSize maxHint = mElements.at( row ).at( col )->maximumSizeHint(); + 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). @@ -3189,16 +3197,16 @@ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVectorminimumSizeHint(); - 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) + QSize minSizeHint = mElements.at( i )->minimumSizeHint(); + 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 + 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() ); } - mElements.at(i)->setOuterRect(insetRect); + 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 ); } } @@ -3360,26 +3382,27 @@ int QCPLayoutInset::elementCount() const } /* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutInset::elementAt(int index) const +QCPLayoutElement* QCPLayoutInset::elementAt( int index ) const { - if (index >= 0 && index < mElements.size()) - return mElements.at(index); + if( index >= 0 && index < mElements.size() ) + return mElements.at( index ); else return 0; } /* inherits documentation from base class */ -QCPLayoutElement *QCPLayoutInset::takeAt(int index) +QCPLayoutElement* QCPLayoutInset::takeAt( int index ) { - if (QCPLayoutElement *el = elementAt(index)) + if( QCPLayoutElement* el = elementAt( index ) ) { - releaseElement(el); - mElements.removeAt(index); - mInsetPlacement.removeAt(index); - mInsetAlignment.removeAt(index); - mInsetRect.removeAt(index); + releaseElement( el ); + mElements.removeAt( index ); + mInsetPlacement.removeAt( index ); + mInsetAlignment.removeAt( index ); + mInsetRect.removeAt( index ); return el; - } else + } + else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; @@ -3387,20 +3410,21 @@ QCPLayoutElement *QCPLayoutInset::takeAt(int index) } /* inherits documentation from base class */ -bool QCPLayoutInset::take(QCPLayoutElement *element) +bool QCPLayoutInset::take( QCPLayoutElement* element ) { - if (element) + if( element ) { - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) - return mParentPlot->selectionTolerance()*0.99; + if( mElements.at( i )->realVisibility() && mElements.at( i )->selectTest( pos, onlySelectable ) >= 0 ) + return mParentPlot->selectionTolerance() * 0.99; } return -1; } @@ -3434,25 +3458,26 @@ double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVari 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) +void QCPLayoutInset::addElement( QCPLayoutElement* element, Qt::Alignment alignment ) { - if (element) + 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 + 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"; } @@ -3460,48 +3485,48 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignme 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) +void QCPLayoutInset::addElement( QCPLayoutElement* element, const QRectF& rect ) { - if (element) + 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 + 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. \code myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode @@ -3510,29 +3535,22 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) /*! Creates a QCPLineEnding instance with default values (style \ref esNone). */ -QCPLineEnding::QCPLineEnding() : - mStyle(esNone), - mWidth(8), - mLength(10), - mInverted(false) +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) +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) +void QCPLineEnding::setStyle( QCPLineEnding::EndingStyle style ) { mStyle = style; } @@ -3540,10 +3558,10 @@ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle 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) +void QCPLineEnding::setWidth( double width ) { mWidth = width; } @@ -3551,10 +3569,10 @@ void QCPLineEnding::setWidth(double 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) +void QCPLineEnding::setLength( double length ) { mLength = length; } @@ -3567,40 +3585,39 @@ void QCPLineEnding::setLength(double length) 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) +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) + 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 - + 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 mWidth * 1.42; // items that only have a width -> width*sqrt(2) } return 0; } @@ -3608,17 +3625,17 @@ double QCPLineEnding::boundingDistance() const /*! 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) + switch( mStyle ) { case esNone: case esLineArrow: @@ -3626,143 +3643,138 @@ double QCPLineEnding::realLength() const case esBar: case esHalfBar: return 0; - + case esFlatArrow: return mLength; - + case esDisc: case esSquare: case esDiamond: - return mWidth*0.5; - + return mWidth * 0.5; + case esSpikeArrow: - return mLength*0.8; + 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 +void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, const QVector2D& dir ) const { - if (mStyle == esNone) + 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)); - + + 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) + miterPen.setJoinStyle( Qt::MiterJoin ); // to make arrow heads spikey + QBrush brush( painter->pen().color(), Qt::SolidPattern ); + switch( mStyle ) { - case esNone: break; + 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); + 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); + 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); + 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); + 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); + 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); + 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()); + painter->drawLine( ( pos + widthVec ).toPointF(), ( pos - widthVec ).toPointF() ); break; } case esHalfBar: { - painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); + painter->drawLine( ( pos + widthVec ).toPointF(), pos.toPointF() ); break; } case esSkewedBar: { - if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) + 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 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()); + // 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; } @@ -3771,26 +3783,25 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto /*! \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 +void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, double angle ) const { - draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); + 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 @@ -3799,30 +3810,29 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle /*! 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(), "", parentAxis), - mParentAxis(parentAxis) +QCPGrid::QCPGrid( QCPAxis* parentAxis ) + : QCPLayerable( parentAxis->parentPlot(), "", 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); + 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) +void QCPGrid::setSubGridVisible( bool visible ) { mSubGridVisible = visible; } @@ -3830,7 +3840,7 @@ void QCPGrid::setSubGridVisible(bool visible) /*! Sets whether sub grid lines are drawn antialiased. */ -void QCPGrid::setAntialiasedSubGrid(bool enabled) +void QCPGrid::setAntialiasedSubGrid( bool enabled ) { mAntialiasedSubGrid = enabled; } @@ -3838,7 +3848,7 @@ void QCPGrid::setAntialiasedSubGrid(bool enabled) /*! Sets whether zero lines are drawn antialiased. */ -void QCPGrid::setAntialiasedZeroLine(bool enabled) +void QCPGrid::setAntialiasedZeroLine( bool enabled ) { mAntialiasedZeroLine = enabled; } @@ -3846,7 +3856,7 @@ void QCPGrid::setAntialiasedZeroLine(bool enabled) /*! Sets the pen with which (major) grid lines are drawn. */ -void QCPGrid::setPen(const QPen &pen) +void QCPGrid::setPen( const QPen& pen ) { mPen = pen; } @@ -3854,18 +3864,18 @@ void QCPGrid::setPen(const QPen &pen) /*! Sets the pen with which sub grid lines are drawn. */ -void QCPGrid::setSubGridPen(const QPen &pen) +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) +void QCPGrid::setZeroLinePen( const QPen& pen ) { mZeroLinePen = pen; } @@ -3876,137 +3886,152 @@ void QCPGrid::setZeroLinePen(const QPen &pen) 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 +void QCPGrid::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); + 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) +void QCPGrid::draw( QCPPainter* painter ) { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - if (mSubGridVisible) - drawSubGridLines(painter); - drawGridLines(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 +void QCPGrid::drawGridLines( QCPPainter* painter ) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - + 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) + 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) + 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) + 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) + 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())); + 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) + 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())); + 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 + } + else { // draw zeroline: int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) + 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) + 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) + 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)); + 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) + 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)); + 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 +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) + if( !mParentAxis ) { - for (int i=0; imSubTickVector.size(); ++i) + 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; i < mParentAxis->mSubTickVector.size(); ++i ) { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + t = mParentAxis->coordToPixel( mParentAxis->mSubTickVector.at( i ) ); // x + painter->drawLine( QLineF( t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top() ) ); } - } else + } + else { - for (int i=0; imSubTickVector.size(); ++i) + for( int i = 0; i < mParentAxis->mSubTickVector.size(); ++i ) { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + t = mParentAxis->coordToPixel( mParentAxis->mSubTickVector.at( i ) ); // y + painter->drawLine( QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); } } } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxis //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -4017,12 +4042,12 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const 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.
@@ -4032,23 +4057,23 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /* 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() */ @@ -4056,14 +4081,14 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /* 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 @@ -4079,24 +4104,24 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! \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 */ @@ -4106,82 +4131,86 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const Constructs an Axis instance of Type \a type for the axis rect \a parent. You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis. */ -QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : - QCPLayerable(parent->parentPlot(), "", 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("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) +QCPAxis::QCPAxis( QCPAxisRect* parent, AxisType type ) + : QCPLayerable( parent->parentPlot(), "", 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( "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 ) { - 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) + 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( 3 ); + setLabelPadding( 6 ); + } + else if( type == atRight ) { - setTickLabelPadding(7); - setLabelPadding(12); - } else if (type == atBottom) + setTickLabelPadding( 7 ); + setLabelPadding( 12 ); + } + else if( type == atBottom ) { - setTickLabelPadding(3); - setLabelPadding(3); - } else if (type == atLeft) + setTickLabelPadding( 3 ); + setLabelPadding( 3 ); + } + else if( type == atLeft ) { - setTickLabelPadding(5); - setLabelPadding(10); + setTickLabelPadding( 5 ); + setLabelPadding( 10 ); } } @@ -4206,12 +4235,12 @@ double QCPAxis::tickLabelRotation() const QString QCPAxis::numberFormat() const { QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) + result.append( mNumberFormatChar ); + if( mNumberBeautifulPowers ) { - result.append("b"); - if (mAxisPainter->numberMultiplyCross) - result.append("c"); + result.append( "b" ); + if( mAxisPainter->numberMultiplyCross ) + result.append( "c" ); } return result; } @@ -4270,208 +4299,215 @@ QCPLineEnding QCPAxis::upperEnding() const 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) +void QCPAxis::setScaleType( QCPAxis::ScaleType type ) { - if (mScaleType != type) + if( mScaleType != type ) { mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); + if( mScaleType == stLogarithmic ) + setRange( mRange.sanitizedForLogScale() ); mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); + 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) +void QCPAxis::setScaleLogBase( double base ) { - if (base > 1) + if( base > 1 ) { mScaleLogBase = base; - mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation + mScaleLogBaseLogInv = 1.0 / qLn( mScaleLogBase ); // buffer for faster baseLog() calculation mCachedMarginValid = false; - } else + } + 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) +void QCPAxis::setRange( const QCPRange& range ) { - if (range.lower == mRange.lower && range.upper == mRange.upper) + if( range.lower == mRange.lower && range.upper == mRange.upper ) + return; + + if( !QCPRange::validRange( range ) ) return; - - if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) + if( mScaleType == stLogarithmic ) { mRange = range.sanitizedForLogScale(); - } else + } + else { mRange = range.sanitizedForLinScale(); } mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + 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) +void QCPAxis::setSelectableParts( const SelectableParts& selectable ) { - if (mSelectableParts != selectable) + if( mSelectableParts != selectable ) { mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); + 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) +void QCPAxis::setSelectedParts( const SelectableParts& selected ) { - if (mSelectedParts != selected) + if( mSelectedParts != selected ) { mSelectedParts = selected; - emit selectionChanged(mSelectedParts); + 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) +void QCPAxis::setRange( double lower, double upper ) { - if (lower == mRange.lower && upper == mRange.upper) + if( lower == mRange.lower && upper == mRange.upper ) + return; + + if( !QCPRange::validRange( lower, upper ) ) return; - - if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; - if (mScaleType == stLogarithmic) + if( mScaleType == stLogarithmic ) { mRange = mRange.sanitizedForLogScale(); - } else + } + else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + 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) +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); + 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) +void QCPAxis::setRangeLower( double lower ) { - if (mRange.lower == lower) + if( mRange.lower == lower ) return; - + QCPRange oldRange = mRange; mRange.lower = lower; - if (mScaleType == stLogarithmic) + if( mScaleType == stLogarithmic ) { mRange = mRange.sanitizedForLogScale(); - } else + } + else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + 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) +void QCPAxis::setRangeUpper( double upper ) { - if (mRange.upper == upper) + if( mRange.upper == upper ) return; - + QCPRange oldRange = mRange; mRange.upper = upper; - if (mScaleType == stLogarithmic) + if( mScaleType == stLogarithmic ) { mRange = mRange.sanitizedForLogScale(); - } else + } + else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + emit rangeChanged( mRange ); + emit rangeChanged( mRange, oldRange ); } /*! @@ -4483,9 +4519,9 @@ void QCPAxis::setRangeUpper(double upper) of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ -void QCPAxis::setRangeReversed(bool reversed) +void QCPAxis::setRangeReversed( bool reversed ) { - if (mRangeReversed != reversed) + if( mRangeReversed != reversed ) { mRangeReversed = reversed; mCachedMarginValid = false; @@ -4495,21 +4531,21 @@ void QCPAxis::setRangeReversed(bool reversed) /*! 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) +void QCPAxis::setAutoTicks( bool on ) { - if (mAutoTicks != on) + if( mAutoTicks != on ) { mAutoTicks = on; mCachedMarginValid = false; @@ -4519,23 +4555,24 @@ void QCPAxis::setAutoTicks(bool on) /*! 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) +void QCPAxis::setAutoTickCount( int approximateCount ) { - if (mAutoTickCount != approximateCount) + if( mAutoTickCount != approximateCount ) { - if (approximateCount > 0) + if( approximateCount > 0 ) { mAutoTickCount = approximateCount; mCachedMarginValid = false; - } else + } + else qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; } } @@ -4544,20 +4581,20 @@ void QCPAxis::setAutoTickCount(int 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) +void QCPAxis::setAutoTickLabels( bool on ) { - if (mAutoTickLabels != on) + if( mAutoTickLabels != on ) { mAutoTickLabels = on; mCachedMarginValid = false; @@ -4571,14 +4608,14 @@ void QCPAxis::setAutoTickLabels(bool on) 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) +void QCPAxis::setAutoTickStep( bool on ) { - if (mAutoTickStep != on) + if( mAutoTickStep != on ) { mAutoTickStep = on; mCachedMarginValid = false; @@ -4589,14 +4626,14 @@ void QCPAxis::setAutoTickStep(bool on) 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) +void QCPAxis::setAutoSubTicks( bool on ) { - if (mAutoSubTicks != on) + if( mAutoSubTicks != on ) { mAutoSubTicks = on; mCachedMarginValid = false; @@ -4609,9 +4646,9 @@ void QCPAxis::setAutoSubTicks(bool on) 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) +void QCPAxis::setTicks( bool show ) { - if (mTicks != show) + if( mTicks != show ) { mTicks = show; mCachedMarginValid = false; @@ -4621,9 +4658,9 @@ void QCPAxis::setTicks(bool show) /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ -void QCPAxis::setTickLabels(bool show) +void QCPAxis::setTickLabels( bool show ) { - if (mTickLabels != show) + if( mTickLabels != show ) { mTickLabels = show; mCachedMarginValid = false; @@ -4634,9 +4671,9 @@ void QCPAxis::setTickLabels(bool show) Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ -void QCPAxis::setTickLabelPadding(int padding) +void QCPAxis::setTickLabelPadding( int padding ) { - if (mAxisPainter->tickLabelPadding != padding) + if( mAxisPainter->tickLabelPadding != padding ) { mAxisPainter->tickLabelPadding = padding; mCachedMarginValid = false; @@ -4645,28 +4682,28 @@ void QCPAxis::setTickLabelPadding(int padding) /*! 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) +void QCPAxis::setTickLabelType( LabelType type ) { - if (mTickLabelType != type) + if( mTickLabelType != type ) { mTickLabelType = type; mCachedMarginValid = false; @@ -4675,12 +4712,12 @@ void QCPAxis::setTickLabelType(LabelType type) /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ -void QCPAxis::setTickLabelFont(const QFont &font) +void QCPAxis::setTickLabelFont( const QFont& font ) { - if (font != mTickLabelFont) + if( font != mTickLabelFont ) { mTickLabelFont = font; mCachedMarginValid = false; @@ -4689,12 +4726,12 @@ void QCPAxis::setTickLabelFont(const QFont &font) /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ -void QCPAxis::setTickLabelColor(const QColor &color) +void QCPAxis::setTickLabelColor( const QColor& color ) { - if (color != mTickLabelColor) + if( color != mTickLabelColor ) { mTickLabelColor = color; mCachedMarginValid = false; @@ -4705,16 +4742,16 @@ void QCPAxis::setTickLabelColor(const QColor &color) 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) +void QCPAxis::setTickLabelRotation( double degrees ) { - if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) + if( !qFuzzyIsNull( degrees - mAxisPainter->tickLabelRotation ) ) { - mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mAxisPainter->tickLabelRotation = qBound( -90.0, degrees, 90.0 ); mCachedMarginValid = false; } } @@ -4722,14 +4759,14 @@ void QCPAxis::setTickLabelRotation(double degrees) /*! 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) +void QCPAxis::setDateTimeFormat( const QString& format ) { - if (mDateTimeFormat != format) + if( mDateTimeFormat != format ) { mDateTimeFormat = format; mCachedMarginValid = false; @@ -4743,10 +4780,10 @@ void QCPAxis::setDateTimeFormat(const QString &format) 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) +void QCPAxis::setDateTimeSpec( const Qt::TimeSpec& timeSpec ) { mDateTimeSpec = timeSpec; } @@ -4759,7 +4796,7 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) 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 @@ -4768,13 +4805,13 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) 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 @@ -4787,55 +4824,60 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) \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) +void QCPAxis::setNumberFormat( const QString& formatCode ) { - if (formatCode.isEmpty()) + if( formatCode.isEmpty() ) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } mCachedMarginValid = false; - + // interpret first char as number format char: QString allowedFormatChars = "eEfgG"; - if (allowedFormatChars.contains(formatCode.at(0))) + if( allowedFormatChars.contains( formatCode.at( 0 ) ) ) { - mNumberFormatChar = formatCode.at(0).toLatin1(); - } else + mNumberFormatChar = formatCode.at( 0 ).toLatin1(); + } + else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } - if (formatCode.length() < 2) + if( formatCode.length() < 2 ) { mNumberBeautifulPowers = false; mAxisPainter->numberMultiplyCross = false; return; } - + // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g')) + if( formatCode.at( 1 ) == 'b' && ( mNumberFormatChar == 'e' || mNumberFormatChar == 'g' ) ) { mNumberBeautifulPowers = true; - } else + } + else { - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + 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) + if( formatCode.length() < 3 ) { mAxisPainter->numberMultiplyCross = false; return; } - + // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == 'c') + if( formatCode.at( 2 ) == 'c' ) { mAxisPainter->numberMultiplyCross = true; - } else if (formatCode.at(2) == 'd') + } + else if( formatCode.at( 2 ) == 'd' ) { mAxisPainter->numberMultiplyCross = false; - } else + } + else { qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; return; @@ -4853,9 +4895,9 @@ void QCPAxis::setNumberFormat(const QString &formatCode) 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) +void QCPAxis::setNumberPrecision( int precision ) { - if (mNumberPrecision != precision) + if( mNumberPrecision != precision ) { mNumberPrecision = precision; mCachedMarginValid = false; @@ -4867,9 +4909,9 @@ void QCPAxis::setNumberPrecision(int precision) The tick step is the interval between (major) ticks, in plot coordinates. \see setSubTickCount */ -void QCPAxis::setTickStep(double step) +void QCPAxis::setTickStep( double step ) { - if (mTickStep != step) + if( mTickStep != step ) { mTickStep = step; mCachedMarginValid = false; @@ -4882,14 +4924,14 @@ void QCPAxis::setTickStep(double step) 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) +void QCPAxis::setTickVector( const QVector& vec ) { // don't check whether mTickVector != vec here, because it takes longer than we would save mTickVector = vec; @@ -4901,13 +4943,13 @@ void QCPAxis::setTickVector(const QVector &vec) 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) +void QCPAxis::setTickVectorLabels( const QVector& vec ) { // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save mTickVectorLabels = vec; @@ -4919,24 +4961,24 @@ void QCPAxis::setTickVectorLabels(const QVector &vec) 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) +void QCPAxis::setTickLength( int inside, int outside ) { - setTickLengthIn(inside); - setTickLengthOut(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) +void QCPAxis::setTickLengthIn( int inside ) { - if (mAxisPainter->tickLengthIn != inside) + if( mAxisPainter->tickLengthIn != inside ) { mAxisPainter->tickLengthIn = inside; } @@ -4946,22 +4988,22 @@ void QCPAxis::setTickLengthIn(int 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) +void QCPAxis::setTickLengthOut( int outside ) { - if (mAxisPainter->tickLengthOut != outside) + if( mAxisPainter->tickLengthOut != outside ) { mAxisPainter->tickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin + 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. @@ -4969,7 +5011,7 @@ void QCPAxis::setTickLengthOut(int outside) 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) +void QCPAxis::setSubTickCount( int count ) { mSubTickCount = count; } @@ -4979,24 +5021,24 @@ void QCPAxis::setSubTickCount(int count) 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) +void QCPAxis::setSubTickLength( int inside, int outside ) { - setSubTickLengthIn(inside); - setSubTickLengthOut(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) +void QCPAxis::setSubTickLengthIn( int inside ) { - if (mAxisPainter->subTickLengthIn != inside) + if( mAxisPainter->subTickLengthIn != inside ) { mAxisPainter->subTickLengthIn = inside; } @@ -5006,56 +5048,56 @@ void QCPAxis::setSubTickLengthIn(int 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) +void QCPAxis::setSubTickLengthOut( int outside ) { - if (mAxisPainter->subTickLengthOut != outside) + if( mAxisPainter->subTickLengthOut != outside ) { mAxisPainter->subTickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin + 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) +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) +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) +void QCPAxis::setSubTickPen( const QPen& pen ) { mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ -void QCPAxis::setLabelFont(const QFont &font) +void QCPAxis::setLabelFont( const QFont& font ) { - if (mLabelFont != font) + if( mLabelFont != font ) { mLabelFont = font; mCachedMarginValid = false; @@ -5064,10 +5106,10 @@ void QCPAxis::setLabelFont(const QFont &font) /*! Sets the color of the axis label. - + \see setLabelFont */ -void QCPAxis::setLabelColor(const QColor &color) +void QCPAxis::setLabelColor( const QColor& color ) { mLabelColor = color; } @@ -5076,9 +5118,9 @@ void QCPAxis::setLabelColor(const QColor &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) +void QCPAxis::setLabel( const QString& str ) { - if (mLabel != str) + if( mLabel != str ) { mLabel = str; mCachedMarginValid = false; @@ -5087,12 +5129,12 @@ void QCPAxis::setLabel(const QString &str) /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ -void QCPAxis::setLabelPadding(int padding) +void QCPAxis::setLabelPadding( int padding ) { - if (mAxisPainter->labelPadding != padding) + if( mAxisPainter->labelPadding != padding ) { mAxisPainter->labelPadding = padding; mCachedMarginValid = false; @@ -5104,14 +5146,14 @@ void QCPAxis::setLabelPadding(int padding) 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) +void QCPAxis::setPadding( int padding ) { - if (mPadding != padding) + if( mPadding != padding ) { mPadding = padding; mCachedMarginValid = false; @@ -5120,25 +5162,25 @@ void QCPAxis::setPadding(int padding) /*! 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) +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) +void QCPAxis::setSelectedTickLabelFont( const QFont& font ) { - if (font != mSelectedTickLabelFont) + if( font != mSelectedTickLabelFont ) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts @@ -5147,10 +5189,10 @@ void QCPAxis::setSelectedTickLabelFont(const QFont &font) /*! 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) +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 @@ -5158,12 +5200,12 @@ void QCPAxis::setSelectedLabelFont(const QFont &font) /*! 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) +void QCPAxis::setSelectedTickLabelColor( const QColor& color ) { - if (color != mSelectedTickLabelColor) + if( color != mSelectedTickLabelColor ) { mSelectedTickLabelColor = color; } @@ -5171,40 +5213,40 @@ void QCPAxis::setSelectedTickLabelColor(const QColor &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) +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) +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) +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) +void QCPAxis::setSelectedSubTickPen( const QPen& pen ) { mSelectedSubTickPen = pen; } @@ -5212,14 +5254,14 @@ void QCPAxis::setSelectedSubTickPen(const QPen &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) +void QCPAxis::setLowerEnding( const QCPLineEnding& ending ) { mAxisPainter->lowerEnding = ending; } @@ -5227,14 +5269,14 @@ void QCPAxis::setLowerEnding(const QCPLineEnding &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) +void QCPAxis::setUpperEnding( const QCPLineEnding& ending ) { mAxisPainter->upperEnding = ending; } @@ -5242,25 +5284,26 @@ void QCPAxis::setUpperEnding(const QCPLineEnding &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) +void QCPAxis::moveRange( double diff ) { QCPRange oldRange = mRange; - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { mRange.lower += diff; mRange.upper += diff; - } else // mScaleType == stLogarithmic + } + else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + emit rangeChanged( mRange ); + emit rangeChanged( mRange, oldRange ); } /*! @@ -5269,31 +5312,35 @@ void QCPAxis::moveRange(double diff) 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) +void QCPAxis::scaleRange( double factor, double center ) { QCPRange oldRange = mRange; - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(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 + } + else // mScaleType == stLogarithmic { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range + if( ( mRange.upper < 0 && center < 0 ) || + ( mRange.upper > 0 && center > 0 ) ) // make sure center has same sign as range { QCPRange newRange; - newRange.lower = pow(mRange.lower/center, factor)*center; - newRange.upper = pow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) + newRange.lower = pow( mRange.lower / center, factor ) * center; + newRange.upper = pow( 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; + } + 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); + emit rangeChanged( mRange ); + emit rangeChanged( mRange, oldRange ); } /*! @@ -5309,110 +5356,121 @@ void QCPAxis::scaleRange(double factor, double center) 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) +void QCPAxis::setScaleRatio( const QCPAxis* otherAxis, double ratio ) { int otherPixelSize, ownPixelSize; - - if (otherAxis->orientation() == Qt::Horizontal) + + if( otherAxis->orientation() == Qt::Horizontal ) otherPixelSize = otherAxis->axisRect()->width(); else otherPixelSize = otherAxis->axisRect()->height(); - - if (orientation() == Qt::Horizontal) + + 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); + + 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) +void QCPAxis::rescale( bool onlyVisiblePlottables ) { QList p = plottables(); QCPRange newRange; bool haveRange = false; - for (int i=0; irealVisibility() && onlyVisiblePlottables) + if( !p.at( i )->realVisibility() && 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); + 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) + plottableRange = p.at( i )->getValueRange( currentFoundRange, signDomain ); + if( currentFoundRange ) { - if (!haveRange) + if( !haveRange ) newRange = plottableRange; else - newRange.expand(plottableRange); + newRange.expand( plottableRange ); haveRange = true; } } - if (haveRange) + 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 + 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) + 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 - 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); + newRange.lower = center / qSqrt( mRange.upper / mRange.lower ); + newRange.upper = center * qSqrt( mRange.upper / mRange.lower ); } } - setRange(newRange); + setRange( newRange ); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ -double QCPAxis::pixelToCoord(double value) const +double QCPAxis::pixelToCoord( double value ) const { - if (orientation() == Qt::Horizontal) + if( orientation() == Qt::Horizontal ) { - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { - if (!mRangeReversed) - return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; + 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 pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; - else - return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; + return -( value - mAxisRect->left() ) / (double)mAxisRect->width() * mRange.size() + mRange.upper; } - } else // orientation() == Qt::Vertical + else // mScaleType == stLogarithmic + { + if( !mRangeReversed ) + return pow( mRange.upper / mRange.lower, ( value - mAxisRect->left() ) / (double)mAxisRect->width() ) * + mRange.lower; + else + return pow( mRange.upper / mRange.lower, ( mAxisRect->left() - value ) / (double)mAxisRect->width() ) * + mRange.upper; + } + } + else // orientation() == Qt::Vertical { - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { - if (!mRangeReversed) - return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; + 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 + return -( mAxisRect->bottom() - value ) / (double)mAxisRect->height() * mRange.size() + mRange.upper; + } + else // mScaleType == stLogarithmic { - if (!mRangeReversed) - return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; + if( !mRangeReversed ) + return pow( mRange.upper / mRange.lower, ( mAxisRect->bottom() - value ) / (double)mAxisRect->height() ) * + mRange.lower; else - return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; + return pow( mRange.upper / mRange.lower, ( value - mAxisRect->bottom() ) / (double)mAxisRect->height() ) * + mRange.upper; } } } @@ -5420,50 +5478,59 @@ double QCPAxis::pixelToCoord(double value) const /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ -double QCPAxis::coordToPixel(double value) const +double QCPAxis::coordToPixel( double value ) const { - if (orientation() == Qt::Horizontal) + if( orientation() == Qt::Horizontal ) { - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { - if (!mRangeReversed) - return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); + 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 + 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; + 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(); + 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(); + return baseLog( mRange.upper / value ) / baseLog( mRange.upper / mRange.lower ) * mAxisRect->width() + + mAxisRect->left(); } } - } else // orientation() == Qt::Vertical + } + else // orientation() == Qt::Vertical { - if (mScaleType == stLinear) + if( mScaleType == stLinear ) { - if (!mRangeReversed) - return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); + 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 + 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; + 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(); + 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(); + return mAxisRect->bottom() - + baseLog( mRange.upper / value ) / baseLog( mRange.upper / mRange.lower ) * mAxisRect->height(); } } } @@ -5473,73 +5540,76 @@ double QCPAxis::coordToPixel(double value) const 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 +QCPAxis::SelectablePart QCPAxis::getPartAt( const QPointF& pos ) const { - if (!mVisible) + if( !mVisible ) return spNone; - - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) + + if( mAxisPainter->axisSelectionBox().contains( pos.toPoint() ) ) return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) + else if( mAxisPainter->tickLabelsSelectionBox().contains( pos.toPoint() ) ) return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) + 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 +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) + if( !mParentPlot ) return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; + 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 ) + return result; + + for( int i = 0; i < mParentPlot->mPlottables.size(); ++i ) { - if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) - result.append(mParentPlot->mPlottables.at(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 ) + return result; + + for( int i = 0; i < mParentPlot->mGraphs.size(); ++i ) { - if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) - result.append(mParentPlot->mGraphs.at(i)); + if( mParentPlot->mGraphs.at( i )->keyAxis() == this || mParentPlot->mGraphs.at( i )->valueAxis() == this ) + result.append( mParentPlot->mGraphs.at( i ) ); } return result; } @@ -5547,22 +5617,23 @@ QList QCPAxis::graphs() const /*! 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) + if( !mParentPlot ) + return result; + + for( int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId ) { - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posId positions = mParentPlot->mItems.at( itemId )->positions(); + for( int posId = 0; posId < positions.size(); ++posId ) { - if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this) + if( positions.at( posId )->keyAxis() == this || positions.at( posId )->valueAxis() == this ) { - result.append(mParentPlot->mItems.at(itemId)); + result.append( mParentPlot->mItems.at( itemId ) ); break; } } @@ -5574,15 +5645,20 @@ QList QCPAxis::items() const 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) +QCPAxis::AxisType QCPAxis::marginSideToAxisType( QCP::MarginSide side ) { - switch (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; + 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; @@ -5591,20 +5667,31 @@ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) /*! Returns the axis type that describes the opposite axis of an axis with the specified \a type. */ -QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) +QCPAxis::AxisType QCPAxis::opposite( QCPAxis::AxisType type ) { - switch (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; + 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 @@ -5612,44 +5699,47 @@ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) */ void QCPAxis::setupTickVectors() { - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - + 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) + if( mAutoTicks ) { generateAutoTicks(); - } else + } + else { emit ticksRequest(); } - - visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); - if (mTickVector.isEmpty()) + + visibleTickBounds( mLowestVisibleTick, mHighestVisibleTick ); + if( mTickVector.isEmpty() ) { mSubTickVector.clear(); return; } - + // generate subticks between ticks: - mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); - if (mSubTickCount > 0) + 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) + 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) + 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) + subTickPosition = mTickVector.at( i - 1 ) + k * subTickStep; + if( subTickPosition < mRange.lower ) continue; - if (subTickPosition > mRange.upper) + if( subTickPosition > mRange.upper ) { done = true; break; @@ -5657,108 +5747,125 @@ void QCPAxis::setupTickVectors() mSubTickVector[subTickIndex] = subTickPosition; subTickIndex++; } - if (done) break; + if( done ) + break; } - mSubTickVector.resize(subTickIndex); + mSubTickVector.resize( subTickIndex ); } // generate tick labels according to tick positions: - if (mAutoTickLabels) + if( mAutoTickLabels ) { int vecsize = mTickVector.size(); - mTickVectorLabels.resize(vecsize); - if (mTickLabelType == ltNumber) + mTickVectorLabels.resize( vecsize ); + if( mTickLabelType == ltNumber ) { - for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) - mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision); - } else if (mTickLabelType == ltDateTime) + for( int i = mLowestVisibleTick; i <= mHighestVisibleTick; ++i ) + mTickVectorLabels[i] = + mParentPlot->locale().toString( mTickVector.at( i ), mNumberFormatChar, mNumberPrecision ); + } + else if( mTickLabelType == ltDateTime ) { - for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) + 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); +#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); + mTickVectorLabels[i] = mParentPlot->locale().toString( + QDateTime::fromMSecsSinceEpoch( mTickVector.at( i ) * 1000 ).toTimeSpec( mDateTimeSpec ), mDateTimeFormat ); #endif } } - } else // mAutoTickLabels == false + } + else // mAutoTickLabels == false { - if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels + 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()); + 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( mScaleType == stLinear ) { - if (mAutoTickStep) + 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) + 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 + mTickStep = (int)( tickStepMantissa * 2 ) / 2.0 * magnitudeFactor; + } + else { // round to first digit in multiples of 2 - mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; + mTickStep = (int)( tickStepMantissa / 2.0 ) * 2.0 * magnitudeFactor; } } - if (mAutoSubTicks) - mSubTickCount = calculateAutoSubTickCount(mTickStep); + if( mAutoSubTicks ) + mSubTickCount = calculateAutoSubTickCount( mTickStep ); // Generate tick positions according to mTickStep: - qint64 firstStep = floor(mRange.lower/mTickStep); - qint64 lastStep = ceil(mRange.upper/mTickStep); - int tickcount = lastStep-firstStep+1; - if (tickcount < 0) tickcount = 0; - mTickVector.resize(tickcount); - for (int i=0; i 0 && mRange.upper > 0) // positive range + if( mRange.lower > 0 && mRange.upper > 0 ) // positive range { - double lowerMag = basePow((int)floor(baseLog(mRange.lower))); + double lowerMag = basePow( (int)floor( 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 + 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); + mTickVector.append( currentMag ); } - } else if (mRange.lower < 0 && mRange.upper < 0) // negative range + } + else if( mRange.lower < 0 && mRange.upper < 0 ) // negative range { - double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower))); + double lowerMag = -basePow( (int)ceil( 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 + 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); + mTickVector.append( currentMag ); } - } else // invalid range for logarithmic scale, because lower and upper have different sign + } + 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; @@ -5767,94 +5874,132 @@ void QCPAxis::generateAutoTicks() } /*! \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 QCPAxis::calculateAutoSubTickCount( double tickStep ) const { - int result = mSubTickCount; // default to current setting, if no proper value can be found - + 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; - + 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); + double fracPart = modf( tickStepMantissa, &intPartf ); intPart = intPartf; - + // handle cases with (almost) integer mantissa: - if (fracPart < epsilon || 1.0-fracPart < epsilon) + if( fracPart < epsilon || 1.0 - fracPart < epsilon ) { - if (1.0-fracPart < epsilon) + if( 1.0 - fracPart < epsilon ) ++intPart; - switch (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 + 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 + } + else { // handle cases with significantly fractional mantissa: - if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa + if( qAbs( fracPart - 0.5 ) < epsilon ) // *.5 mantissa { - switch (intPart) + 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 + 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) +void QCPAxis::selectEvent( QMouseEvent* event, bool additive, const QVariant& details, bool* selectionStateChanged ) { - Q_UNUSED(event) + Q_UNUSED( event ) SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) + if( mSelectableParts.testFlag( part ) ) { SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) + setSelectedParts( additive ? mSelectedParts ^ part : part ); + if( selectionStateChanged ) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ -void QCPAxis::deselectEvent(bool *selectionStateChanged) +void QCPAxis::deselectEvent( bool* selectionStateChanged ) { SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) + setSelectedParts( mSelectedParts & ~mSelectableParts ); + if( selectionStateChanged ) *selectionStateChanged = mSelectedParts != selBefore; } @@ -5864,48 +6009,49 @@ void QCPAxis::deselectEvent(bool *selectionStateChanged) 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 +void QCPAxis::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint( painter, mAntialiased, QCP::aeAxes ); } /*! \internal - + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. */ -void QCPAxis::draw(QCPPainter *painter) +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) + 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) + for( int i = lowTick; i <= highTick; ++i ) { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(i)); + tickPositions.append( coordToPixel( mTickVector.at( i ) ) ); + if( mTickLabels ) + tickLabels.append( mTickVectorLabels.at( i ) ); } - - if (mSubTickCount > 0) + + if( mSubTickCount > 0 ) { const int subTickCount = mSubTickVector.size(); - for (int i=0; itickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; mAxisPainter->subTickPositions = subTickPositions; - mAxisPainter->draw(painter); + 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 +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) + + for( int i = 0; i < mTickVector.size(); ++i ) { - if (mTickVector.at(i) >= mRange.lower) + if( mTickVector.at( i ) >= mRange.lower ) { lowFound = true; lowIndex = i; break; } } - for (int i=mTickVector.size()-1; i >= 0; --i) + for( int i = mTickVector.size() - 1; i >= 0; --i ) { - if (mTickVector.at(i) <= mRange.upper) + if( mTickVector.at( i ) <= mRange.upper ) { highFound = true; highIndex = i; break; } } - - if (!lowFound && highFound) - lowIndex = highIndex+1; - else if (lowFound && !highFound) - highIndex = lowIndex-1; + + 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 +double QCPAxis::baseLog( double value ) const { - return qLn(value)*mScaleLogBaseLogInv; + 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 +double QCPAxis::basePow( double value ) const { - return qPow(mScaleLogBase, value); + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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 + 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) + + 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) + 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) + for( int i = lowTick; i <= highTick; ++i ) { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(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. @@ -6137,7 +6283,6 @@ QCP::Interaction QCPAxis::selectionCategory() const return QCP::iSelectAxes; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -6146,9 +6291,9 @@ QCP::Interaction QCPAxis::selectionCategory() const \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. @@ -6158,27 +6303,27 @@ QCP::Interaction QCPAxis::selectionCategory() const 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), - 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( 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 ), + 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 { } @@ -6187,106 +6332,135 @@ 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) +void QCPAxisPainterPrivate::draw( QCPPainter* painter ) { QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) + if( newHash != mLabelParameterHash ) { mLabelCache.clear(); mLabelParameterHash = newHash; } - + QPoint origin; - switch (type) + switch( type ) { - case QCPAxis::atLeft: origin = alignmentRect.bottomLeft() +QPoint(-offset, 0); break; - case QCPAxis::atRight: origin = alignmentRect.bottomRight()+QPoint(+offset, 0); break; - case QCPAxis::atTop: origin = alignmentRect.topLeft() +QPoint(0, -offset); break; - case QCPAxis::atBottom: origin = alignmentRect.bottomLeft() +QPoint(0, +offset); break; + case QCPAxis::atLeft: + origin = alignmentRect.bottomLeft() + QPoint( -offset, 0 ); + break; + case QCPAxis::atRight: + origin = alignmentRect.bottomRight() + QPoint( +offset, 0 ); + break; + case QCPAxis::atTop: + origin = alignmentRect.topLeft() + QPoint( 0, -offset ); + break; + case QCPAxis::atBottom: + origin = alignmentRect.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) + 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; + 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(alignmentRect.width()+xCor, yCor)); + painter->setPen( basePen ); + if( QCPAxis::orientation( type ) == Qt::Horizontal ) + baseLine.setPoints( origin + QPointF( xCor, yCor ), origin + QPointF( alignmentRect.width() + xCor, yCor ) ); else - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -alignmentRect.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); - + baseLine.setPoints( origin + QPointF( xCor, yCor ), origin + QPointF( xCor, -alignmentRect.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()) + 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) + 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; i < tickPositions.size(); ++i ) + painter->drawLine( 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)); + for( int i = 0; i < tickPositions.size(); ++i ) + painter->drawLine( QLineF( origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at( i ) + yCor, + origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at( i ) + yCor ) ); } } - + // draw subticks: - if (!subTickPositions.isEmpty()) + if( !subTickPositions.isEmpty() ) { - painter->setPen(subTickPen); + 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) + 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; i < subTickPositions.size(); ++i ) + painter->drawLine( 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)); + for( int i = 0; i < subTickPositions.size(); ++i ) + painter->drawLine( 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)); - + 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); - + 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: - QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label - if (!tickLabels.isEmpty()) + QSize tickLabelsSize( 0, 0 ); // size of largest tick label, for offset calculation of axis label + if( !tickLabels.isEmpty() ) { margin += tickLabelPadding; - painter->setFont(tickLabelFont); - painter->setPen(QPen(tickLabelColor)); - const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); - for (int i=0; isetFont( tickLabelFont ); + painter->setPen( QPen( tickLabelColor ) ); + const int maxLabelIndex = qMin( tickPositions.size(), tickLabels.size() ); + for( int i = 0; i < maxLabelIndex; ++i ) + placeTickLabel( painter, tickPositions.at( i ), margin, tickLabels.at( i ), &tickLabelsSize ); + if( QCPAxis::orientation( type ) == Qt::Horizontal ) margin += tickLabelsSize.height(); else margin += tickLabelsSize.width(); @@ -6294,109 +6468,129 @@ void QCPAxisPainterPrivate::draw(QCPPainter *painter) // axis label: QRect labelBounds; - if (!label.isEmpty()) + 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) + 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, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + painter->translate( ( origin.x() - margin - labelBounds.height() ), origin.y() ); + painter->rotate( -90 ); + painter->drawText( 0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, + label ); + painter->setTransform( oldTransform ); } - else if (type == QCPAxis::atRight) + else if( type == QCPAxis::atRight ) { QTransform oldTransform = painter->transform(); - painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-alignmentRect.height()); - painter->rotate(90); - painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + painter->translate( ( origin.x() + margin + labelBounds.height() ), origin.y() - alignmentRect.height() ); + painter->rotate( 90 ); + painter->drawText( 0, 0, alignmentRect.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(), alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - else if (type == QCPAxis::atBottom) - painter->drawText(origin.x(), origin.y()+margin, alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + else if( type == QCPAxis::atTop ) + painter->drawText( origin.x(), origin.y() - margin - labelBounds.height(), alignmentRect.width(), + labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label ); + else if( type == QCPAxis::atBottom ) + painter->drawText( origin.x(), origin.y() + margin, alignmentRect.width(), labelBounds.height(), + Qt::TextDontClip | Qt::AlignCenter, label ); } - + // set selection boxes: int selectionTolerance = 0; - if (mParentPlot) + if( mParentPlot ) selectionTolerance = mParentPlot->selectionTolerance(); else qDebug() << Q_FUNC_INFO << "mParentPlot is null"; - int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisOutSize = qMax( qMax( tickLengthOut, subTickLengthOut ), selectionTolerance ); int selAxisInSize = selectionTolerance; - int selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - int selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; + int selTickLabelSize = + ( QCPAxis::orientation( type ) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width() ); + int selTickLabelOffset = qMax( tickLengthOut, subTickLengthOut ) + tickLabelPadding; int selLabelSize = labelBounds.height(); - int selLabelOffset = selTickLabelOffset+selTickLabelSize+labelPadding; - if (type == QCPAxis::atLeft) + int selLabelOffset = selTickLabelOffset + selTickLabelSize + labelPadding; + if( type == QCPAxis::atLeft ) { - mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, alignmentRect.top(), origin.x()+selAxisInSize, alignmentRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, alignmentRect.top(), origin.x()-selTickLabelOffset, alignmentRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, alignmentRect.top(), origin.x()-selLabelOffset, alignmentRect.bottom()); - } else if (type == QCPAxis::atRight) + mAxisSelectionBox.setCoords( origin.x() - selAxisOutSize, alignmentRect.top(), origin.x() + selAxisInSize, + alignmentRect.bottom() ); + mTickLabelsSelectionBox.setCoords( origin.x() - selTickLabelOffset - selTickLabelSize, alignmentRect.top(), + origin.x() - selTickLabelOffset, alignmentRect.bottom() ); + mLabelSelectionBox.setCoords( origin.x() - selLabelOffset - selLabelSize, alignmentRect.top(), + origin.x() - selLabelOffset, alignmentRect.bottom() ); + } + else if( type == QCPAxis::atRight ) { - mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, alignmentRect.top(), origin.x()+selAxisOutSize, alignmentRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, alignmentRect.top(), origin.x()+selTickLabelOffset, alignmentRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, alignmentRect.top(), origin.x()+selLabelOffset, alignmentRect.bottom()); - } else if (type == QCPAxis::atTop) + mAxisSelectionBox.setCoords( origin.x() - selAxisInSize, alignmentRect.top(), origin.x() + selAxisOutSize, + alignmentRect.bottom() ); + mTickLabelsSelectionBox.setCoords( origin.x() + selTickLabelOffset + selTickLabelSize, alignmentRect.top(), + origin.x() + selTickLabelOffset, alignmentRect.bottom() ); + mLabelSelectionBox.setCoords( origin.x() + selLabelOffset + selLabelSize, alignmentRect.top(), + origin.x() + selLabelOffset, alignmentRect.bottom() ); + } + else if( type == QCPAxis::atTop ) { - mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisOutSize, alignmentRect.right(), origin.y()+selAxisInSize); - mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, alignmentRect.right(), origin.y()-selTickLabelOffset); - mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()-selLabelOffset-selLabelSize, alignmentRect.right(), origin.y()-selLabelOffset); - } else if (type == QCPAxis::atBottom) + mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisOutSize, alignmentRect.right(), + origin.y() + selAxisInSize ); + mTickLabelsSelectionBox.setCoords( alignmentRect.left(), origin.y() - selTickLabelOffset - selTickLabelSize, + alignmentRect.right(), origin.y() - selTickLabelOffset ); + mLabelSelectionBox.setCoords( alignmentRect.left(), origin.y() - selLabelOffset - selLabelSize, + alignmentRect.right(), origin.y() - selLabelOffset ); + } + else if( type == QCPAxis::atBottom ) { - mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisInSize, alignmentRect.right(), origin.y()+selAxisOutSize); - mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, alignmentRect.right(), origin.y()+selTickLabelOffset); - mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()+selLabelOffset+selLabelSize, alignmentRect.right(), origin.y()+selLabelOffset); + mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisInSize, alignmentRect.right(), + origin.y() + selAxisOutSize ); + mTickLabelsSelectionBox.setCoords( alignmentRect.left(), origin.y() + selTickLabelOffset + selTickLabelSize, + alignmentRect.right(), origin.y() + selTickLabelOffset ); + mLabelSelectionBox.setCoords( alignmentRect.left(), origin.y() + selLabelOffset + selLabelSize, + alignmentRect.right(), origin.y() + selLabelOffset ); } // draw hitboxes for debug purposes: - //painter->setBrush(Qt::NoBrush); - //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); + // 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)); - + if( !tickPositions.isEmpty() ) + result += qMax( 0, qMax( tickLengthOut, subTickLengthOut ) ); + // calculate size of tick labels: - QSize tickLabelsSize(0, 0); - if (!tickLabels.isEmpty()) + QSize tickLabelsSize( 0, 0 ); + if( !tickLabels.isEmpty() ) { - for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled + if( mParentPlot->plottingHints().testFlag( QCP::phCacheLabels ) && + !painter->modes().testFlag( QCPPainter::pmNoCaching ) ) // label caching enabled { - if (!mLabelCache.contains(text)) // no cached label exists, create it + if( !mLabelCache.contains( text ) ) // no cached label exists, create it { - CachedLabel *newCachedLabel = new CachedLabel; - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF drawOffset = getTickLabelDrawOffset(labelData); - newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft(); - newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - newCachedLabel->pixmap.fill(Qt::transparent); - QCPPainter cachePainter(&newCachedLabel->pixmap); - cachePainter.setPen(painter->pen()); - drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); - mLabelCache.insert(text, newCachedLabel, 1); + CachedLabel* newCachedLabel = new CachedLabel; + TickLabelData labelData = getTickLabelData( painter->font(), text ); + QPointF drawOffset = getTickLabelDrawOffset( labelData ); + newCachedLabel->offset = drawOffset + labelData.rotatedTotalBounds.topLeft(); + newCachedLabel->pixmap = QPixmap( labelData.rotatedTotalBounds.size() ); + newCachedLabel->pixmap.fill( Qt::transparent ); + QCPPainter cachePainter( &newCachedLabel->pixmap ); + cachePainter.setPen( painter->pen() ); + drawTickLabel( &cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), + -labelData.rotatedTotalBounds.topLeft().y(), labelData ); + mLabelCache.insert( text, newCachedLabel, 1 ); } // draw cached label: - const CachedLabel *cachedLabel = mLabelCache.object(text); + const CachedLabel* cachedLabel = mLabelCache.object( text ); // if label would be partly clipped by widget border on sides, don't draw it: - if (QCPAxis::orientation(type) == Qt::Horizontal) + if( QCPAxis::orientation( type ) == Qt::Horizontal ) { - if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || - labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left()) - return; - } else - { - if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() || - labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top()) + if( labelAnchor.x() + cachedLabel->offset.x() + cachedLabel->pixmap.width() > viewportRect.right() || + labelAnchor.x() + cachedLabel->offset.x() < viewportRect.left() ) return; } - painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); + else + { + if( labelAnchor.y() + cachedLabel->offset.y() + cachedLabel->pixmap.height() > viewportRect.bottom() || + labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top() ) + return; + } + painter->drawPixmap( labelAnchor + cachedLabel->offset, cachedLabel->pixmap ); finalSize = cachedLabel->pixmap.size(); - } else // label caching disabled, draw text directly on surface: + } + else // label caching disabled, draw text directly on surface: { - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + 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: - if (QCPAxis::orientation(type) == Qt::Horizontal) + if( QCPAxis::orientation( type ) == Qt::Horizontal ) { - if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || - finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left()) - return; - } else - { - if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || - finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top()) + if( finalPosition.x() + ( labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left() ) > + viewportRect.right() || + finalPosition.x() + labelData.rotatedTotalBounds.left() < viewportRect.left() ) return; } - drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + else + { + if( finalPosition.y() + ( labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top() ) > + viewportRect.bottom() || + finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top() ) + return; + } + 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()); + 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 +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); - + painter->translate( x, y ); + if( !qFuzzyIsNull( tickLabelRotation ) ) + painter->rotate( tickLabelRotation ); + // draw text: - if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used + 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); + 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); + 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 +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; - if (substituteExponent) + if( substituteExponent ) { - ePos = text.indexOf('e'); - if (ePos > -1) + ePos = text.indexOf( 'e' ); + if( ePos > -1 ) useBeautifulPowers = true; } - + // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so we check here before possibly setting a negative value in the 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) + if( result.baseFont.pointSizeF() > 0 ) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so + // we check here before possibly setting a negative value in the 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); + 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 == "1") + if( abbreviateDecimalPowers && result.basePart == "1" ) result.basePart = "10"; else - result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10"; - result.expPart = text.mid(ePos+1); + result.basePart += ( numberMultiplyCross ? QString( QChar( 215 ) ) : QString( QChar( 183 ) ) ) + "10"; + result.expPart = text.mid( ePos + 1 ); // clip "+" and leading zeros off expPart: - while (result.expPart.length() > 2 && result.expPart.at(1) == '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) == '+') - result.expPart.remove(0, 1); + while( result.expPart.length() > 2 && + result.expPart.at( 1 ) == '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 ) == '+' ) + result.expPart.remove( 0, 1 ); // prepare smaller font for exponent: result.expFont = font; - result.expFont.setPointSize(result.expFont.pointSize()*0.75); + result.expFont.setPointSize( result.expFont.pointSize() * 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.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 = 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 - + 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)) + if( !qFuzzyIsNull( tickLabelRotation ) ) { QTransform transform; - transform.rotate(tickLabelRotation); - result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + 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 +QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labelData ) const { /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short @@ -6641,115 +6871,132 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &label 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) + 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 ) { - if (doRotation) + if( doRotation ) { - if (tickLabelRotation > 0) + 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; + 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 + 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; + y = -labelData.totalBounds.height() / 2.0; } - } else if (type == QCPAxis::atRight) + } + else if( type == QCPAxis::atRight ) { - if (doRotation) + if( doRotation ) { - if (tickLabelRotation > 0) + 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 = +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; + y = flip ? +labelData.totalBounds.width() / 2.0 : -qCos( -radians ) * labelData.totalBounds.height() / 2.0; } - } else + } + else { x = 0; - y = -labelData.totalBounds.height()/2.0; + y = -labelData.totalBounds.height() / 2.0; } - } else if (type == QCPAxis::atTop) + } + else if( type == QCPAxis::atTop ) { - if (doRotation) + if( doRotation ) { - if (tickLabelRotation > 0) + 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(); + 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 + else + { + x = -qSin( -radians ) * labelData.totalBounds.height() / 2.0; + y = -qCos( -radians ) * labelData.totalBounds.height(); + } + } + else { - x = -labelData.totalBounds.width()/2.0; + x = -labelData.totalBounds.width() / 2.0; y = -labelData.totalBounds.height(); } - } else if (type == QCPAxis::atBottom) + } + else if( type == QCPAxis::atBottom ) { - if (doRotation) + if( doRotation ) { - if (tickLabelRotation > 0) + if( tickLabelRotation > 0 ) { - x = +qSin(radians)*labelData.totalBounds.height()/2.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 + 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; + x = -labelData.totalBounds.width() / 2.0; y = 0; } } - - return QPointF(x, y); + + 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 +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 + if( mParentPlot->plottingHints().testFlag( QCP::phCacheLabels ) && + mLabelCache.contains( text ) ) // label caching enabled and have cached label { - const CachedLabel *cachedLabel = mLabelCache.object(text); + const CachedLabel* cachedLabel = mLabelCache.object( text ); finalSize = cachedLabel->pixmap.size(); - } else // label caching disabled or no label with this text cached: + } + else // label caching disabled or no label with this text cached: { - TickLabelData labelData = getTickLabelData(font, text); + 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()); -} + // 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 @@ -6761,16 +7008,16 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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 is displayed by \ref QCPGraph (typically created with \ref QCustomPlot::addGraph). \li A parametric curve can be displayed with \ref QCPCurve. \li A stackable bar chart can be achieved with \ref QCPBars. \li A box of a statistical box plot is created with \ref QCPStatisticalBox. - + \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 @@ -6779,9 +7026,9 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString \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 @@ -6789,31 +7036,38 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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: - + - + - + - + - + - + @@ -6829,14 +7083,14 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! \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. */ /*! \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 @@ -6847,13 +7101,13 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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 @@ -6864,7 +7118,7 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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 */ @@ -6872,15 +7126,15 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /* 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 */ @@ -6891,30 +7145,30 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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(), "", 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) +QCPAbstractPlottable::QCPAbstractPlottable( QCPAxis* keyAxis, QCPAxis* valueAxis ) + : QCPLayerable( keyAxis->parentPlot(), "", 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()) + 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()) + if( keyAxis->orientation() == valueAxis->orientation() ) qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; } @@ -6922,55 +7176,54 @@ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) 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) +void QCPAbstractPlottable::setName( const QString& name ) { mName = name; } /*! Sets whether fills of this plottable is drawn antialiased or not. - + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ -void QCPAbstractPlottable::setAntialiasedFill(bool enabled) +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) +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) +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 and scatter points with this pen. \see setBrush */ -void QCPAbstractPlottable::setPen(const QPen &pen) +void QCPAbstractPlottable::setPen( const QPen& pen ) { mPen = pen; } @@ -6981,7 +7234,7 @@ void QCPAbstractPlottable::setPen(const QPen &pen) \see setSelected, setSelectable, setSelectedBrush, selectTest */ -void QCPAbstractPlottable::setSelectedPen(const QPen &pen) +void QCPAbstractPlottable::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } @@ -6989,13 +7242,13 @@ void QCPAbstractPlottable::setSelectedPen(const QPen &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) +void QCPAbstractPlottable::setBrush( const QBrush& brush ) { mBrush = brush; } @@ -7006,7 +7259,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) \see setSelected, setSelectable, setSelectedPen, selectTest */ -void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) +void QCPAbstractPlottable::setSelectedBrush( const QBrush& brush ) { mSelectedBrush = brush; } @@ -7016,13 +7269,13 @@ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) 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) +void QCPAbstractPlottable::setKeyAxis( QCPAxis* axis ) { mKeyAxis = axis; } @@ -7035,10 +7288,10 @@ void QCPAbstractPlottable::setKeyAxis(QCPAxis *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) +void QCPAbstractPlottable::setValueAxis( QCPAxis* axis ) { mValueAxis = axis; } @@ -7046,18 +7299,18 @@ void QCPAbstractPlottable::setValueAxis(QCPAxis *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) +void QCPAbstractPlottable::setSelectable( bool selectable ) { - if (mSelectable != selectable) + if( mSelectable != selectable ) { mSelectable = selectable; - emit selectableChanged(mSelectable); + emit selectableChanged( mSelectable ); } } @@ -7068,19 +7321,19 @@ void QCPAbstractPlottable::setSelectable(bool selectable) 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) +void QCPAbstractPlottable::setSelected( bool selected ) { - if (mSelected != selected) + if( mSelected != selected ) { mSelected = selected; - emit selectionChanged(mSelected); + emit selectionChanged( mSelected ); } } @@ -7090,118 +7343,135 @@ void QCPAbstractPlottable::setSelected(bool selected) 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 +void QCPAbstractPlottable::rescaleAxes( bool onlyEnlarge ) const { - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); + 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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + if( !keyAxis ) { - 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 + 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) + 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 - 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); + newRange.lower = center / qSqrt( keyAxis->range().upper / keyAxis->range().lower ); + newRange.upper = center * qSqrt( keyAxis->range().upper / keyAxis->range().lower ); } } - keyAxis->setRange(newRange); + 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 +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) + QCPAxis* valueAxis = mValueAxis.data(); + if( !valueAxis ) { - 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 + 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) + 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 - 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); + newRange.lower = center / qSqrt( valueAxis->range().upper / valueAxis->range().lower ); + newRange.upper = center * qSqrt( valueAxis->range().upper / valueAxis->range().lower ); } } - valueAxis->setRange(newRange); + 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) + if( !mParentPlot || !mParentPlot->legend ) return false; - - if (!mParentPlot->legend->hasItemWithPlottable(this)) + + if( !mParentPlot->legend->hasItemWithPlottable( this ) ) { - mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); + mParentPlot->legend->addItem( new QCPPlottableLegendItem( mParentPlot->legend, this ) ); return true; - } else + } + else return false; } @@ -7209,19 +7479,19 @@ bool QCPAbstractPlottable::addToLegend() 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) + if( !mParentPlot->legend ) return false; - - if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) - return mParentPlot->legend->removeItem(lip); + + if( QCPPlottableLegendItem* lip = mParentPlot->legend->itemWithPlottable( this ) ) + return mParentPlot->legend->removeItem( lip ); else return false; } @@ -7229,7 +7499,7 @@ bool QCPAbstractPlottable::removeFromLegend() const /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { - if (mKeyAxis && mValueAxis) + if( mKeyAxis && mValueAxis ) return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); else return QRect(); @@ -7242,73 +7512,87 @@ QCP::Interaction QCPAbstractPlottable::selectionCategory() const } /*! \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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - x = keyAxis->coordToPixel(key); - y = valueAxis->coordToPixel(value); - } else + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + if( keyAxis->orientation() == Qt::Horizontal ) { - y = keyAxis->coordToPixel(key); - x = valueAxis->coordToPixel(value); + 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 +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)); + 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)); + 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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - key = keyAxis->pixelToCoord(x); - value = valueAxis->pixelToCoord(y); - } else + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + if( keyAxis->orientation() == Qt::Horizontal ) { - key = keyAxis->pixelToCoord(y); - value = valueAxis->pixelToCoord(x); + key = keyAxis->pixelToCoord( x ); + value = valueAxis->pixelToCoord( y ); + } + else + { + key = keyAxis->pixelToCoord( y ); + value = valueAxis->pixelToCoord( x ); } } @@ -7317,9 +7601,9 @@ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, doubl 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 +void QCPAbstractPlottable::pixelsToCoords( const QPointF& pixelPos, double& key, double& value ) const { - pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); + pixelsToCoords( pixelPos.x(), pixelPos.y(), key, value ); } /*! \internal @@ -7348,131 +7632,134 @@ QBrush QCPAbstractPlottable::mainBrush() const 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 +void QCPAbstractPlottable::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); + 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 +void QCPAbstractPlottable::applyFillAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); + 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 +void QCPAbstractPlottable::applyScattersAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); + 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 +void QCPAbstractPlottable::applyErrorBarsAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); + 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 +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); - + QVector2D a( start ); + QVector2D b( end ); + QVector2D p( point ); + QVector2D v( b - a ); + double vLengthSqr = v.lengthSquared(); - if (!qFuzzyIsNull(vLengthSqr)) + 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(); + 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(); + 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) +void QCPAbstractPlottable::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) + Q_UNUSED( event ) + Q_UNUSED( details ) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) + setSelected( additive ? !mSelected : true ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ -void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) +void QCPAbstractPlottable::deselectEvent( bool* selectionStateChanged ) { - if (mSelectable) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) + 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. @@ -7483,10 +7770,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) 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. */ @@ -7494,10 +7781,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /* 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). @@ -7510,41 +7797,41 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) 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( QCustomPlot* parentPlot, QCPAbstractItem* parentItem, const QString name, int anchorId ) + : mName( name ), mParentPlot( parentPlot ), mParentItem( parentItem ), mAnchorId( anchorId ) { } QCPItemAnchor::~QCPItemAnchor() { // unregister as parent at children: - QList currentChildren(mChildren.toList()); - for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren + QList currentChildren( mChildren.toList() ); + for( int i = 0; i < currentChildren.size(); ++i ) + currentChildren.at( i )->setParentAnchor( + 0 ); // this acts back on this anchor and child removes itself from mChildren } /*! 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( mParentItem ) { - if (mAnchorId > -1) + if( mAnchorId > -1 ) { - return mParentItem->anchorPixelPoint(mAnchorId); - } else + return mParentItem->anchorPixelPoint( mAnchorId ); + } + else { qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; return QPointF(); } - } else + } + else { qDebug() << Q_FUNC_INFO << "no parent item set"; return QPointF(); @@ -7555,37 +7842,36 @@ QPointF QCPItemAnchor::pixelPoint() const Adds \a pos to the child list of this anchor. 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::addChild(QCPItemPosition *pos) +void QCPItemAnchor::addChild( QCPItemPosition* pos ) { - if (!mChildren.contains(pos)) - mChildren.insert(pos); + if( !mChildren.contains( pos ) ) + mChildren.insert( pos ); else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast( pos ); } /*! \internal Removes \a pos from the child list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ -void QCPItemAnchor::removeChild(QCPItemPosition *pos) +void QCPItemAnchor::removeChild( QCPItemPosition* pos ) { - if (!mChildren.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if( !mChildren.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. @@ -7614,12 +7900,12 @@ void QCPItemAnchor::removeChild(QCPItemPosition *pos) 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), - mPositionType(ptAbsolute), - mKey(0), - mValue(0), - mParentAnchor(0) +QCPItemPosition::QCPItemPosition( QCustomPlot* parentPlot, QCPAbstractItem* parentItem, const QString name ) + : QCPItemAnchor( parentPlot, parentItem, name ), + mPositionType( ptAbsolute ), + mKey( 0 ), + mValue( 0 ), + mParentAnchor( 0 ) { } @@ -7627,17 +7913,19 @@ 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 - QList currentChildren(mChildren.toList()); - for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren + // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of + // QCPItemAnchor::pixelPoint + QList currentChildren( mChildren.toList() ); + for( int i = 0; i < currentChildren.size(); ++i ) + currentChildren.at( i )->setParentAnchor( + 0 ); // this acts back on this anchor and child removes itself from mChildren // unregister as child in parent: - if (mParentAnchor) - mParentAnchor->removeChild(this); + if( mParentAnchor ) + mParentAnchor->removeChild( this ); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ -QCPAxisRect *QCPItemPosition::axisRect() const +QCPAxisRect* QCPItemPosition::axisRect() const { return mAxisRect.data(); } @@ -7645,45 +7933,45 @@ QCPAxisRect *QCPItemPosition::axisRect() const /*! 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. */ -void QCPItemPosition::setType(QCPItemPosition::PositionType type) +void QCPItemPosition::setType( QCPItemPosition::PositionType type ) { - if (mPositionType != type) + if( mPositionType != 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 recoverPixelPosition = true; - if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) + if( ( mPositionType == ptPlotCoords || type == ptPlotCoords ) && ( !mKeyAxis || !mValueAxis ) ) recoverPixelPosition = false; - if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) + if( ( mPositionType == ptAxisRectRatio || type == ptAxisRectRatio ) && ( !mAxisRect ) ) recoverPixelPosition = false; - + QPointF pixelP; - if (recoverPixelPosition) + if( recoverPixelPosition ) pixelP = pixelPoint(); - + mPositionType = type; - - if (recoverPixelPosition) - setPixelPoint(pixelP); + + if( recoverPixelPosition ) + setPixelPoint( pixelP ); } } @@ -7692,78 +7980,81 @@ void QCPItemPosition::setType(QCPItemPosition::PositionType type) follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be \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. */ -bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) +bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPixelPosition ) { // make sure self is not assigned as parent: - if (parentAnchor == this) + if( parentAnchor == this ) { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); + 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) + QCPItemAnchor* currentParent = parentAnchor; + while( currentParent ) { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) + if( QCPItemPosition* currentParentPos = currentParent->toQCPItemPosition() ) { // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) + if( currentParentPos == this ) { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" + << reinterpret_cast( parentAnchor ); return false; } currentParent = currentParentPos->mParentAnchor; - } else + } + 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) + 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); + 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 (!mParentAnchor && mPositionType == ptPlotCoords) - setType(ptAbsolute); - + if( !mParentAnchor && mPositionType == ptPlotCoords ) + setType( ptAbsolute ); + // save pixel position: QPointF pixelP; - if (keepPixelPosition) + if( keepPixelPosition ) pixelP = pixelPoint(); // unregister at current parent anchor: - if (mParentAnchor) - mParentAnchor->removeChild(this); + if( mParentAnchor ) + mParentAnchor->removeChild( this ); // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChild(this); + if( parentAnchor ) + parentAnchor->addChild( this ); mParentAnchor = parentAnchor; // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPoint(pixelP); + if( keepPixelPosition ) + setPixelPoint( pixelP ); else - setCoords(0, 0); + setCoords( 0, 0 ); return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType). - + 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 @@ -7773,7 +8064,7 @@ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixe \see setPixelPoint */ -void QCPItemPosition::setCoords(double key, double value) +void QCPItemPosition::setCoords( double key, double value ) { mKey = key; mValue = value; @@ -7784,9 +8075,9 @@ void QCPItemPosition::setCoords(double key, double value) 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) +void QCPItemPosition::setCoords( const QPointF& pos ) { - setCoords(pos.x(), pos.y()); + setCoords( pos.x(), pos.y() ); } /*! @@ -7797,96 +8088,106 @@ void QCPItemPosition::setCoords(const QPointF &pos) */ QPointF QCPItemPosition::pixelPoint() const { - switch (mPositionType) + switch( mPositionType ) { case ptAbsolute: { - if (mParentAnchor) - return QPointF(mKey, mValue) + mParentAnchor->pixelPoint(); + if( mParentAnchor ) + return QPointF( mKey, mValue ) + mParentAnchor->pixelPoint(); else - return QPointF(mKey, mValue); + return QPointF( mKey, mValue ); } - + case ptViewportRatio: { - if (mParentAnchor) + if( mParentAnchor ) { - return QPointF(mKey*mParentPlot->viewport().width(), - mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint(); - } else + return QPointF( mKey * mParentPlot->viewport().width(), mValue * mParentPlot->viewport().height() ) + + mParentAnchor->pixelPoint(); + } + else { - return QPointF(mKey*mParentPlot->viewport().width(), - mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft(); + return QPointF( mKey * mParentPlot->viewport().width(), mValue * mParentPlot->viewport().height() ) + + mParentPlot->viewport().topLeft(); } } - + case ptAxisRectRatio: { - if (mAxisRect) + if( mAxisRect ) { - if (mParentAnchor) + if( mParentAnchor ) { - return QPointF(mKey*mAxisRect.data()->width(), - mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint(); - } else - { - return QPointF(mKey*mAxisRect.data()->width(), - mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft(); + return QPointF( mKey * mAxisRect.data()->width(), mValue * mAxisRect.data()->height() ) + + mParentAnchor->pixelPoint(); } - } else + else + { + return QPointF( mKey * mAxisRect.data()->width(), mValue * mAxisRect.data()->height() ) + + mAxisRect.data()->topLeft(); + } + } + else { qDebug() << Q_FUNC_INFO << "No axis rect defined"; - return QPointF(mKey, mValue); + return QPointF( mKey, mValue ); } } - + case ptPlotCoords: { double x, y; - if (mKeyAxis && mValueAxis) + if( mKeyAxis && mValueAxis ) { // both key and value axis are given, translate key/value to x/y coordinates: - if (mKeyAxis.data()->orientation() == Qt::Horizontal) + if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { - x = mKeyAxis.data()->coordToPixel(mKey); - y = mValueAxis.data()->coordToPixel(mValue); - } else - { - y = mKeyAxis.data()->coordToPixel(mKey); - x = mValueAxis.data()->coordToPixel(mValue); + x = mKeyAxis.data()->coordToPixel( mKey ); + y = mValueAxis.data()->coordToPixel( mValue ); } - } else if (mKeyAxis) + else + { + y = mKeyAxis.data()->coordToPixel( mKey ); + x = mValueAxis.data()->coordToPixel( mValue ); + } + } + else if( mKeyAxis ) { // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: - if (mKeyAxis.data()->orientation() == Qt::Horizontal) + if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { - x = mKeyAxis.data()->coordToPixel(mKey); + x = mKeyAxis.data()->coordToPixel( mKey ); y = mValue; - } else + } + else { - y = mKeyAxis.data()->coordToPixel(mKey); + y = mKeyAxis.data()->coordToPixel( mKey ); x = mValue; } - } else if (mValueAxis) + } + else if( mValueAxis ) { - // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: - if (mValueAxis.data()->orientation() == Qt::Horizontal) + // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays + // pixel: + if( mValueAxis.data()->orientation() == Qt::Horizontal ) { - x = mValueAxis.data()->coordToPixel(mValue); + x = mValueAxis.data()->coordToPixel( mValue ); y = mKey; - } else + } + else { - y = mValueAxis.data()->coordToPixel(mValue); + y = mValueAxis.data()->coordToPixel( mValue ); x = mKey; } - } else + } + else { // no axis given, basically the same as if mPositionType were ptAbsolute qDebug() << Q_FUNC_INFO << "No axes defined"; x = mKey; y = mValue; } - return QPointF(x, y); + return QPointF( x, y ); } } return QPointF(); @@ -7897,7 +8198,7 @@ QPointF QCPItemPosition::pixelPoint() const 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) +void QCPItemPosition::setAxes( QCPAxis* keyAxis, QCPAxis* valueAxis ) { mKeyAxis = keyAxis; mValueAxis = valueAxis; @@ -7908,7 +8209,7 @@ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) 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) +void QCPItemPosition::setAxisRect( QCPAxisRect* axisRect ) { mAxisRect = axisRect; } @@ -7923,151 +8224,164 @@ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) \see pixelPoint, setCoords */ -void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) +void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) { - switch (mPositionType) + switch( mPositionType ) { case ptAbsolute: { - if (mParentAnchor) - setCoords(pixelPoint-mParentAnchor->pixelPoint()); + if( mParentAnchor ) + setCoords( pixelPoint - mParentAnchor->pixelPoint() ); else - setCoords(pixelPoint); + setCoords( pixelPoint ); break; } - + case ptViewportRatio: { - if (mParentAnchor) + if( mParentAnchor ) { - QPointF p(pixelPoint-mParentAnchor->pixelPoint()); + QPointF p( pixelPoint - mParentAnchor->pixelPoint() ); p.rx() /= (double)mParentPlot->viewport().width(); p.ry() /= (double)mParentPlot->viewport().height(); - setCoords(p); - } else + setCoords( p ); + } + else { - QPointF p(pixelPoint-mParentPlot->viewport().topLeft()); + QPointF p( pixelPoint - mParentPlot->viewport().topLeft() ); p.rx() /= (double)mParentPlot->viewport().width(); p.ry() /= (double)mParentPlot->viewport().height(); - setCoords(p); + setCoords( p ); } break; } - + case ptAxisRectRatio: { - if (mAxisRect) + if( mAxisRect ) { - if (mParentAnchor) + if( mParentAnchor ) { - QPointF p(pixelPoint-mParentAnchor->pixelPoint()); + QPointF p( pixelPoint - mParentAnchor->pixelPoint() ); p.rx() /= (double)mAxisRect.data()->width(); p.ry() /= (double)mAxisRect.data()->height(); - setCoords(p); - } else - { - QPointF p(pixelPoint-mAxisRect.data()->topLeft()); - p.rx() /= (double)mAxisRect.data()->width(); - p.ry() /= (double)mAxisRect.data()->height(); - setCoords(p); + setCoords( p ); } - } else + else + { + QPointF p( pixelPoint - mAxisRect.data()->topLeft() ); + p.rx() /= (double)mAxisRect.data()->width(); + p.ry() /= (double)mAxisRect.data()->height(); + setCoords( p ); + } + } + else { qDebug() << Q_FUNC_INFO << "No axis rect defined"; - setCoords(pixelPoint); + setCoords( pixelPoint ); } break; } - + case ptPlotCoords: { double newKey, newValue; - if (mKeyAxis && mValueAxis) + if( mKeyAxis && mValueAxis ) { // both key and value axis are given, translate point to key/value coordinates: - if (mKeyAxis.data()->orientation() == Qt::Horizontal) + if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { - newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); - newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); - } else - { - newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); - newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); + newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.x() ); + newValue = mValueAxis.data()->pixelToCoord( pixelPoint.y() ); } - } else if (mKeyAxis) + else + { + newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.y() ); + newValue = mValueAxis.data()->pixelToCoord( pixelPoint.x() ); + } + } + else if( mKeyAxis ) { // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: - if (mKeyAxis.data()->orientation() == Qt::Horizontal) + if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { - newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); + newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.x() ); newValue = pixelPoint.y(); - } else + } + else { - newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); + newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.y() ); newValue = pixelPoint.x(); } - } else if (mValueAxis) + } + else if( mValueAxis ) { - // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: - if (mValueAxis.data()->orientation() == Qt::Horizontal) + // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays + // pixel: + if( mValueAxis.data()->orientation() == Qt::Horizontal ) { newKey = pixelPoint.y(); - newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); - } else + newValue = mValueAxis.data()->pixelToCoord( pixelPoint.x() ); + } + else { newKey = pixelPoint.x(); - newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); + newValue = mValueAxis.data()->pixelToCoord( pixelPoint.y() ); } - } else + } + else { // no axis given, basically the same as if mPositionType were ptAbsolute qDebug() << Q_FUNC_INFO << "No axes defined"; newKey = pixelPoint.x(); newValue = pixelPoint.y(); } - setCoords(newKey, newValue); + setCoords( newKey, newValue ); break; } } } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// 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:
QCustomPlot *\b mParentPlotA pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the + constructor.
QString \b mName The 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)The 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).The 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)The 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).The 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.The 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 mSelected indicates whether the plottable is selected or not.
- - - + + + - +
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).
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.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key + coordinate.
- + Items are by default clipped to the main axis rect. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect. - + \section items-using Using items - + First you instantiate the item you want to use and add it to the plot: \code QCPItemLine *line = new QCPItemLine(customPlot); @@ -8090,31 +8404,31 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) line->start->setCoords(100, 200); line->end->setCoords(450, 320); \endcode - + \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), @@ -8123,9 +8437,9 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) // 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. @@ -8133,19 +8447,19 @@ void QCPItemPosition::setPixelPoint(const QPointF &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 @@ -8153,7 +8467,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) 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. */ @@ -8161,17 +8475,17 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /* 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 */ @@ -8180,9 +8494,9 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /*! \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. @@ -8201,28 +8515,25 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /*! Base class constructor which initializes base class members. */ -QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), - mClipToAxisRect(false), - mSelectable(true), - mSelected(false) +QCPAbstractItem::QCPAbstractItem( QCustomPlot* parentPlot ) + : QCPLayerable( parentPlot ), mClipToAxisRect( false ), mSelectable( true ), mSelected( false ) { QList rects = parentPlot->axisRects(); - if (rects.size() > 0) + if( rects.size() > 0 ) { - setClipToAxisRect(true); - setClipAxisRect(rects.first()); + setClipToAxisRect( true ); + setClipAxisRect( rects.first() ); } } QCPAbstractItem::~QCPAbstractItem() { // don't delete mPositions because every position is also an anchor and thus in mAnchors - qDeleteAll(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 +QCPAxisRect* QCPAbstractItem::clipAxisRect() const { return mClipAxisRect.data(); } @@ -8230,44 +8541,44 @@ QCPAxisRect *QCPAbstractItem::clipAxisRect() const /*! 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) +void QCPAbstractItem::setClipToAxisRect( bool clip ) { mClipToAxisRect = clip; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + 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) +void QCPAbstractItem::setClipAxisRect( QCPAxisRect* rect ) { mClipAxisRect = rect; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + 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) +void QCPAbstractItem::setSelectable( bool selectable ) { - if (mSelectable != selectable) + if( mSelectable != selectable ) { mSelectable = selectable; - emit selectableChanged(mSelectable); + emit selectableChanged( mSelectable ); } } @@ -8278,38 +8589,38 @@ void QCPAbstractItem::setSelectable(bool selectable) 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) +void QCPAbstractItem::setSelected( bool selected ) { - if (mSelected != selected) + if( mSelected != selected ) { mSelected = selected; - emit selectionChanged(mSelected); + 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 +QCPItemPosition* QCPAbstractItem::position( const QString& name ) const { - for (int i=0; iname() == name) - return mPositions.at(i); + if( mPositions.at( i )->name() == name ) + return mPositions.at( i ); } qDebug() << Q_FUNC_INFO << "position with name not found:" << name; return 0; @@ -8318,19 +8629,19 @@ QCPItemPosition *QCPAbstractItem::position(const QString &name) const /*! 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 +QCPItemAnchor* QCPAbstractItem::anchor( const QString& name ) const { - for (int i=0; iname() == name) - return mAnchors.at(i); + if( mAnchors.at( i )->name() == name ) + return mAnchors.at( i ); } qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; return 0; @@ -8338,34 +8649,34 @@ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const /*! 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 +bool QCPAbstractItem::hasAnchor( const QString& name ) const { - for (int i=0; iname() == name) + if( mAnchors.at( i )->name() == 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) + if( mClipToAxisRect && mClipAxisRect ) return mClipAxisRect.data()->rect(); else return mParentPlot->viewport(); @@ -8377,49 +8688,50 @@ QRect QCPAbstractItem::clipRect() const 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 +void QCPAbstractItem::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); + 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 +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); - + QVector2D a( start ); + QVector2D b( end ); + QVector2D p( point ); + QVector2D v( b - a ); + double vLengthSqr = v.lengthSquared(); - if (!qFuzzyIsNull(vLengthSqr)) + 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(); + 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(); + return ( ( a + mu * v ) - p ).lengthSquared(); + } + else + return ( a - p ).lengthSquared(); } /*! \internal @@ -8427,40 +8739,40 @@ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, 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 which were greater or equal to zero. (Because this function may return -1.0 when \a pos doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item wasn't hit. - + \see distSqrToLine */ -double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const +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()); + 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( filledRect && result > mParentPlot->selectionTolerance() * 0.99 ) { - if (rect.contains(pos)) - result = mParentPlot->selectionTolerance()*0.99; + if( rect.contains( pos ) ) + result = mParentPlot->selectionTolerance() * 0.99; } return result; } @@ -8469,15 +8781,16 @@ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, b 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 +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; + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" + << anchorId; return QPointF(); } @@ -8486,27 +8799,27 @@ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const 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) +QCPItemPosition* QCPAbstractItem::createPosition( const QString& name ) { - if (hasAnchor(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); + 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; } @@ -8515,51 +8828,54 @@ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) 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) +QCPItemAnchor* QCPAbstractItem::createAnchor( const QString& name, int anchorId ) { - if (hasAnchor(name)) + 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); + 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) +void QCPAbstractItem::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) + Q_UNUSED( event ) + Q_UNUSED( details ) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) + setSelected( additive ? !mSelected : true ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ -void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) +void QCPAbstractItem::deselectEvent( bool* selectionStateChanged ) { - if (mSelectable) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) + setSelected( false ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } @@ -8570,26 +8886,23 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const return QCP::iSelectItems; } - /*! \file */ - - /*! \mainpage %QCustomPlot 1.2.1 Documentation \image html qcp-doc-logo.png - + Below is a brief overview of and guide to the classes and their relations. If you are new to QCustomPlot and just want to start using it, it's recommended to look at the tutorials and examples at - + http://www.qcustomplot.com/ - + This documentation is especially helpful as a reference, when you're familiar with the basic concept of how to use %QCustomPlot and you wish to learn more about specific functionality. See the \ref classoverview "class overview" for diagrams explaining the relationships between the most important classes of the QCustomPlot library. - + The central widget which displays the plottables and axes on its surface is QCustomPlot. Every QCustomPlot contains four axes by default. They can be accessed via the members \ref QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2" @@ -8597,15 +8910,15 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const number of axes and axis rects, see the documentation of QCPAxisRect for details. \section mainpage-plottables Plottables - + \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph inside the plot with different line styles, scatter styles, filling etc. - + Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working with QCPGraph plottables, that makes it very easy to handle them:\n You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph. - + For all other plottables, you need to use the normal plottable interface:\n First, you create an instance of the plottable you want, e.g. \code @@ -8614,41 +8927,41 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const \code customPlot->addPlottable(newCurve);\endcode and then modify the properties of the newly created plottable via the newCurve pointer. - + Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will probably want to qobject_cast the returned pointer to the respective plottable subclass. (As usual, if the cast returns zero, the plottable wasn't of that specific subclass.) - + All further interfacing with plottables (e.g how to set data) is specific to the plottable type. See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox, QCPColorMap. \section mainpage-axes Controlling the Axes - + As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2 (top), \a yAxis2 (right). - + Their range is handled by the simple QCPRange class. You can set the range with the QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely with \ref QCPAxis::setScaleLogBase. - + By default, an axis automatically creates and labels ticks in a sensible manner. See the following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks, QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels, QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep, QCPAxis::setTickLength,... - + Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel. - + The distance of an axis backbone to the respective viewport border is called its margin. Normally, the margins are calculated automatically. To change this, set \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect(). - + \section mainpage-legend Plot Legend - + Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small layout element inside the plot which lists the plottables with an icon of the plottable line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from @@ -8656,61 +8969,61 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot automatically adds it to the legend, too. This behaviour can be modified with the QCustomPlot::setAutoAddPlottableToLegend property. - + The QCPLegend provides an interface to access, add and remove legend items directly, too. See QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for example. - + Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a QCPLegend simply is a normal layout element). - + \section mainpage-userinteraction User Interactions - + QCustomPlot supports dragging axis ranges with the mouse (\ref QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref QCPAxisRect::setRangeZoom) and a complete selection mechanism. - + The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For details about the interaction system, see the documentation there. - + Further, QCustomPlot always emits corresponding signals, when objects are clicked or doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick and \ref QCustomPlot::axisClick for example. - + \section mainpage-items Items - + Apart from plottables there is another category of plot objects that are important: Items. The base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel coordinates or placed at a relative position on an axis rect. Further, it usually doesn't represent data directly, but acts as decoration, emphasis, description etc. - + Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For example, you could place the head of an arrow at a fixed plot coordinate, so it always points to some important area in the plot. The tail of the arrow can be anchored to a text item which always resides in the top center of the axis rect, independent of where the user drags the axis ranges. This way the arrow stretches and turns so it always points from the label to the specified plot coordinate, without any further code necessary. - + For a more detailed introduction, see the QCPAbstractItem documentation, and from there the documentations of the individual built-in items, to find out how to use them. - + \section mainpage-layoutelements Layout elements and layouts - + QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by placing them inside a \ref QCPLayout. - + Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink. - + \section mainpage-performancetweaks Performance Tweaks - + Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick lines can cause a significant slow down. If you notice this in your application, here are some thoughts on how to increase performance. By far the most time is spent in the drawing functions, specifically the drawing of graphs. For maximum performance, consider the following (most recommended/effective measures first): - + \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >= 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8. @@ -8731,13 +9044,14 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const \li Avoid any kind of alpha (transparency), especially in fills \li Avoid lines with a pen width greater than one \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements) - \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most + \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if + most data points stay unchanged, e.g. in a running measurement. \li Set the \a copy parameter of the setData functions to false, so only pointers get transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000) - + \section mainpage-flags Preprocessor Define Flags - + QCustomPlot understands some preprocessor defines that are useful for debugging and compilation:
\c QCUSTOMPLOT_COMPILE_LIBRARY @@ -8753,15 +9067,15 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const */ /*! \page classoverview Class Overview - + The following diagrams may help to gain a deeper understanding of the relationships between classes that make up the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown. - + \section classoverview-relations Class Relationship Diagram \image html RelationOverview.png "Overview of most important classes and their relations" \section classoverview-inheritance Class Inheritance Tree \image html InheritanceOverview.png "Inheritance tree of most important classes" - + */ //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -8769,10 +9083,10 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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/ */ @@ -8780,22 +9094,22 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /* 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, 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. */ @@ -8811,7 +9125,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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. @@ -8820,11 +9134,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 @@ -8834,7 +9148,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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. @@ -8843,150 +9157,150 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 */ @@ -8996,7 +9310,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 @@ -9009,7 +9323,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 @@ -9024,7 +9338,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 @@ -9039,7 +9353,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 @@ -9053,7 +9367,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 @@ -9069,75 +9383,76 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! 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) +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); + setAttribute( Qt::WA_NoMousePropagation ); + setAttribute( Qt::WA_OpaquePaintEvent ); + setMouseTracking( true ); QLocale currentLocale = locale(); - currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); - setLocale(currentLocale); - + currentLocale.setNumberOptions( QLocale::OmitGroupSeparator ); + setLocale( currentLocale ); + // create initial layers: - mLayers.append(new QCPLayer(this, "background")); - mLayers.append(new QCPLayer(this, "grid")); - mLayers.append(new QCPLayer(this, "main")); - mLayers.append(new QCPLayer(this, "axes")); - mLayers.append(new QCPLayer(this, "legend")); + mLayers.append( new QCPLayer( this, "background" ) ); + mLayers.append( new QCPLayer( this, "grid" ) ); + mLayers.append( new QCPLayer( this, "main" ) ); + mLayers.append( new QCPLayer( this, "axes" ) ); + mLayers.append( new QCPLayer( this, "legend" ) ); updateLayerIndices(); - setCurrentLayer("main"); - + setCurrentLayer( "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("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); + mPlotLayout->initializeParentPlot( this ); + mPlotLayout->setParent( this ); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will + // call QWidget::updateGeometry + mPlotLayout->setLayer( "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("background"); - xAxis->setLayer("axes"); - yAxis->setLayer("axes"); - xAxis2->setLayer("axes"); - yAxis2->setLayer("axes"); - xAxis->grid()->setLayer("grid"); - yAxis->grid()->setLayer("grid"); - xAxis2->grid()->setLayer("grid"); - yAxis2->grid()->setLayer("grid"); - legend->setLayer("legend"); - - setViewport(rect()); // needs to be called after mPlotLayout has been created - + legend->setVisible( false ); + defaultAxisRect->insetLayout()->addElement( legend, Qt::AlignRight | Qt::AlignTop ); + defaultAxisRect->insetLayout()->setMargins( QMargins( 12, 12, 12, 12 ) ); + + defaultAxisRect->setLayer( "background" ); + xAxis->setLayer( "axes" ); + yAxis->setLayer( "axes" ); + xAxis2->setLayer( "axes" ); + yAxis2->setLayer( "axes" ); + xAxis->grid()->setLayer( "grid" ); + yAxis->grid()->setLayer( "grid" ); + xAxis2->grid()->setLayer( "grid" ); + yAxis2->grid()->setLayer( "grid" ); + legend->setLayer( "legend" ); + + setViewport( rect() ); // needs to be called after mPlotLayout has been created + replot(); } @@ -9146,115 +9461,115 @@ QCustomPlot::~QCustomPlot() clearPlottables(); clearItems(); - if (mPlotLayout) + if( mPlotLayout ) { delete mPlotLayout; mPlotLayout = 0; } - + mCurrentLayer = 0; - qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + 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) +void QCustomPlot::setAntialiasedElements( const QCP::AntialiasedElements& antialiasedElements ) { mAntialiasedElements = antialiasedElements; - + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + 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) +void QCustomPlot::setAntialiasedElement( QCP::AntialiasedElement antialiasedElement, bool enabled ) { - if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) + if( !enabled && mAntialiasedElements.testFlag( antialiasedElement ) ) mAntialiasedElements &= ~antialiasedElement; - else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) + else if( enabled && !mAntialiasedElements.testFlag( antialiasedElement ) ) mAntialiasedElements |= antialiasedElement; - + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + 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) +void QCustomPlot::setNotAntialiasedElements( const QCP::AntialiasedElements& notAntialiasedElements ) { mNotAntialiasedElements = notAntialiasedElements; - + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + 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) +void QCustomPlot::setNotAntialiasedElement( QCP::AntialiasedElement notAntialiasedElement, bool enabled ) { - if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) + if( !enabled && mNotAntialiasedElements.testFlag( notAntialiasedElement ) ) mNotAntialiasedElements &= ~notAntialiasedElement; - else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) + else if( enabled && !mNotAntialiasedElements.testFlag( notAntialiasedElement ) ) mNotAntialiasedElements |= notAntialiasedElement; - + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + 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) +void QCustomPlot::setAutoAddPlottableToLegend( bool on ) { mAutoAddPlottableToLegend = on; } @@ -9262,13 +9577,13 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool 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 @@ -9277,76 +9592,76 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on) 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) +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) +void QCustomPlot::setInteraction( const QCP::Interaction& interaction, bool enabled ) { - if (!enabled && mInteractions.testFlag(interaction)) + if( !enabled && mInteractions.testFlag( interaction ) ) mInteractions &= ~interaction; - else if (enabled && !mInteractions.testFlag(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) +void QCustomPlot::setSelectionTolerance( int pixels ) { mSelectionTolerance = pixels; } @@ -9357,52 +9672,52 @@ void QCustomPlot::setSelectionTolerance(int pixels) 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) +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) +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) +void QCustomPlot::setPlottingHint( QCP::PlottingHint hint, bool enabled ) { QCP::PlottingHints newHints = mPlottingHints; - if (!enabled) + if( !enabled ) newHints &= ~hint; else newHints |= hint; - - if (newHints != mPlottingHints) - setPlottingHints(newHints); + + 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) +void QCustomPlot::setMultiSelectModifier( Qt::KeyboardModifier modifier ) { mMultiSelectModifier = modifier; } @@ -9410,15 +9725,15 @@ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier 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) +void QCustomPlot::setViewport( const QRect& rect ) { mViewport = rect; - if (mPlotLayout) - mPlotLayout->setOuterRect(mViewport); + if( mPlotLayout ) + mPlotLayout->setOuterRect( mViewport ); } /*! @@ -9429,14 +9744,14 @@ void QCustomPlot::setViewport(const QRect &rect) 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) +void QCustomPlot::setBackground( const QPixmap& pm ) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); @@ -9449,25 +9764,25 @@ void QCustomPlot::setBackground(const QPixmap &pm) 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) +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) +void QCustomPlot::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode ) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); @@ -9479,13 +9794,13 @@ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioM 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) +void QCustomPlot::setBackgroundScaled( bool scaled ) { mBackgroundScaled = scaled; } @@ -9493,28 +9808,29 @@ void QCustomPlot::setBackgroundScaled(bool 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) +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) +QCPAbstractPlottable* QCustomPlot::plottable( int index ) { - if (index >= 0 && index < mPlottables.size()) + if( index >= 0 && index < mPlottables.size() ) { - return mPlottables.at(index); - } else + return mPlottables.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; @@ -9522,90 +9838,94 @@ QCPAbstractPlottable *QCustomPlot::plottable(int index) } /*! \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() +QCPAbstractPlottable* QCustomPlot::plottable() { - if (!mPlottables.isEmpty()) + if( !mPlottables.isEmpty() ) { return mPlottables.last(); - } else + } + 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) +bool QCustomPlot::addPlottable( QCPAbstractPlottable* plottable ) { - if (mPlottables.contains(plottable)) + if( mPlottables.contains( plottable ) ) { - qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); + qDebug() << Q_FUNC_INFO + << "plottable already added to this QCustomPlot:" << reinterpret_cast( plottable ); return false; } - if (plottable->parentPlot() != this) + if( plottable->parentPlot() != this ) { - qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); + qDebug() << Q_FUNC_INFO + << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast( plottable ); return false; } - - mPlottables.append(plottable); + + mPlottables.append( plottable ); // possibly add plottable to legend: - if (mAutoAddPlottableToLegend) + 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()); + 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) +bool QCustomPlot::removePlottable( QCPAbstractPlottable* plottable ) { - if (!mPlottables.contains(plottable)) + if( !mPlottables.contains( plottable ) ) { - qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(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); + if( QCPGraph* graph = qobject_cast( plottable ) ) + mGraphs.removeOne( graph ); // remove plottable: delete plottable; - mPlottables.removeOne(plottable); + mPlottables.removeOne( plottable ); return true; } /*! \overload - + Removes the plottable by its \a index. */ -bool QCustomPlot::removePlottable(int index) +bool QCustomPlot::removePlottable( int index ) { - if (index >= 0 && index < mPlottables.size()) - return removePlottable(mPlottables[index]); + if( index >= 0 && index < mPlottables.size() ) + return removePlottable( mPlottables[index] ); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; @@ -9615,22 +9935,22 @@ bool QCustomPlot::removePlottable(int index) /*! 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]); + 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 @@ -9640,18 +9960,18 @@ int QCustomPlot::plottableCount() const /*! 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) + foreach( QCPAbstractPlottable* plottable, mPlottables ) { - if (plottable->selected()) - result.append(plottable); + if( plottable->selected() ) + result.append( plottable ); } return result; } @@ -9660,61 +9980,67 @@ QList QCustomPlot::selectedPlottables() const 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* 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) + 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 + 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 + 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) + 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 +bool QCustomPlot::hasPlottable( QCPAbstractPlottable* plottable ) const { - return mPlottables.contains(plottable); + 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 +QCPGraph* QCustomPlot::graph( int index ) const { - if (index >= 0 && index < mGraphs.size()) + if( index >= 0 && index < mGraphs.size() ) { - return mGraphs.at(index); - } else + return mGraphs.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; @@ -9722,18 +10048,19 @@ QCPGraph *QCustomPlot::graph(int index) const } /*! \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 +QCPGraph* QCustomPlot::graph() const { - if (!mGraphs.isEmpty()) + if( !mGraphs.isEmpty() ) { return mGraphs.last(); - } else + } + else return 0; } @@ -9741,35 +10068,39 @@ QCPGraph *QCustomPlot::graph() const 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) +QCPGraph* QCustomPlot::addGraph( QCPAxis* keyAxis, QCPAxis* valueAxis ) { - if (!keyAxis) keyAxis = xAxis; - if (!valueAxis) valueAxis = yAxis; - if (!keyAxis || !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)"; + 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) + 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)) + + QCPGraph* newGraph = new QCPGraph( keyAxis, valueAxis ); + if( addPlottable( newGraph ) ) { - newGraph->setName("Graph "+QString::number(mGraphs.size())); + newGraph->setName( "Graph " + QString::number( mGraphs.size() ) ); return newGraph; - } else + } + else { delete newGraph; return 0; @@ -9780,24 +10111,24 @@ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) 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) +bool QCustomPlot::removeGraph( QCPGraph* graph ) { - return removePlottable(graph); + return removePlottable( graph ); } /*! \overload - + Removes the graph by its \a index. */ -bool QCustomPlot::removeGraph(int index) +bool QCustomPlot::removeGraph( int index ) { - if (index >= 0 && index < mGraphs.size()) - return removeGraph(mGraphs[index]); + if( index >= 0 && index < mGraphs.size() ) + return removeGraph( mGraphs[index] ); else return false; } @@ -9806,20 +10137,20 @@ bool QCustomPlot::removeGraph(int index) 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]); + 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 @@ -9829,37 +10160,38 @@ int QCustomPlot::graphCount() const /*! 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) + foreach( QCPGraph* graph, mGraphs ) { - if (graph->selected()) - result.append(graph); + 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 +QCPAbstractItem* QCustomPlot::item( int index ) const { - if (index >= 0 && index < mItems.size()) + if( index >= 0 && index < mItems.size() ) { - return mItems.at(index); - } else + return mItems.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; @@ -9867,71 +10199,75 @@ QCPAbstractItem *QCustomPlot::item(int index) const } /*! \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 +QCPAbstractItem* QCustomPlot::item() const { - if (!mItems.isEmpty()) + if( !mItems.isEmpty() ) { return mItems.last(); - } else + } + 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) +bool QCustomPlot::addItem( QCPAbstractItem* item ) { - if (!mItems.contains(item) && item->parentPlot() == this) + if( !mItems.contains( item ) && item->parentPlot() == this ) { - mItems.append(item); + mItems.append( item ); return true; - } else + } + else { - qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); + 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) +bool QCustomPlot::removeItem( QCPAbstractItem* item ) { - if (mItems.contains(item)) + if( mItems.contains( item ) ) { delete item; - mItems.removeOne(item); + mItems.removeOne( item ); return true; - } else + } + else { - qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + 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) +bool QCustomPlot::removeItem( int index ) { - if (index >= 0 && index < mItems.size()) - return removeItem(mItems[index]); + if( index >= 0 && index < mItems.size() ) + return removeItem( mItems[index] ); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; @@ -9941,22 +10277,22 @@ bool QCustomPlot::removeItem(int index) /*! 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]); + 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 @@ -9966,16 +10302,16 @@ int QCustomPlot::itemCount() const /*! 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) + foreach( QCPAbstractItem* item, mItems ) { - if (item->selected()) - result.append(item); + if( item->selected() ) + result.append( item ); } return result; } @@ -9985,77 +10321,83 @@ QList QCustomPlot::selectedItems() const 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* 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) + 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 + 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 + 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) + 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 +bool QCustomPlot::hasItem( QCPAbstractItem* item ) const { - return mItems.contains(item); + 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 +QCPLayer* QCustomPlot::layer( const QString& name ) const { - foreach (QCPLayer *layer, mLayers) + foreach( QCPLayer* layer, mLayers ) { - if (layer->name() == name) + 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 +QCPLayer* QCustomPlot::layer( int index ) const { - if (index >= 0 && index < mLayers.size()) + if( index >= 0 && index < mLayers.size() ) { - return mLayers.at(index); - } else + return mLayers.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; @@ -10065,7 +10407,7 @@ QCPLayer *QCustomPlot::layer(int index) const /*! Returns the layer that is set as current layer (see \ref setCurrentLayer). */ -QCPLayer *QCustomPlot::currentLayer() const +QCPLayer* QCustomPlot::currentLayer() const { return mCurrentLayer; } @@ -10073,19 +10415,20 @@ QCPLayer *QCustomPlot::currentLayer() const /*! 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) +bool QCustomPlot::setCurrentLayer( const QString& name ) { - if (QCPLayer *newCurrentLayer = layer(name)) + if( QCPLayer* newCurrentLayer = layer( name ) ) { - return setCurrentLayer(newCurrentLayer); - } else + return setCurrentLayer( newCurrentLayer ); + } + else { qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; return false; @@ -10093,28 +10436,28 @@ bool QCustomPlot::setCurrentLayer(const QString &name) } /*! \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) +bool QCustomPlot::setCurrentLayer( QCPLayer* layer ) { - if (!mLayers.contains(layer)) + if( !mLayers.contains( layer ) ) { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(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 @@ -10125,84 +10468,86 @@ int QCustomPlot::layerCount() const /*! 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) +bool QCustomPlot::addLayer( const QString& name, QCPLayer* otherLayer, QCustomPlot::LayerInsertMode insertMode ) { - if (!otherLayer) + if( !otherLayer ) otherLayer = mLayers.last(); - if (!mLayers.contains(otherLayer)) + if( !mLayers.contains( otherLayer ) ) { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + qDebug() << Q_FUNC_INFO + << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast( otherLayer ); return false; } - if (layer(name)) + 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); + + 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) +bool QCustomPlot::removeLayer( QCPLayer* layer ) { - if (!mLayers.contains(layer)) + if( !mLayers.contains( layer ) ) { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); return false; } - if (mLayers.size() < 2) + 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); + 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) + 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 = children.size() - 1; i >= 0; --i ) + children.at( i )->moveToLayer( targetLayer, true ); + } + else // append normally { - for (int i=0; imoveToLayer(targetLayer, false); + for( int i = 0; i < children.size(); ++i ) + children.at( i )->moveToLayer( targetLayer, false ); } // if removed layer is current layer, change current layer to layer below/above: - if (layer == mCurrentLayer) - setCurrentLayer(targetLayer); + if( layer == mCurrentLayer ) + setCurrentLayer( targetLayer ); // remove layer: delete layer; - mLayers.removeOne(layer); + mLayers.removeOne( layer ); updateLayerIndices(); return true; } @@ -10210,37 +10555,38 @@ bool QCustomPlot::removeLayer(QCPLayer *layer) /*! 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) +bool QCustomPlot::moveLayer( QCPLayer* layer, QCPLayer* otherLayer, QCustomPlot::LayerInsertMode insertMode ) { - if (!mLayers.contains(layer)) + if( !mLayers.contains( layer ) ) { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); return false; } - if (!mLayers.contains(otherLayer)) + if( !mLayers.contains( otherLayer ) ) { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + qDebug() << Q_FUNC_INFO + << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast( otherLayer ); return false; } - - mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); + + mLayers.move( layer->index(), otherLayer->index() + ( insertMode == limAbove ? 1 : 0 ) ); 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 @@ -10250,20 +10596,21 @@ int QCustomPlot::axisRectCount() const /*! 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 +QCPAxisRect* QCustomPlot::axisRect( int index ) const { const QList rectList = axisRects(); - if (index >= 0 && index < rectList.size()) + if( index >= 0 && index < rectList.size() ) { - return rectList.at(index); - } else + return rectList.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; return 0; @@ -10272,51 +10619,51 @@ QCPAxisRect *QCustomPlot::axisRect(int index) const /*! 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()) + if( mPlotLayout ) + elementStack.push( mPlotLayout ); + + while( !elementStack.isEmpty() ) { - foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) + foreach( QCPLayoutElement* element, elementStack.pop()->elements( false ) ) { - if (element) + if( element ) { - elementStack.push(element); - if (QCPAxisRect *ar = qobject_cast(element)) - result.append(ar); + 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* QCustomPlot::layoutElementAt( const QPointF& pos ) const { - QCPLayoutElement *currentElement = mPlotLayout; + QCPLayoutElement* currentElement = mPlotLayout; bool searchSubElements = true; - while (searchSubElements && currentElement) + while( searchSubElements && currentElement ) { searchSubElements = false; - foreach (QCPLayoutElement *subElement, currentElement->elements(false)) + foreach( QCPLayoutElement* subElement, currentElement->elements( false ) ) { - if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) + if( subElement && subElement->realVisibility() && subElement->selectTest( pos, false ) >= 0 ) { currentElement = subElement; searchSubElements = true; @@ -10330,74 +10677,74 @@ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const /*! 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()) + QList result, allAxes; + foreach( QCPAxisRect* rect, axisRects() ) allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) + + foreach( QCPAxis* axis, allAxes ) { - if (axis->selectedParts() != QCPAxis::spNone) - result.append(axis); + 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()) + if( mPlotLayout ) + elementStack.push( mPlotLayout ); + + while( !elementStack.isEmpty() ) { - foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) + foreach( QCPLayoutElement* subElement, elementStack.pop()->elements( false ) ) { - if (subElement) + if( subElement ) { - elementStack.push(subElement); - if (QCPLegend *leg = qobject_cast(subElement)) + elementStack.push( subElement ); + if( QCPLegend* leg = qobject_cast( subElement ) ) { - if (leg->selectedParts() != QCPLegend::spNone) - result.append(leg); + 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( QCPLayer* layer, mLayers ) { - foreach (QCPLayerable *layerable, layer->children()) - layerable->deselectEvent(0); + foreach( QCPLayerable* layerable, layer->children() ) + layerable->deselectEvent( 0 ); } } @@ -10405,59 +10752,62 @@ void QCustomPlot::deselectAll() 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) +void QCustomPlot::replot( QCustomPlot::RefreshPriority refreshPriority ) { - if (mReplotting) // incase signals loop back to replot slot + if( mReplotting ) // incase signals loop back to replot slot return; mReplotting = true; emit beforeReplot(); - - mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); + + mPaintBuffer.fill( mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent ); QCPPainter painter; - painter.begin(&mPaintBuffer); - if (painter.isActive()) + 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.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) + if( ( refreshPriority == rpHint && mPlottingHints.testFlag( QCP::phForceRepaint ) ) || + refreshPriority == rpImmediate ) repaint(); else update(); - } else // might happen if QCustomPlot has width or height zero + } + else // might happen if QCustomPlot has width or height zero qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer"; - + 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) +void QCustomPlot::rescaleAxes( bool onlyVisiblePlottables ) { QList allAxes; - foreach (QCPAxisRect *rect, axisRects()) + foreach( QCPAxisRect* rect, axisRects() ) allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - axis->rescale(onlyVisiblePlottables); + + foreach( QCPAxis* axis, allAxes ) + axis->rescale( onlyVisiblePlottables ); } /*! @@ -10471,13 +10821,13 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) 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 @@ -10488,64 +10838,69 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) 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 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( fileName ) + Q_UNUSED( noCosmeticPen ) + Q_UNUSED( width ) + Q_UNUSED( height ) 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) + if( width == 0 || height == 0 ) { newWidth = this->width(); newHeight = this->height(); - } else + } + else { newWidth = width; newHeight = height; } - - QPrinter printer(QPrinter::ScreenResolution); - printer.setOutputFileName(fileName); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setFullPage(true); - printer.setColorMode(QPrinter::Color); - printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); - printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + + QPrinter printer( QPrinter::ScreenResolution ); + printer.setOutputFileName( fileName ); + printer.setOutputFormat( QPrinter::PdfFormat ); + printer.setFullPage( true ); + 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)); - printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); + setViewport( QRect( 0, 0, newWidth, newHeight ) ); + printer.setPaperSize( viewport().size(), QPrinter::DevicePixel ); QCPPainter printpainter; - if (printpainter.begin(&printer)) + 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 && + 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); + 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 + setViewport( oldViewport ); +#endif // QT_NO_PRINTER return success; } @@ -10559,7 +10914,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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. @@ -10570,7 +10925,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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. @@ -10580,15 +10935,15 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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) +bool QCustomPlot::savePng( const QString& fileName, int width, int height, double scale, int quality ) { - return saveRastered(fileName, width, height, scale, "PNG", quality); + return saveRastered( fileName, width, height, scale, "PNG", quality ); } /*! @@ -10601,7 +10956,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double 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. @@ -10619,15 +10974,15 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double 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) +bool QCustomPlot::saveJpg( const QString& fileName, int width, int height, double scale, int quality ) { - return saveRastered(fileName, width, height, scale, "JPG", quality); + return saveRastered( fileName, width, height, scale, "JPG", quality ); } /*! @@ -10640,7 +10995,7 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double 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. @@ -10655,19 +11010,19 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double 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) +bool QCustomPlot::saveBmp( const QString& fileName, int width, int height, double scale ) { - return saveRastered(fileName, width, height, scale, "BMP"); + 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. @@ -10680,9 +11035,9 @@ QSize QCustomPlot::minimumSizeHint() const } /*! \internal - + Returns a size hint that is the same as \ref minimumSizeHint. - + */ QSize QCustomPlot::sizeHint() const { @@ -10690,251 +11045,257 @@ QSize QCustomPlot::sizeHint() const } /*! \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) +void QCustomPlot::paintEvent( QPaintEvent* event ) { - Q_UNUSED(event); - QPainter painter(this); - painter.drawPixmap(0, 0, mPaintBuffer); + 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) +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 + 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) +void QCustomPlot::mouseDoubleClickEvent( QMouseEvent* event ) { - emit mouseDoubleClick(event); - + emit mouseDoubleClick( event ); + QVariant details; - QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &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); - + 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) + 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->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. + + // 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) +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) - + 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); + 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) +void QCustomPlot::mouseMoveEvent( QMouseEvent* event ) { - emit mouseMove(event); + emit mouseMove( event ); // call event of affected layout element: - if (mMouseEventElement) - mMouseEventElement->mouseMoveEvent(event); - - QWidget::mouseMoveEvent(event); + 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) +void QCustomPlot::mouseReleaseEvent( QMouseEvent* event ) { - emit mouseRelease(event); + emit mouseRelease( event ); bool doReplot = false; - - if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation + + if( ( mMousePressPos - event->pos() ).manhattanLength() < 5 ) // determine whether it was a click operation { - if (event->button() == Qt::LeftButton) + if( event->button() == Qt::LeftButton ) { // handle selection mechanism: QVariant details; - QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); + QCPLayerable* clickedLayerable = layerableAt( event->pos(), true, &details ); bool selectionStateChanged = false; - bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); + bool additive = + mInteractions.testFlag( QCP::iMultiSelect ) && event->modifiers().testFlag( mMultiSelectModifier ); // deselect all other layerables if not additive selection: - if (!additive) + if( !additive ) { - foreach (QCPLayer *layer, mLayers) + foreach( QCPLayer* layer, mLayers ) { - foreach (QCPLayerable *layerable, layer->children()) + foreach( QCPLayerable* layerable, layer->children() ) { - if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) + if( layerable != clickedLayerable && mInteractions.testFlag( layerable->selectionCategory() ) ) { bool selChanged = false; - layerable->deselectEvent(&selChanged); + layerable->deselectEvent( &selChanged ); selectionStateChanged |= selChanged; } } } } - if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) + if( clickedLayerable && mInteractions.testFlag( clickedLayerable->selectionCategory() ) ) { // a layerable was actually clicked, call its selectEvent: bool selChanged = false; - clickedLayerable->selectEvent(event, additive, details, &selChanged); + clickedLayerable->selectEvent( event, additive, details, &selChanged ); selectionStateChanged |= selChanged; } doReplot = true; - if (selectionStateChanged) + if( selectionStateChanged ) 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); + 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) + if( mMouseEventElement ) { - mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement->mouseReleaseEvent( event ); mMouseEventElement = 0; } - - if (doReplot || noAntialiasingOnDrag()) + + if( doReplot || noAntialiasingOnDrag() ) replot(); - - QWidget::mouseReleaseEvent(event); + + 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) +void QCustomPlot::wheelEvent( QWheelEvent* event ) { - emit mouseWheel(event); - + emit mouseWheel( event ); + // call event of affected layout element: - if (QCPLayoutElement *el = layoutElementAt(event->pos())) - el->wheelEvent(event); - - QWidget::wheelEvent(event); + 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) +void QCustomPlot::draw( QCPPainter* painter ) { // run through layout phases: - mPlotLayout->update(QCPLayoutElement::upPreparation); - mPlotLayout->update(QCPLayoutElement::upMargins); - mPlotLayout->update(QCPLayoutElement::upLayout); - + mPlotLayout->update( QCPLayoutElement::upPreparation ); + mPlotLayout->update( QCPLayoutElement::upMargins ); + mPlotLayout->update( QCPLayoutElement::upLayout ); + // draw viewport background pixmap: - drawBackground(painter); + drawBackground( painter ); // draw all layered objects (grid, axes, plottables, items, legend,...): - foreach (QCPLayer *layer, mLayers) + foreach( QCPLayer* layer, mLayers ) { - foreach (QCPLayerable *child, layer->children()) + foreach( QCPLayerable* child, layer->children() ) { - if (child->realVisibility()) + if( child->realVisibility() ) { painter->save(); - painter->setClipRect(child->clipRect().translated(0, -1)); - child->applyDefaultAntialiasingHint(painter); - child->draw(painter); + 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()) { @@ -10948,9 +11309,9 @@ void QCustomPlot::draw(QCPPainter *painter) } /*! \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 @@ -10958,79 +11319,82 @@ void QCustomPlot::draw(QCPPainter *painter) 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) +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( !mBackgroundPixmap.isNull() ) { - if (mBackgroundScaled) + 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 + 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())); + 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) +void QCustomPlot::axisRemoved( QCPAxis* axis ) { - if (xAxis == axis) + if( xAxis == axis ) xAxis = 0; - if (xAxis2 == axis) + if( xAxis2 == axis ) xAxis2 = 0; - if (yAxis == axis) + if( yAxis == axis ) yAxis = 0; - if (yAxis2 == axis) + 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) +void QCustomPlot::legendRemoved( QCPLegend* legend ) { - if (this->legend == 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; + for( int i = 0; i < mLayers.size(); ++i ) + mLayers.at( i )->mIndex = 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.) @@ -11041,27 +11405,28 @@ void QCustomPlot::updateLayerIndices() const 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 +QCPLayerable* QCustomPlot::layerableAt( const QPointF& pos, bool onlySelectable, QVariant* selectionDetails ) const { - for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) + 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) + 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()) + if( !layerables.at( i )->realVisibility() ) continue; QVariant details; - double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); - if (dist >= 0 && dist < minimumDistance) + double dist = layerables.at( i )->selectTest( pos, onlySelectable, &details ); + if( dist >= 0 && dist < minimumDistance ) { minimumDistance = dist; - minimumDistanceLayerable = layerables.at(i); - if (selectionDetails) *selectionDetails = details; + minimumDistanceLayerable = layerables.at( i ); + if( selectionDetails ) + *selectionDetails = details; } } - if (minimumDistance < selectionTolerance()) + if( minimumDistance < selectionTolerance() ) return minimumDistanceLayerable; } return 0; @@ -11072,66 +11437,78 @@ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, 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) +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); + 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) +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. + // 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) + if( width == 0 || height == 0 ) { newWidth = this->width(); newHeight = this->height(); - } else + } + else { newWidth = width; newHeight = height; } - int scaledWidth = qRound(scale*newWidth); - int scaledHeight = qRound(scale*newHeight); + 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 + 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()) + painter.begin( &result ); + if( painter.isActive() ) { QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter.setMode(QCPPainter::pmNoCaching); - if (!qFuzzyCompare(scale, 1.0)) + 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( 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) - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - setViewport(oldViewport); + if( mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush ) + painter.fillRect( mViewport, mBackgroundBrush ); + draw( &painter ); + setViewport( oldViewport ); painter.end(); - } else // might happen if pixmap has width or height zero + } + else // might happen if pixmap has width or height zero { qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; return QPixmap(); @@ -11141,53 +11518,57 @@ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) /*! 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 + + \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) +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. + // 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) + if( width == 0 || height == 0 ) { newWidth = this->width(); newHeight = this->height(); - } else + } + else { newWidth = width; newHeight = height; } - if (painter->isActive()) + if( painter->isActive() ) { QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter->setMode(QCPPainter::pmNoCaching); - // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill + setViewport( QRect( 0, 0, newWidth, newHeight ) ); + painter->setMode( QCPPainter::pmNoCaching ); + // warning: the following is different in toPixmap, because a solid background color is applied there via + // QPixmap::fill // here, we need to do this via QPainter::fillRect. - if (mBackgroundBrush.style() != Qt::NoBrush) - painter->fillRect(mViewport, mBackgroundBrush); - draw(painter); - setViewport(oldViewport); - } else + if( mBackgroundBrush.style() != Qt::NoBrush ) + 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 a \ref QCPColorMap::setGradient "setGradient" method which takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) @@ -11196,16 +11577,16 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) 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.: \code colorMap->setGradient(QCPColorGradient::gpHot); \endcode - + 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. @@ -11214,42 +11595,37 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) /*! 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) +QCPColorGradient::QCPColorGradient( GradientPreset preset ) + : mLevelCount( 350 ), mColorInterpolation( ciRGB ), mPeriodic( false ), mColorBufferInvalidated( true ) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); - loadPreset(preset); + mColorBuffer.fill( qRgb( 0, 0, 0 ), mLevelCount ); + loadPreset( preset ); } /* undocumented operator */ -bool QCPColorGradient::operator==(const QCPColorGradient &other) const +bool QCPColorGradient::operator==( const QCPColorGradient& other ) const { - return ((other.mLevelCount == this->mLevelCount) && - (other.mColorInterpolation == this->mColorInterpolation) && - (other.mPeriodic == this->mPeriodic) && - (other.mColorStops == this->mColorStops)); + 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) +void QCPColorGradient::setLevelCount( int n ) { - if (n < 2) + if( n < 2 ) { qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; n = 2; } - if (n != mLevelCount) + if( n != mLevelCount ) { mLevelCount = n; mColorBufferInvalidated = true; @@ -11260,13 +11636,13 @@ void QCPColorGradient::setLevelCount(int n) 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) +void QCPColorGradient::setColorStops( const QMap& colorStops ) { mColorStops = colorStops; mColorBufferInvalidated = true; @@ -11275,25 +11651,25 @@ void QCPColorGradient::setColorStops(const QMap &colorStops) /*! 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) +void QCPColorGradient::setColorStopAt( double position, const QColor& color ) { - mColorStops.insert(position, 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) +void QCPColorGradient::setColorInterpolation( QCPColorGradient::ColorInterpolation interpolation ) { - if (interpolation != mColorInterpolation) + if( interpolation != mColorInterpolation ) { mColorInterpolation = interpolation; mColorBufferInvalidated = true; @@ -11304,18 +11680,18 @@ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolatio 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) +void QCPColorGradient::setPeriodic( bool enabled ) { mPeriodic = enabled; } @@ -11326,226 +11702,237 @@ void QCPColorGradient::setPeriodic(bool enabled) 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) +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) + if( !data ) { qDebug() << Q_FUNC_INFO << "null pointer given as data"; return; } - if (!scanLine) + if( !scanLine ) { qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; return; } - if (mColorBufferInvalidated) + if( mColorBufferInvalidated ) updateColorBuffer(); - - if (!logarithmic) + + if( !logarithmic ) { - const double posToIndexFactor = mLevelCount/range.size(); - if (mPeriodic) + const double posToIndexFactor = mLevelCount / range.size(); + if( mPeriodic ) { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); + scanLine[i] = mColorBuffer.at( index ); } } - } else // logarithmic == true - { - if (mPeriodic) + else { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); + else if( index >= mLevelCount ) + index = mLevelCount - 1; + scanLine[i] = mColorBuffer.at( index ); + } + } + } + else // logarithmic == true + { + if( mPeriodic ) + { + for( int i = 0; i < n; ++i ) + { + int index = + (int)( qLn( data[dataIndexFactor * i] / range.lower ) / qLn( range.upper / range.lower ) * mLevelCount ) % + mLevelCount; + if( index < 0 ) + index += mLevelCount; + scanLine[i] = mColorBuffer.at( index ); + } + } + else + { + for( int i = 0; i < n; ++i ) + { + int index = qLn( data[dataIndexFactor * i] / range.lower ) / qLn( range.upper / range.lower ) * mLevelCount; + if( index < 0 ) + index = 0; + else if( index >= 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) +QRgb QCPColorGradient::color( double position, const QCPRange& range, bool logarithmic ) { // If you change something here, make sure to also adapt ::colorize() - if (mColorBufferInvalidated) + if( mColorBufferInvalidated ) updateColorBuffer(); int index = 0; - if (!logarithmic) - index = (position-range.lower)*mLevelCount/range.size(); + if( !logarithmic ) + index = ( position - range.lower ) * mLevelCount / range.size(); else - index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount; - if (mPeriodic) + index = qLn( position / range.lower ) / qLn( range.upper / range.lower ) * mLevelCount; + if( mPeriodic ) { index = index % mLevelCount; - if (index < 0) + if( index < 0 ) index += mLevelCount; - } else - { - if (index < 0) - index = 0; - else if (index >= mLevelCount) - index = mLevelCount-1; } - return mColorBuffer.at(index); + 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) +void QCPColorGradient::loadPreset( GradientPreset preset ) { clearColorStops(); - switch (preset) + switch( preset ) { case gpGrayscale: - setColorInterpolation(ciRGB); - setColorStopAt(0, Qt::black); - setColorStopAt(1, Qt::white); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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() @@ -11557,52 +11944,54 @@ void QCPColorGradient::clearColorStops() /*! 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); + QCPColorGradient result( *this ); result.clearColorStops(); - for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) - result.setColorStopAt(1.0-it.key(), it.value()); + 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) + 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 + double position = i * indexToPosFactor; + QMap::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 - 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 + } + 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) + 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()); + 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: @@ -11610,68 +11999,73 @@ void QCPColorGradient::updateColorBuffer() 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); + 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(); + 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) + } + else if( mColorStops.size() == 1 ) { - mColorBuffer.fill(mColorStops.constBegin().value().rgb()); - } else // mColorStops is empty, fill color buffer with black + mColorBuffer.fill( mColorStops.constBegin().value().rgb() ); + } + else // mColorStops is empty, fill color buffer with black { - mColorBuffer.fill(qRgb(0, 0, 0)); + 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.
@@ -11680,81 +12074,81 @@ void QCPColorGradient::updateColorBuffer() /* 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. */ @@ -11765,47 +12159,47 @@ void QCPColorGradient::updateColorBuffer() 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) +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) + 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); + 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 ); } } @@ -11813,34 +12207,35 @@ QCPAxisRect::~QCPAxisRect() { delete mInsetLayout; mInsetLayout = 0; - + QList axesList = axes(); - for (int i=0; i ax(mAxes.value(type)); - if (index >= 0 && index < ax.size()) + QList ax( mAxes.value( type ) ); + if( index >= 0 && index < ax.size() ) { - return ax.at(index); - } else + return ax.at( index ); + } + else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return 0; @@ -11849,35 +12244,35 @@ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const /*! 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 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); + 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()) + QHashIterator > it( mAxes ); + while( it.hasNext() ) { it.next(); result << it.value(); @@ -11887,72 +12282,75 @@ QList QCPAxisRect::axes() const /*! Adds a new axis to the axis rect side specified with \a type, and returns it. - + 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 initialized to \ref QCPLineEnding::esHalfBar. - + \see addAxes, setupFullAxesBox */ -QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type) +QCPAxis* QCPAxisRect::addAxis( QCPAxis::AxisType type ) { - QCPAxis *newAxis = new QCPAxis(this, type); - if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset + QCPAxis* newAxis = new QCPAxis( this, type ); + 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)); + 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); + 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 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); + 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) +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()) + // 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)) + 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); + 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); + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast( axis ); return false; } @@ -11960,7 +12358,7 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) 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) @@ -11976,151 +12374,152 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) \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) +void QCPAxisRect::setupFullAxesBox( bool connectRanges ) { QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - if (axisCount(QCPAxis::atBottom) == 0) - xAxis = addAxis(QCPAxis::atBottom); + 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()); + xAxis = axis( QCPAxis::atBottom ); - 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) + 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))); + 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) + for( int i = 0; i < mParentPlot->mPlottables.size(); ++i ) { - if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mPlottables.at(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) + for( int i = 0; i < mParentPlot->mGraphs.size(); ++i ) { - if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mGraphs.at(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 +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) + for( int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId ) { - if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) + if( mParentPlot->mItems.at( itemId )->clipAxisRect() == this ) { - result.append(mParentPlot->mItems.at(itemId)); + result.append( mParentPlot->mItems.at( itemId ) ); continue; } - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posId positions = mParentPlot->mItems.at( itemId )->positions(); + for( int posId = 0; posId < positions.size(); ++posId ) { - if (positions.at(posId)->axisRect() == this || - positions.at(posId)->keyAxis()->axisRect() == this || - positions.at(posId)->valueAxis()->axisRect() == this) + if( positions.at( posId )->axisRect() == this || positions.at( posId )->keyAxis()->axisRect() == this || + positions.at( posId )->valueAxis()->axisRect() == this ) { - result.append(mParentPlot->mItems.at(itemId)); + result.append( mParentPlot->mItems.at( itemId ) ); break; } } @@ -12131,59 +12530,61 @@ QList QCPAxisRect::items() const /*! 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) +void QCPAxisRect::update( UpdatePhase phase ) { - QCPLayoutElement::update(phase); - - switch (phase) + QCPLayoutElement::update( phase ); + + switch( phase ) { case upPreparation: { QList allAxes = axes(); - for (int i=0; isetupTickVectors(); + for( int i = 0; i < allAxes.size(); ++i ) + allAxes.at( i )->setupTickVectors(); break; } case upLayout: { - mInsetLayout->setOuterRect(rect()); + mInsetLayout->setOuterRect( rect() ); break; } - default: break; + default: + break; } - - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): - mInsetLayout->update(phase); + + // 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 QCPAxisRect::elements( bool recursive ) const { QList result; - if (mInsetLayout) + if( mInsetLayout ) { result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); + if( recursive ) + result << mInsetLayout->elements( recursive ); } return result; } /* inherits documentation from base class */ -void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const +void QCPAxisRect::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - painter->setAntialiasing(false); + painter->setAntialiasing( false ); } /* inherits documentation from base class */ -void QCPAxisRect::draw(QCPPainter *painter) +void QCPAxisRect::draw( QCPPainter* painter ) { - drawBackground(painter); + drawBackground( painter ); } /*! @@ -12198,17 +12599,17 @@ void QCPAxisRect::draw(QCPPainter *painter) 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) +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. @@ -12217,22 +12618,22 @@ void QCPAxisRect::setBackground(const QPixmap &pm) 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) +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) +void QCPAxisRect::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode ) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); @@ -12244,13 +12645,13 @@ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioM 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) +void QCPAxisRect::setBackgroundScaled( bool scaled ) { mBackgroundScaled = scaled; } @@ -12260,39 +12661,39 @@ void QCPAxisRect::setBackgroundScaled(bool scaled) 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) +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) +QCPAxis* QCPAxisRect::rangeDragAxis( Qt::Orientation orientation ) { - return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); + 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) +QCPAxis* QCPAxisRect::rangeZoomAxis( Qt::Orientation orientation ) { - return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); + 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) +double QCPAxisRect::rangeZoomFactor( Qt::Orientation orientation ) { - return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); + return ( orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert ); } /*! @@ -12301,17 +12702,17 @@ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) \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, setNoAntialiasingOnDrag */ -void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) +void QCPAxisRect::setRangeDrag( Qt::Orientations orientations ) { mRangeDrag = orientations; } @@ -12325,13 +12726,13 @@ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) 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) +void QCPAxisRect::setRangeZoom( Qt::Orientations orientations ) { mRangeZoom = orientations; } @@ -12339,10 +12740,10 @@ void QCPAxisRect::setRangeZoom(Qt::Orientations 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) +void QCPAxisRect::setRangeDragAxes( QCPAxis* horizontal, QCPAxis* vertical ) { mRangeDragHorzAxis = horizontal; mRangeDragVertAxis = vertical; @@ -12352,10 +12753,10 @@ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *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) +void QCPAxisRect::setRangeZoomAxes( QCPAxis* horizontal, QCPAxis* vertical ) { mRangeZoomHorzAxis = horizontal; mRangeZoomVertAxis = vertical; @@ -12371,30 +12772,30 @@ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) 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) +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) +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 @@ -12402,233 +12803,245 @@ void QCPAxisRect::setRangeZoomFactor(double factor) 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) +void QCPAxisRect::drawBackground( QCPPainter* painter ) { // draw background fill: - if (mBackgroundBrush != Qt::NoBrush) - painter->fillRect(mRect, mBackgroundBrush); - + if( mBackgroundBrush != Qt::NoBrush ) + painter->fillRect( mRect, mBackgroundBrush ); + // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) + if( !mBackgroundPixmap.isNull() ) { - if (mBackgroundScaled) + 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(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else + 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(), mScaledBackgroundPixmap, + QRect( 0, 0, mRect.width(), mRect.height() ) & mScaledBackgroundPixmap.rect() ); + } + else { - painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + painter->drawPixmap( mRect.topLeft(), 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) +void QCPAxisRect::updateAxesOffset( QCPAxis::AxisType type ) { - const QList axesList = mAxes.value(type); - if (axesList.isEmpty()) + 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; ivisible(); // 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; i < axesList.size(); ++i ) { - int offset = axesList.at(i-1)->offset() + 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) + int offset = axesList.at( i - 1 )->offset() + 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(); + if( !isFirstVisible ) + offset += axesList.at( i )->tickLengthIn(); isFirstVisible = false; } - axesList.at(i)->setOffset(offset); + axesList.at( i )->setOffset( offset ); } } /* inherits documentation from base class */ -int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) +int QCPAxisRect::calculateAutoMargin( QCP::MarginSide side ) { - if (!mAutoMargins.testFlag(side)) + if( !mAutoMargins.testFlag( side ) ) qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; - - updateAxesOffset(QCPAxis::marginSideToAxisType(side)); - + + 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) + 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) +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) + 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()) + if( mParentPlot->noAntialiasingOnDrag() ) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + if( mParentPlot->interactions().testFlag( QCP::iRangeDrag ) ) { - if (mRangeDragHorzAxis) + if( mRangeDragHorzAxis ) mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); - if (mRangeDragVertAxis) + 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) +void QCPAxisRect::mouseMoveEvent( QMouseEvent* event ) { // Mouse range dragging interaction: - if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + if( mDragging && mParentPlot->interactions().testFlag( QCP::iRangeDrag ) ) { - if (mRangeDrag.testFlag(Qt::Horizontal)) + if( mRangeDrag.testFlag( Qt::Horizontal ) ) { - if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) + if( QCPAxis* rangeDragHorzAxis = mRangeDragHorzAxis.data() ) { - if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) + 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 ); + } + 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); + 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( mRangeDrag.testFlag( Qt::Vertical ) ) { - if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) + if( QCPAxis* rangeDragVertAxis = mRangeDragVertAxis.data() ) { - if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) + 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 ); + } + 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); + 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( mRangeDrag != 0 ) // if either vertical or horizontal drag was enabled, do a replot { - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); + if( mParentPlot->noAntialiasingOnDrag() ) + mParentPlot->setNotAntialiasedElements( QCP::aeAll ); mParentPlot->replot(); } } } /* inherits documentation from base class */ -void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) +void QCPAxisRect::mouseReleaseEvent( QMouseEvent* event ) { - Q_UNUSED(event) + Q_UNUSED( event ) mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) + if( mParentPlot->noAntialiasingOnDrag() ) { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + 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) +void QCPAxisRect::wheelEvent( QWheelEvent* event ) { // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) + if( mParentPlot->interactions().testFlag( QCP::iRangeZoom ) ) { - if (mRangeZoom != 0) + if( mRangeZoom != 0 ) { double factor; - double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - if (mRangeZoom.testFlag(Qt::Horizontal)) + double wheelSteps = event->delta() / 120.0; // a single step delta is +/-120 usually + if( mRangeZoom.testFlag( Qt::Horizontal ) ) { - factor = pow(mRangeZoomFactorHorz, wheelSteps); - if (mRangeZoomHorzAxis.data()) - mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); + factor = pow( mRangeZoomFactorHorz, wheelSteps ); + if( mRangeZoomHorzAxis.data() ) + mRangeZoomHorzAxis.data()->scaleRange( factor, mRangeZoomHorzAxis.data()->pixelToCoord( event->pos().x() ) ); } - if (mRangeZoom.testFlag(Qt::Vertical)) + if( mRangeZoom.testFlag( Qt::Vertical ) ) { - factor = pow(mRangeZoomFactorVert, wheelSteps); - if (mRangeZoomVertAxis.data()) - mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); + factor = pow( 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: @@ -12636,7 +13049,8 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) - +
A 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.The generic font of the item. You should use this font for all or at least the most prominent text of the + item.
*/ @@ -12644,7 +13058,7 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /* 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. */ @@ -12655,36 +13069,36 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) 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) +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("legend"); - setMargins(QMargins(8, 2, 8, 2)); + setLayer( "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) +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) +void QCPAbstractLegendItem::setTextColor( const QColor& color ) { mTextColor = color; } @@ -12692,10 +13106,10 @@ void QCPAbstractLegendItem::setTextColor(const QColor &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) +void QCPAbstractLegendItem::setSelectedFont( const QFont& font ) { mSelectedFont = font; } @@ -12703,63 +13117,64 @@ void QCPAbstractLegendItem::setSelectedFont(const QFont &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) +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) +void QCPAbstractLegendItem::setSelectable( bool selectable ) { - if (mSelectable != selectable) + if( mSelectable != selectable ) { mSelectable = selectable; - emit selectableChanged(mSelectable); + 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) +void QCPAbstractLegendItem::setSelected( bool selected ) { - if (mSelected != selected) + if( mSelected != selected ) { mSelected = selected; - emit selectionChanged(mSelected); + emit selectionChanged( mSelected ); } } /* inherits documentation from base class */ -double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +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))) + Q_UNUSED( details ) + if( !mParentPlot ) return -1; - - if (mRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; + 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 +void QCPAbstractLegendItem::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); + applyAntialiasingHint( painter, mAntialiased, QCP::aeLegendItems ); } /* inherits documentation from base class */ @@ -12769,27 +13184,30 @@ QRect QCPAbstractLegendItem::clipRect() const } /* inherits documentation from base class */ -void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +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)) + Q_UNUSED( event ) + Q_UNUSED( details ) + if( mSelectable && mParentLegend->selectableParts().testFlag( QCPLegend::spItems ) ) { bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) + setSelected( additive ? !mSelected : true ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ -void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) +void QCPAbstractLegendItem::deselectEvent( bool* selectionStateChanged ) { - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) + if( mSelectable && mParentLegend->selectableParts().testFlag( QCPLegend::spItems ) ) { bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) + setSelected( false ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } @@ -12800,13 +13218,13 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! \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 @@ -12816,7 +13234,7 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) 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 @@ -12825,20 +13243,19 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! 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) +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. */ @@ -12848,7 +13265,7 @@ QPen QCPPlottableLegendItem::getIconBorderPen() const } /*! \internal - + Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ @@ -12858,7 +13275,7 @@ QColor QCPPlottableLegendItem::getTextColor() const } /*! \internal - + Returns the font that shall be used to draw text, taking into account the selection state of this item. */ @@ -12868,54 +13285,61 @@ QFont QCPPlottableLegendItem::getFont() const } /*! \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) +void QCPPlottableLegendItem::draw( QCPPainter* painter ) { - if (!mPlottable) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); + 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()); + 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->setClipRect( iconRect, Qt::IntersectClip ); + mPlottable->drawLegendIcon( painter, iconRect ); painter->restore(); // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) + if( getIconBorderPen().style() != Qt::NoPen ) { - painter->setPen(getIconBorderPen()); - painter->setBrush(Qt::NoBrush); - painter->drawRect(iconRect); + 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); + if( !mPlottable ) + return QSize(); + QSize result( 0, 0 ); QRect textRect; - QFontMetrics fontMetrics(getFont()); + 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()); + 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 //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -12924,12 +13348,12 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const \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 @@ -12949,7 +13373,7 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. - + \see setSelectedParts, setSelectableParts */ @@ -12957,38 +13381,38 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /*! 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); + 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 (mParentPlot) - mParentPlot->legendRemoved(this); + if( mParentPlot ) + mParentPlot->legendRemoved( this ); } /* no doc for getter, see setSelectedParts */ @@ -12996,15 +13420,15 @@ 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()) + if( item( i ) && item( i )->selected() ) { hasSelectedItems = true; break; } } - if (hasSelectedItems) + if( hasSelectedItems ) return mSelectedParts | spItems; else return mSelectedParts & ~spItems; @@ -13013,7 +13437,7 @@ QCPLegend::SelectableParts QCPLegend::selectedParts() const /*! Sets the pen, the border of the entire legend is drawn with. */ -void QCPLegend::setBorderPen(const QPen &pen) +void QCPLegend::setBorderPen( const QPen& pen ) { mBorderPen = pen; } @@ -13021,7 +13445,7 @@ void QCPLegend::setBorderPen(const QPen &pen) /*! Sets the brush of the legend background. */ -void QCPLegend::setBrush(const QBrush &brush) +void QCPLegend::setBrush( const QBrush& brush ) { mBrush = brush; } @@ -13030,18 +13454,18 @@ void QCPLegend::setBrush(const QBrush &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) +void QCPLegend::setFont( const QFont& font ) { mFont = font; - for (int i=0; isetFont(mFont); + if( item( i ) ) + item( i )->setFont( mFont ); } } @@ -13049,18 +13473,18 @@ void QCPLegend::setFont(const QFont &font) 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) +void QCPLegend::setTextColor( const QColor& color ) { mTextColor = color; - for (int i=0; isetTextColor(color); + if( item( i ) ) + item( i )->setTextColor( color ); } } @@ -13068,17 +13492,17 @@ void QCPLegend::setTextColor(const QColor &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) +void QCPLegend::setIconSize( const QSize& size ) { mIconSize = size; } /*! \overload */ -void QCPLegend::setIconSize(int width, int height) +void QCPLegend::setIconSize( int width, int height ) { - mIconSize.setWidth(width); - mIconSize.setHeight(height); + mIconSize.setWidth( width ); + mIconSize.setHeight( height ); } /*! @@ -13086,7 +13510,7 @@ void QCPLegend::setIconSize(int width, int height) 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) +void QCPLegend::setIconTextPadding( int padding ) { mIconTextPadding = padding; } @@ -13094,10 +13518,10 @@ void QCPLegend::setIconTextPadding(int 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) +void QCPLegend::setIconBorderPen( const QPen& pen ) { mIconBorderPen = pen; } @@ -13105,19 +13529,19 @@ void QCPLegend::setIconBorderPen(const QPen &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) +void QCPLegend::setSelectableParts( const SelectableParts& selectable ) { - if (mSelectableParts != selectable) + if( mSelectableParts != selectable ) { mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); + emit selectableChanged( mSelectableParts ); } } @@ -13125,45 +13549,47 @@ void QCPLegend::setSelectableParts(const SelectableParts &selectable) 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) +void QCPLegend::setSelectedParts( const SelectableParts& selected ) { SelectableParts newSelected = selected; - mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed - if (mSelectedParts != newSelected) + if( mSelectedParts != newSelected ) { - if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) + 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 + if( mSelectedParts.testFlag( spItems ) && + !newSelected.testFlag( spItems ) ) // spItems flag was unset, so clear item selection { - for (int i=0; isetSelected(false); + if( item( i ) ) + item( i )->setSelected( false ); } } mSelectedParts = newSelected; - emit selectionChanged(mSelectedParts); + emit selectionChanged( mSelectedParts ); } } @@ -13173,7 +13599,7 @@ void QCPLegend::setSelectedParts(const SelectableParts &selected) \see setSelectedParts, setSelectableParts, setSelectedBrush */ -void QCPLegend::setSelectedBorderPen(const QPen &pen) +void QCPLegend::setSelectedBorderPen( const QPen& pen ) { mSelectedBorderPen = pen; } @@ -13183,7 +13609,7 @@ void QCPLegend::setSelectedBorderPen(const QPen &pen) \see setSelectedParts, setSelectableParts, setSelectedFont */ -void QCPLegend::setSelectedIconBorderPen(const QPen &pen) +void QCPLegend::setSelectedIconBorderPen( const QPen& pen ) { mSelectedIconBorderPen = pen; } @@ -13194,68 +13620,68 @@ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) \see setSelectedParts, setSelectableParts, setSelectedBorderPen */ -void QCPLegend::setSelectedBrush(const QBrush &brush) +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) +void QCPLegend::setSelectedFont( const QFont& font ) { mSelectedFont = font; - for (int i=0; isetSelectedFont(font); + if( item( i ) ) + item( i )->setSelectedFont( 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) +void QCPLegend::setSelectedTextColor( const QColor& color ) { mSelectedTextColor = color; - for (int i=0; isetSelectedTextColor(color); + if( item( i ) ) + item( i )->setSelectedTextColor( color ); } } /*! Returns the item with index \a i. - + \see itemCount */ -QCPAbstractLegendItem *QCPLegend::item(int index) const +QCPAbstractLegendItem* QCPLegend::item( int index ) const { - return qobject_cast(elementAt(index)); + 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 +QCPPlottableLegendItem* QCPLegend::itemWithPlottable( const QCPAbstractPlottable* plottable ) const { - for (int i=0; i(item(i))) + if( QCPPlottableLegendItem* pli = qobject_cast( item( i ) ) ) { - if (pli->plottable() == plottable) + if( pli->plottable() == plottable ) return pli; } } @@ -13274,40 +13700,42 @@ int QCPLegend::itemCount() const /*! Returns whether the legend contains \a itm. */ -bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const +bool QCPLegend::hasItem( QCPAbstractLegendItem* item ) const { - for (int i=0; iitem(i)) - return true; + if( item == this->item( i ) ) + return true; } return false; } /*! - Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + 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 +bool QCPLegend::hasItemWithPlottable( const QCPAbstractPlottable* plottable ) const { - return itemWithPlottable(plottable); + 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) +bool QCPLegend::addItem( QCPAbstractLegendItem* item ) { - if (!hasItem(item)) + if( !hasItem( item ) ) { - return addElement(rowCount(), 0, item); - } else + return addElement( rowCount(), 0, item ); + } + else return false; } @@ -13315,31 +13743,32 @@ bool QCPLegend::addItem(QCPAbstractLegendItem *item) Removes the item with index \a index from the legend. Returns true, if successful. - + \see itemCount, clearItems */ -bool QCPLegend::removeItem(int index) +bool QCPLegend::removeItem( int index ) { - if (QCPAbstractLegendItem *ali = item(index)) + if( QCPAbstractLegendItem* ali = item( index ) ) { - bool success = remove(ali); + bool success = remove( ali ); simplify(); return success; - } else + } + else return false; } /*! \overload - + Removes \a item from the legend. Returns true, if successful. - + \see clearItems */ -bool QCPLegend::removeItem(QCPAbstractLegendItem *item) +bool QCPLegend::removeItem( QCPAbstractLegendItem* item ) { - bool success = remove(item); + bool success = remove( item ); simplify(); return success; } @@ -13349,25 +13778,25 @@ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) */ void QCPLegend::clearItems() { - for (int i=itemCount()-1; i>=0; --i) - removeItem(i); + 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 QCPLegend::selectedItems() const { QList result; - for (int i=0; iselected()) - result.append(ali); + if( ali->selected() ) + result.append( ali ); } } return result; @@ -13379,89 +13808,94 @@ QList QCPLegend::selectedItems() const 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 +void QCPLegend::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); + 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; + 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; + 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) +void QCPLegend::draw( QCPPainter* painter ) { // draw background rect: - painter->setBrush(getBrush()); - painter->setPen(getBorderPen()); - painter->drawRect(mOuterRect); + 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 +double QCPLegend::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - if (!mParentPlot) return -1; - if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + if( !mParentPlot ) return -1; - - if (mOuterRect.contains(pos.toPoint())) + if( onlySelectable && !mSelectableParts.testFlag( spLegendBox ) ) + return -1; + + if( mOuterRect.contains( pos.toPoint() ) ) { - if (details) details->setValue(spLegendBox); - return mParentPlot->selectionTolerance()*0.99; + 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) +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)) + 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) + 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) +void QCPLegend::deselectEvent( bool* selectionStateChanged ) { - mSelectedParts = selectedParts(); // in case item selection has changed - if (mSelectableParts.testFlag(spLegendBox)) + mSelectedParts = selectedParts(); // in case item selection has changed + if( mSelectableParts.testFlag( spLegendBox ) ) { SelectableParts selBefore = mSelectedParts; - setSelectedParts(selectedParts() & ~spLegendBox); - if (selectionStateChanged) + setSelectedParts( selectedParts() & ~spLegendBox ); + if( selectionStateChanged ) *selectionStateChanged = mSelectedParts != selBefore; } } @@ -13479,28 +13913,27 @@ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const } /* inherits documentation from base class */ -void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) +void QCPLegend::parentPlotInitialized( QCustomPlot* parentPlot ) { - Q_UNUSED(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: \code customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title")); \endcode - + 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 @@ -13510,10 +13943,10 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* 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 */ @@ -13521,91 +13954,91 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /*! 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("sans serif", 13*1.5, QFont::Bold)), - mTextColor(Qt::black), - mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) +QCPPlotTitle::QCPPlotTitle( QCustomPlot* parentPlot ) + : QCPLayoutElement( parentPlot ), + mFont( QFont( "sans serif", 13 * 1.5, QFont::Bold ) ), + mTextColor( Qt::black ), + mSelectedFont( QFont( "sans serif", 13 * 1.6, QFont::Bold ) ), + mSelectedTextColor( Qt::blue ), + mSelectable( false ), + mSelected( false ) { - if (parentPlot) + 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); + 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)); + 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) +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("axes"); - setMargins(QMargins(5, 5, 5, 0)); + setLayer( "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) +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) +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) +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) +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) +void QCPPlotTitle::setSelectedTextColor( const QColor& color ) { mSelectedTextColor = color; } @@ -13616,50 +14049,50 @@ void QCPPlotTitle::setSelectedTextColor(const QColor &color) 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) +void QCPPlotTitle::setSelectable( bool selectable ) { - if (mSelectable != selectable) + if( mSelectable != selectable ) { mSelectable = selectable; - emit selectableChanged(mSelectable); + 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) +void QCPPlotTitle::setSelected( bool selected ) { - if (mSelected != selected) + if( mSelected != selected ) { mSelected = selected; - emit selectionChanged(mSelected); + emit selectionChanged( mSelected ); } } /* inherits documentation from base class */ -void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const +void QCPPlotTitle::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); + applyAntialiasingHint( painter, mAntialiased, QCP::aeNone ); } /* inherits documentation from base class */ -void QCPPlotTitle::draw(QCPPainter *painter) +void QCPPlotTitle::draw( QCPPainter* painter ) { - painter->setFont(mainFont()); - painter->setPen(QPen(mainTextColor())); - painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); + 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(); + 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; @@ -13668,54 +14101,57 @@ QSize QCPPlotTitle::minimumSizeHint() const /* inherits documentation from base class */ QSize QCPPlotTitle::maximumSizeHint() const { - QFontMetrics metrics(mFont); - QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + 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); + result.setWidth( QWIDGETSIZE_MAX ); return result; } /* inherits documentation from base class */ -void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +void QCPPlotTitle::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) + Q_UNUSED( event ) + Q_UNUSED( details ) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) + setSelected( additive ? !mSelected : true ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ -void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) +void QCPPlotTitle::deselectEvent( bool* selectionStateChanged ) { - if (mSelectable) + if( mSelectable ) { bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) + setSelected( false ); + if( selectionStateChanged ) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ -double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPPlotTitle::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - if (mTextBoundingRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; + + 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. */ @@ -13725,7 +14161,7 @@ QFont QCPPlotTitle::mainFont() const } /*! \internal - + Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ @@ -13734,34 +14170,33 @@ 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 \code colorScale->axis()->setAutoTickCount(3); \endcode - + Placing a color scale next to the main axis rect works like with any other layout element: \code QCPColorScale *colorScale = new QCPColorScale(customPlot); @@ -13771,7 +14206,7 @@ QColor QCPPlotTitle::mainTextColor() const 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: \code @@ -13779,7 +14214,7 @@ QColor QCPPlotTitle::mainTextColor() const colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group); customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group); \endcode - + 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 @@ -13791,14 +14226,14 @@ QColor QCPPlotTitle::mainTextColor() const /* 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. */ @@ -13807,23 +14242,23 @@ QColor QCPPlotTitle::mainTextColor() const /* 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 */ @@ -13832,16 +14267,18 @@ QColor QCPPlotTitle::mainTextColor() const /*! 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)) +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)); + 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() @@ -13852,149 +14289,157 @@ QCPColorScale::~QCPColorScale() /* undocumented getter */ QString QCPColorScale::label() const { - if (!mColorAxis) + if( !mColorAxis ) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return QString(); } - + return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { - if (!mAxisRect) + 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); + + 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) + 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); + + 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) +void QCPColorScale::setType( QCPAxis::AxisType type ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - if (mType != type) + if( mType != type ) { mType = type; - QCPRange rangeTransfer(0, 6); + QCPRange rangeTransfer( 0, 6 ); double logBaseTransfer = 10; QString labelTransfer; // revert some settings on old axis: - if (mColorAxis) + if( mColorAxis ) { rangeTransfer = mColorAxis.data()->range(); labelTransfer = mColorAxis.data()->label(); logBaseTransfer = mColorAxis.data()->scaleLogBase(); - mColorAxis.data()->setLabel(""); - disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + mColorAxis.data()->setLabel( "" ); + disconnect( mColorAxis.data(), SIGNAL( rangeChanged( QCPRange ) ), this, SLOT( setDataRange( QCPRange ) ) ); + disconnect( mColorAxis.data(), SIGNAL( scaleTypeChanged( QCPAxis::ScaleType ) ), this, + SLOT( setDataScaleType( QCPAxis::ScaleType ) ) ); } - foreach (QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop) + foreach( QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight + << QCPAxis::atBottom << QCPAxis::atTop ) { - mAxisRect.data()->axis(atype)->setTicks(atype == mType); - mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + mAxisRect.data()->axis( atype )->setTicks( atype == mType ); + mAxisRect.data()->axis( atype )->setTickLabels( atype == mType ); } // set new mColorAxis pointer: - mColorAxis = mAxisRect.data()->axis(mType); + 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); + 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) +void QCPColorScale::setDataRange( const QCPRange& dataRange ) { - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + if( mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper ) { mDataRange = dataRange; - if (mColorAxis) - mColorAxis.data()->setRange(mDataRange); - emit dataRangeChanged(mDataRange); + 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) +void QCPColorScale::setDataScaleType( QCPAxis::ScaleType scaleType ) { - if (mDataScaleType != scaleType) + if( mDataScaleType != scaleType ) { mDataScaleType = scaleType; - if (mColorAxis) - mColorAxis.data()->setScaleType(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - emit dataScaleTypeChanged(mDataScaleType); + 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) +void QCPColorScale::setGradient( const QCPColorGradient& gradient ) { - if (mGradient != gradient) + if( mGradient != gradient ) { mGradient = gradient; - if (mAxisRect) + if( mAxisRect ) mAxisRect.data()->mGradientImageInvalidated = true; - emit gradientChanged(mGradient); + emit gradientChanged( mGradient ); } } @@ -14002,64 +14447,64 @@ void QCPColorScale::setGradient(const QCPColorGradient &gradient) 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) +void QCPColorScale::setLabel( const QString& str ) { - if (!mColorAxis) + if( !mColorAxis ) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return; } - - mColorAxis.data()->setLabel(str); + + 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) +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) +void QCPColorScale::setRangeDrag( bool enabled ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - - if (enabled) - mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + + if( enabled ) + mAxisRect.data()->setRangeDrag( QCPAxis::orientation( mType ) ); else - mAxisRect.data()->setRangeDrag(0); + 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) +void QCPColorScale::setRangeZoom( bool enabled ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - - if (enabled) - mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + + if( enabled ) + mAxisRect.data()->setRangeZoom( QCPAxis::orientation( mType ) ); else - mAxisRect.data()->setRangeZoom(0); + mAxisRect.data()->setRangeZoom( 0 ); } /*! @@ -14068,11 +14513,11 @@ void QCPColorScale::setRangeZoom(bool enabled) QList QCPColorScale::colorMaps() const { QList result; - for (int i=0; iplottableCount(); ++i) + for( int i = 0; i < mParentPlot->plottableCount(); ++i ) { - if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) - if (cm->colorScale() == this) - result.append(cm); + if( QCPColorMap* cm = qobject_cast( mParentPlot->plottable( i ) ) ) + if( cm->colorScale() == this ) + result.append( cm ); } return result; } @@ -14080,152 +14525,167 @@ QList QCPColorScale::colorMaps() const /*! 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) +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) + if( !maps.at( i )->realVisibility() && onlyVisibleMaps ) continue; QCPRange mapRange; - if (maps.at(i)->colorScale() == this) + if( maps.at( i )->colorScale() == this ) { bool currentFoundRange = true; - mapRange = maps.at(i)->data()->dataBounds(); - if (sign == 1) + 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) + if( mapRange.lower <= 0 && mapRange.upper > 0 ) + mapRange.lower = mapRange.upper * 1e-3; + else if( mapRange.lower <= 0 && mapRange.upper <= 0 ) currentFoundRange = false; } - if (currentFoundRange) + else if( sign == -1 ) { - if (!haveRange) + 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); + newRange.expand( mapRange ); haveRange = true; } } } - if (haveRange) + 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 + 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) + 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 - 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); + newRange.lower = center / qSqrt( mDataRange.upper / mDataRange.lower ); + newRange.upper = center * qSqrt( mDataRange.upper / mDataRange.lower ); } } - setDataRange(newRange); + setDataRange( newRange ); } } /* inherits documentation from base class */ -void QCPColorScale::update(UpdatePhase phase) +void QCPColorScale::update( UpdatePhase phase ) { - QCPLayoutElement::update(phase); - if (!mAxisRect) + QCPLayoutElement::update( phase ); + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - - mAxisRect.data()->update(phase); - - switch (phase) + + mAxisRect.data()->update( phase ); + + switch( phase ) { case upMargins: { - if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) + 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( 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); + 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()); + mAxisRect.data()->setOuterRect( rect() ); break; } - default: break; + default: + break; } } /* inherits documentation from base class */ -void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const +void QCPColorScale::applyDefaultAntialiasingHint( QCPPainter* painter ) const { - painter->setAntialiasing(false); + painter->setAntialiasing( false ); } /* inherits documentation from base class */ -void QCPColorScale::mousePressEvent(QMouseEvent *event) +void QCPColorScale::mousePressEvent( QMouseEvent* event ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - mAxisRect.data()->mousePressEvent(event); + mAxisRect.data()->mousePressEvent( event ); } /* inherits documentation from base class */ -void QCPColorScale::mouseMoveEvent(QMouseEvent *event) +void QCPColorScale::mouseMoveEvent( QMouseEvent* event ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - mAxisRect.data()->mouseMoveEvent(event); + mAxisRect.data()->mouseMoveEvent( event ); } /* inherits documentation from base class */ -void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) +void QCPColorScale::mouseReleaseEvent( QMouseEvent* event ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - mAxisRect.data()->mouseReleaseEvent(event); + mAxisRect.data()->mouseReleaseEvent( event ); } /* inherits documentation from base class */ -void QCPColorScale::wheelEvent(QWheelEvent *event) +void QCPColorScale::wheelEvent( QWheelEvent* event ) { - if (!mAxisRect) + if( !mAxisRect ) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } - mAxisRect.data()->wheelEvent(event); + mAxisRect.data()->wheelEvent( event ); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -14236,67 +14696,80 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) \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) +QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate( QCPColorScale* parentColorScale ) + : QCPAxisRect( parentColorScale->parentPlot(), true ), + mParentColorScale( parentColorScale ), + mGradientImageInvalidated( true ) { - setParentLayerable(parentColorScale); - setMinimumMargins(QMargins(0, 0, 0, 0)); - foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + setParentLayerable( parentColorScale ); + setMinimumMargins( QMargins( 0, 0, 0, 0 ) ); + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + << QCPAxis::atRight ) { - 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))); + 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))); - + 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, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); + connect( parentColorScale, SIGNAL( layerChanged( QCPLayer* ) ), this, SLOT( setLayer( QCPLayer* ) ) ); + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + << QCPAxis::atRight ) + 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) +void QCPColorScaleAxisRectPrivate::draw( QCPPainter* painter ) { - if (mGradientImageInvalidated) + if( mGradientImageInvalidated ) updateGradientImage(); - + bool mirrorHorz = false; bool mirrorVert = false; - if (mParentColorScale->mColorAxis) + 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); + 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(), mGradientImage.mirrored(mirrorHorz, mirrorVert)); - QCPAxisRect::draw(painter); + + painter->drawImage( rect(), mGradientImage.mirrored( mirrorHorz, mirrorVert ) ); + QCPAxisRect::draw( painter ); } /*! \internal @@ -14306,35 +14779,36 @@ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { - if (rect().isEmpty()) + if( rect().isEmpty() ) return; - + int n = mParentColorScale->mGradient.levelCount(); int w, h; - QVector data(n); - for (int i=0; i data( n ); + for( int i = 0; i < n; ++i ) data[i] = i; - if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) + if( mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop ) { w = n; h = rect().height(); - mGradientImage = QImage(w, h, QImage::Format_RGB32); + 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 ) ) ); + mParentColorScale->mGradient.colorize( data.constData(), QCPRange( 0, n - 1 ), pixels.first(), n ); + for( int y = 1; y < h; ++y ) + memcpy( pixels.at( y ), pixels.first(), n * sizeof( QRgb ) ); + } + else { w = rect().width(); h = n; - mGradientImage = QImage(w, h, QImage::Format_RGB32); - for (int y=0; y(mGradientImage.scanLine(y)); - const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); - for (int x=0; x( mGradientImage.scanLine( y ) ); + const QRgb lineColor = mParentColorScale->mGradient.color( data[h - 1 - y], QCPRange( 0, n - 1 ) ); + for( int x = 0; x < w; ++x ) pixels[x] = lineColor; } } @@ -14346,21 +14820,22 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() This slot is connected to the selectionChanged signals of the four axes in the constructor. It synchronizes the selection state of the axes. */ -void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts) +void QCPColorScaleAxisRectPrivate::axisSelectionChanged( QCPAxis::SelectableParts selectedParts ) { // axis bases of four axes shall always (de-)selected synchronously: - foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + << QCPAxis::atRight ) { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) + if( QCPAxis* senderAxis = qobject_cast( sender() ) ) + if( senderAxis->axisType() == type ) continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + + if( axis( type )->selectableParts().testFlag( QCPAxis::spAxis ) ) { - if (selectedParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + if( selectedParts.testFlag( QCPAxis::spAxis ) ) + axis( type )->setSelectedParts( axis( type )->selectedParts() | QCPAxis::spAxis ); else - axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + axis( type )->setSelectedParts( axis( type )->selectedParts() & ~QCPAxis::spAxis ); } } } @@ -14370,35 +14845,35 @@ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts 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) +void QCPColorScaleAxisRectPrivate::axisSelectableChanged( QCPAxis::SelectableParts selectableParts ) { // synchronize axis base selectability: - foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + << QCPAxis::atRight ) { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) + if( QCPAxis* senderAxis = qobject_cast( sender() ) ) + if( senderAxis->axisType() == type ) continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + + if( axis( type )->selectableParts().testFlag( QCPAxis::spAxis ) ) { - if (selectableParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + if( selectableParts.testFlag( QCPAxis::spAxis ) ) + axis( type )->setSelectableParts( axis( type )->selectableParts() | QCPAxis::spAxis ); else - axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + 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 @@ -14406,37 +14881,26 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart \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) +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) +QCPData::QCPData( double key, double value ) + : key( key ), value( value ), keyErrorPlus( 0 ), keyErrorMinus( 0 ), valueErrorPlus( 0 ), valueErrorMinus( 0 ) { } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraph //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -14445,29 +14909,29 @@ QCPData::QCPData(double key, double value) : \brief A plottable representing a graph in a plot. \image html QCPGraph.png - + Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting instance is 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. - + \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. @@ -14478,7 +14942,7 @@ QCPData::QCPData(double key, double value) : /* 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. @@ -14491,29 +14955,28 @@ QCPData::QCPData(double key, double 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) +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); + + 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() @@ -14523,20 +14986,21 @@ QCPGraph::~QCPGraph() /*! 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) +void QCPGraph::setData( QCPDataMap* data, bool copy ) { - if (copy) + if( copy ) { *mData = *data; - } else + } + else { delete mData; mData = data; @@ -14544,22 +15008,22 @@ void QCPGraph::setData(QCPDataMap *data, bool copy) } /*! \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) +void QCPGraph::setData( const QVector& key, const QVector& value ) { mData->clear(); int n = key.size(); - n = qMin(n, value.size()); + n = qMin( n, value.size() ); QCPData newData; - for (int i=0; iinsertMulti(newData.key, newData); + mData->insertMulti( newData.key, newData ); } } @@ -14569,23 +15033,25 @@ void QCPGraph::setData(const QVector &key, const QVector &value) 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) +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()); + n = qMin( n, value.size() ); + n = qMin( n, valueError.size() ); QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); + mData->insertMulti( key[i], newData ); } } @@ -14598,21 +15064,24 @@ void QCPGraph::setDataValueError(const QVector &key, const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) +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()); + 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); + mData->insertMulti( key[i], newData ); } } @@ -14622,23 +15091,25 @@ void QCPGraph::setDataValueError(const QVector &key, const QVector &key, const QVector &value, const QVector &keyError) +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()); + n = qMin( n, value.size() ); + n = qMin( n, keyError.size() ); QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); + mData->insertMulti( key[i], newData ); } } @@ -14651,21 +15122,24 @@ void QCPGraph::setDataKeyError(const QVector &key, const QVector 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) +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()); + 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); + mData->insertMulti( key[i], newData ); } } @@ -14675,18 +15149,21 @@ void QCPGraph::setDataKeyError(const QVector &key, const QVector 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) +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()); + n = qMin( n, value.size() ); + n = qMin( n, valueError.size() ); + n = qMin( n, keyError.size() ); QCPData newData; - for (int i=0; i &key, const QVectorinsertMulti(key[i], newData); + mData->insertMulti( 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 + 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) +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()); + 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; i &key, const QVectorinsertMulti(key[i], newData); + mData->insertMulti( 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) +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 + 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) +void QCPGraph::setScatterStyle( const QCPScatterStyle& style ) { mScatterStyle = style; } @@ -14760,7 +15243,7 @@ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) \see ErrorType */ -void QCPGraph::setErrorType(ErrorType errorType) +void QCPGraph::setErrorType( ErrorType errorType ) { mErrorType = errorType; } @@ -14769,7 +15252,7 @@ void QCPGraph::setErrorType(ErrorType errorType) Sets the pen with which the error bars will be drawn. \see setErrorBarSize, setErrorType */ -void QCPGraph::setErrorPen(const QPen &pen) +void QCPGraph::setErrorPen( const QPen& pen ) { mErrorPen = pen; } @@ -14777,7 +15260,7 @@ void QCPGraph::setErrorPen(const QPen &pen) /*! Sets the width of the handles at both ends of an error bar in pixels. */ -void QCPGraph::setErrorBarSize(double size) +void QCPGraph::setErrorBarSize( double size ) { mErrorBarSize = size; } @@ -14785,15 +15268,15 @@ void QCPGraph::setErrorBarSize(double 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) +void QCPGraph::setErrorBarSkipSymbol( bool enabled ) { mErrorBarSkipSymbol = enabled; } @@ -14801,29 +15284,29 @@ void QCPGraph::setErrorBarSkipSymbol(bool 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) +void QCPGraph::setChannelFillGraph( QCPGraph* targetGraph ) { // prevent setting channel target to this graph itself: - if (targetGraph == this) + 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) + if( targetGraph && targetGraph->mParentPlot != mParentPlot ) { qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; mChannelFillGraph = 0; return; } - + mChannelFillGraph = targetGraph; } @@ -14831,19 +15314,19 @@ void QCPGraph::setChannelFillGraph(QCPGraph *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 @@ -14852,76 +15335,76 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) 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) +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) +void QCPGraph::addData( const QCPDataMap& dataMap ) { - mData->unite(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) +void QCPGraph::addData( const QCPData& data ) { - mData->insertMulti(data.key, 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) +void QCPGraph::addData( double key, double value ) { QCPData newData; newData.key = key; newData.value = value; - mData->insertMulti(newData.key, newData); + 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) +void QCPGraph::addData( const QVector& keys, const QVector& values ) { - int n = qMin(keys.size(), values.size()); + int n = qMin( keys.size(), values.size() ); QCPData newData; - for (int i=0; iinsertMulti(newData.key, newData); + mData->insertMulti( newData.key, newData ); } } @@ -14929,52 +15412,54 @@ void QCPGraph::addData(const QVector &keys, const QVector &value Removes all data points with keys smaller than \a key. \see addData, clearData */ -void QCPGraph::removeDataBefore(double key) +void QCPGraph::removeDataBefore( double key ) { QCPDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); + 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) +void QCPGraph::removeDataAfter( double key ) { - if (mData->isEmpty()) return; - QCPDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); + 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) +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); + 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) +void QCPGraph::removeData( double key ) { - mData->remove(key); + mData->remove( key ); } /*! @@ -14987,182 +15472,210 @@ void QCPGraph::clearData() } /* inherits documentation from base class */ -double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPGraph::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) + 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); + 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 +void QCPGraph::rescaleAxes( bool onlyEnlarge, bool includeErrorBars ) const { - rescaleKeyAxis(onlyEnlarge, includeErrorBars); - rescaleValueAxis(onlyEnlarge, includeErrorBars); + 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 +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; } + 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); - + if( keyAxis->scaleType() == QCPAxis::stLogarithmic ) + signDomain = ( keyAxis->range().upper < 0 ? sdNegative : sdPositive ); + bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); - - if (foundRange) + QCPRange newRange = getKeyRange( foundRange, signDomain, includeErrorBars ); + + if( foundRange ) { - if (onlyEnlarge) + if( onlyEnlarge ) { - if (keyAxis->range().lower < newRange.lower) + if( keyAxis->range().lower < newRange.lower ) newRange.lower = keyAxis->range().lower; - if (keyAxis->range().upper > newRange.upper) + if( keyAxis->range().upper > newRange.upper ) newRange.upper = keyAxis->range().upper; } - keyAxis->setRange(newRange); + 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 +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; } + 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); - + if( valueAxis->scaleType() == QCPAxis::stLogarithmic ) + signDomain = ( valueAxis->range().upper < 0 ? sdNegative : sdPositive ); + bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); - - if (foundRange) + QCPRange newRange = getValueRange( foundRange, signDomain, includeErrorBars ); + + if( foundRange ) { - if (onlyEnlarge) + if( onlyEnlarge ) { - if (valueAxis->range().lower < newRange.lower) + if( valueAxis->range().lower < newRange.lower ) newRange.lower = valueAxis->range().lower; - if (valueAxis->range().upper > newRange.upper) + if( valueAxis->range().upper > newRange.upper ) newRange.upper = valueAxis->range().upper; } - valueAxis->setRange(newRange); + valueAxis->setRange( newRange ); } } /* inherits documentation from base class */ -void QCPGraph::draw(QCPPainter *painter) +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; - + 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()) + 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: + 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) + 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(); + 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: - drawFill(painter, lineData); - + 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 - + 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); - + if( scatterData ) + drawScatterPlot( painter, scatterData ); + // free allocated line and point vectors: delete lineData; - if (scatterData) + if( scatterData ) delete scatterData; } /* inherits documentation from base class */ -void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +void QCPGraph::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const { // draw fill: - if (mBrush.style() != Qt::NoBrush) + 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); + 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) + 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 + 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()) + if( !mScatterStyle.isNone() ) { - applyScattersAntialiasingHint(painter); + 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())) + 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 + 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()); + mScatterStyle.applyTo( painter, mPen ); + mScatterStyle.drawShape( painter, QRectF( rect ).center() ); } } } @@ -15171,86 +15684,109 @@ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const 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 +void QCPGraph::getPlotData( QVector* lineData, QVector* scatterData ) const { - switch(mLineStyle) + 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; + 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 +void QCPGraph::getScatterPlotData( QVector* scatterData ) const { - getPreparedData(0, scatterData); + 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 +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; } - + 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()); - + 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) + if( keyAxis->orientation() == Qt::Vertical ) { - for (int i=0; icoordToPixel(lineData.at(i).value)); - (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); + ( *linePixelData )[i].setX( valueAxis->coordToPixel( lineData.at( i ).value ) ); + ( *linePixelData )[i].setY( keyAxis->coordToPixel( lineData.at( i ).key ) ); } - } else // key axis is horizontal + } + else // key axis is horizontal { - for (int i=0; icoordToPixel(lineData.at(i).key)); - (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); + ( *linePixelData )[i].setX( keyAxis->coordToPixel( lineData.at( i ).key ) ); + ( *linePixelData )[i].setY( valueAxis->coordToPixel( lineData.at( i ).value ) ); } } } @@ -15263,47 +15799,58 @@ void QCPGraph::getLinePlotData(QVector *linePixelData, QVector 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 +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; } - + 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); - + 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) + if( keyAxis->orientation() == Qt::Vertical ) { - double lastValue = valueAxis->coordToPixel(lineData.first().value); + 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); + key = keyAxis->coordToPixel( 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 + } + else // key axis is horizontal { - double lastValue = valueAxis->coordToPixel(lineData.first().value); + 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); + key = keyAxis->coordToPixel( 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 ); } } } @@ -15316,47 +15863,58 @@ void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *linePixelData, QVector *scatterData) const +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; } - + 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); - + 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) + if( keyAxis->orientation() == Qt::Vertical ) { - double lastKey = keyAxis->coordToPixel(lineData.first().key); + 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); + value = valueAxis->coordToPixel( 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 + } + else // key axis is horizontal { - double lastKey = keyAxis->coordToPixel(lineData.first().key); + 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); + value = valueAxis->coordToPixel( 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 ); } } } @@ -15369,61 +15927,71 @@ void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *linePixelData, QVector *scatterData) const +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - 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 + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if( !linePixelData ) { - 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); + 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; i < lineData.size(); ++i ) + { + key = ( keyAxis->coordToPixel( 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; i < lineData.size(); ++i ) + { + key = ( keyAxis->coordToPixel( 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 ); + } } /*! @@ -15434,147 +16002,169 @@ void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *linePixelData, QVector *scatterData) const +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; } - + 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 - + 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) + if( keyAxis->orientation() == Qt::Vertical ) { - double zeroPointX = valueAxis->coordToPixel(0); + 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); + key = keyAxis->coordToPixel( 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 + } + else // key axis is horizontal { - double zeroPointY = valueAxis->coordToPixel(0); + 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)); + key = keyAxis->coordToPixel( 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 +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) + 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 + 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)); + 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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - applyErrorBarsAntialiasingHint(painter); - painter->setPen(mErrorPen); - if (keyAxis->orientation() == Qt::Vertical) + 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; i < scatterData->size(); ++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)); + for( int i = 0; i < scatterData->size(); ++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) + applyScattersAntialiasingHint( painter ); + mScatterStyle.applyTo( painter, mPen ); + if( keyAxis->orientation() == Qt::Vertical ) { - for (int i=0; isize(); ++i) - mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); - } else + for( int i = 0; i < scatterData->size(); ++i ) + mScatterStyle.drawShape( painter, valueAxis->coordToPixel( scatterData->at( i ).value ), + keyAxis->coordToPixel( scatterData->at( i ).key ) ); + } + else { - for (int i=0; isize(); ++i) - mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); + for( int i = 0; i < scatterData->size(); ++i ) + 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 +void QCPGraph::drawLinePlot( QCPPainter* painter, QVector* lineData ) const { // draw line of graph: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + if( mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0 ) { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - + applyDefaultAntialiasingHint( painter ); + painter->setPen( mainPen() ); + painter->setBrush( Qt::NoBrush ); + /* Draws polyline in batches, currently not used: int p = 0; while (p < lineData->size()) @@ -15589,389 +16179,465 @@ void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) con 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)) + if( mParentPlot->plottingHints().testFlag( QCP::phFastPolylines ) && painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag( QCPPainter::pmVectorized ) && + !painter->modes().testFlag( QCPPainter::pmNoCaching ) ) { - for (int i=1; isize(); ++i) - painter->drawLine(lineData->at(i-1), lineData->at(i)); - } else + for( int i = 1; i < lineData->size(); ++i ) + painter->drawLine( lineData->at( i - 1 ), lineData->at( i ) ); + } + else { - painter->drawPolyline(QPolygonF(*lineData)); + painter->drawPolyline( QPolygonF( *lineData ) ); } } } /*! \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 +void QCPGraph::drawImpulsePlot( QCPPainter* painter, QVector* lineData ) const { // draw impulses: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + if( mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0 ) { - applyDefaultAntialiasingHint(painter); + 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); + 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 +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()) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) + { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; 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 + // 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 ) { - if (lineData) + 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; + 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() ? -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)); + 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 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) + 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) + ++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.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) + if( it.value().value < minValue ) minValue = it.value().value; - else if (it.value().value > maxValue) + else if( it.value().value > maxValue ) maxValue = it.value().value; ++intervalDataCount; - } else // new pixel interval started + } + else // new pixel interval started { - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster + 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; + 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)); + 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( 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( 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) + + if( scatterData ) { double valueMaxRange = valueAxis->range().upper; double valueMinRange = valueAxis->range().lower; QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; + 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 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) + ++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.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) + 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) + } + 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 + } + else // new pixel started { - if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them + 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 + // 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) + while( intervalIt != it ) { - if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) - scatterData->append(intervalIt.value()); + 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 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)); + 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 + 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 + // 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) + while( intervalIt != it ) { - if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) - scatterData->append(intervalIt.value()); + 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 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 + } + else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters { - QVector *dataVector = 0; - if (lineData) + QVector* dataVector = 0; + if( lineData ) dataVector = lineData; - else if (scatterData) + else if( scatterData ) dataVector = scatterData; - if (dataVector) + 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) + QCPDataMap::const_iterator upperEnd = upper + 1; + dataVector->reserve( dataCount + 2 ); // +2 for possible fill end points + while( it != upperEnd ) { - dataVector->append(it.value()); + dataVector->append( it.value() ); ++it; } } - if (lineData && scatterData) + 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 +void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData& data ) const { - 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 + 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::Vertical) + 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) + 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); + 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( 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)); + 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)); + painter->drawLine( QLineF( x - barWidthHalf, a, x + barWidthHalf, a ) ); + painter->drawLine( QLineF( x - barWidthHalf, b, x + barWidthHalf, b ) ); } - if (mErrorType == etValue || mErrorType == etBoth) + 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); + 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( 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)); + 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)); + painter->drawLine( QLineF( a, y - barWidthHalf, a, y + barWidthHalf ) ); + painter->drawLine( QLineF( b, y - barWidthHalf, b, y + barWidthHalf ) ); } - } else // mKeyAxis->orientation() is Qt::Horizontal + } + else // mKeyAxis->orientation() is Qt::Horizontal { // draw value error vertically and key error horizontally - if (mErrorType == etKey || mErrorType == etBoth) + 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); + 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( 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)); + 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)); + painter->drawLine( QLineF( a, y - barWidthHalf, a, y + barWidthHalf ) ); + painter->drawLine( QLineF( b, y - barWidthHalf, b, y + barWidthHalf ) ); } - if (mErrorType == etValue || mErrorType == etBoth) + 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); + 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( 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)); + 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)); + 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 +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()) + 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 + 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 +int QCPGraph::countDataInBounds( const QCPDataMap::const_iterator& lower, + const QCPDataMap::const_iterator& upper, + int maxCount ) const { - if (upper == mData->constEnd() && lower == mData->constEnd()) + if( upper == mData->constEnd() && lower == mData->constEnd() ) return 0; QCPDataMap::const_iterator it = lower; int count = 1; - while (it != upper && count < maxCount) + while( it != upper && count < maxCount ) { ++it; ++count; @@ -15980,114 +16646,130 @@ int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const Q } /*! \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 +void QCPGraph::addFillBasePoints( QVector* lineData ) const { - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - + if( !mKeyAxis ) + { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + // append points that close the polygon fill at the key axis: - if (mKeyAxis.data()->orientation() == Qt::Vertical) + if( mKeyAxis.data()->orientation() == Qt::Vertical ) { - *lineData << upperFillBasePoint(lineData->last().y()); - *lineData << lowerFillBasePoint(lineData->first().y()); - } else + *lineData << upperFillBasePoint( lineData->last().y() ); + *lineData << lowerFillBasePoint( lineData->first().y() ); + } + else { - *lineData << upperFillBasePoint(lineData->last().x()); - *lineData << lowerFillBasePoint(lineData->first().x()); + *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 +void QCPGraph::removeFillBasePoints( QVector* lineData ) const { - lineData->remove(lineData->size()-2, 2); + 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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - if (keyAxis->axisType() == QCPAxis::atLeft) + 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)); + point.setX( valueAxis->coordToPixel( 0 ) ); + point.setY( lowerKey ); } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + 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( 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()); + 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( 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()); + 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()); + 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 @@ -16097,62 +16779,73 @@ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const \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 +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) + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) { - if (keyAxis->axisType() == QCPAxis::atLeft) + 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)); + point.setX( valueAxis->coordToPixel( 0 ) ); + point.setY( upperKey ); } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + 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( 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()); + 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( 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()); + 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()); + 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 @@ -16160,178 +16853,209 @@ QPointF QCPGraph::upperFillBasePoint(double upperKey) const key axes vertical). For increased performance (due to implicit sharing), keep the returned QPolygonF const. */ -const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const +const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineData ) const { - if (!mChannelFillGraph) + 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(); - - 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(); + 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); - + thisData.reserve( lineData->size() + otherData.size() ); // because we will join both vectors at end of this function + for( int i = 0; i < lineData->size(); ++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; - + 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) + 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()) + // 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()) + if( croppedData->first().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); + if( staticData->first().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 + 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()); + 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()); - + ( *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)); + 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()); + 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 + ( *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()) + // 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()) + if( croppedData->first().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); + if( staticData->first().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 + 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()); + 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()); - + ( *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)); + 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()); + 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()); + ( *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); + 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 +int QCPGraph::findIndexAboveX( const QVector* data, double x ) const { - for (int i=data->size()-1; i>=0; --i) + for( int i = data->size() - 1; i >= 0; --i ) { - if (data->at(i).x() < x) + if( data->at( i ).x() < x ) { - if (isize()-1) - return i+1; + if( i < data->size() - 1 ) + return i + 1; else - return data->size()-1; + 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 +int QCPGraph::findIndexBelowX( const QVector* data, double x ) const { - for (int i=0; isize(); ++i) + for( int i = 0; i < data->size(); ++i ) { - if (data->at(i).x() > x) + if( data->at( i ).x() > x ) { - if (i>0) - return i-1; + if( i > 0 ) + return i - 1; else return 0; } @@ -16340,20 +17064,20 @@ int QCPGraph::findIndexBelowX(const QVector *data, double x) const } /*! \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 +int QCPGraph::findIndexAboveY( const QVector* data, double y ) const { - for (int i=0; isize(); ++i) + for( int i = 0; i < data->size(); ++i ) { - if (data->at(i).y() < y) + if( data->at( i ).y() < y ) { - if (i>0) - return i-1; + if( i > 0 ) + return i - 1; else return 0; } @@ -16362,212 +17086,185 @@ int QCPGraph::findIndexAboveY(const QVector *data, double y) const } /*! \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 500. */ -double QCPGraph::pointDistance(const QPointF &pixelPoint) const +double QCPGraph::pointDistance( const QPointF& pixelPoint ) const { - if (mData->isEmpty()) + if( mData->isEmpty() ) { qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data"; return 500; } - if (mData->size() == 1) + if( mData->size() == 1 ) { - QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); - return QVector2D(dataPoint-pixelPoint).length(); + QPointF dataPoint = coordsToPixels( mData->constBegin().key(), mData->constBegin().value().value ); + return QVector2D( dataPoint - pixelPoint ).length(); } - - if (mLineStyle == lsNone && mScatterStyle.isNone()) + + if( mLineStyle == lsNone && mScatterStyle.isNone() ) return 500; - + // calculate minimum distances to graph representation: - if (mLineStyle == lsNone) + if( mLineStyle == lsNone ) { // no line displayed, only calculate distance to scatter points: - QVector *scatterData = new QVector; - getScatterPlotData(scatterData); + QVector* scatterData = new QVector; + getScatterPlotData( scatterData ); double minDistSqr = std::numeric_limits::max(); QPointF ptA; - QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels - for (int i=1; isize(); ++i) + QPointF ptB = coordsToPixels( + scatterData->at( 0 ).key, + scatterData->at( 0 ).value ); // getScatterPlotData returns in plot coordinates, so transform to pixels + for( int i = 1; i < scatterData->size(); ++i ) { ptA = ptB; - ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value); - double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint); - if (currentDistSqr < minDistSqr) + ptB = coordsToPixels( scatterData->at( i ).key, scatterData->at( i ).value ); + double currentDistSqr = distSqrToLine( ptA, ptB, pixelPoint ); + if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } delete scatterData; - return sqrt(minDistSqr); - } else + return sqrt( minDistSqr ); + } + else { // line displayed calculate distance to line segments: - QVector *lineData = new QVector; - getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here + QVector* lineData = new QVector; + getPlotData( lineData, 0 ); // unlike with getScatterPlotData we get pixel coordinates here double minDistSqr = std::numeric_limits::max(); - if (mLineStyle == lsImpulse) + if( mLineStyle == lsImpulse ) { // impulse plot differs from other line styles in that the lineData points are only pairwise connected: - for (int i=0; isize()-1; i+=2) // iterate pairs + for( int i = 0; i < lineData->size() - 1; i += 2 ) // iterate pairs { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); - if (currentDistSqr < minDistSqr) + double currentDistSqr = distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); + if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } - } else + } + else { // all other line plots (line and step) connect points directly: - for (int i=0; isize()-1; ++i) + for( int i = 0; i < lineData->size() - 1; ++i ) { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); - if (currentDistSqr < minDistSqr) + double currentDistSqr = distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); + if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } } delete lineData; - return sqrt(minDistSqr); + return sqrt( minDistSqr ); } } /*! \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 +int QCPGraph::findIndexBelowY( const QVector* data, double y ) const { - for (int i=data->size()-1; i>=0; --i) + for( int i = data->size() - 1; i >= 0; --i ) { - if (data->at(i).y() > y) + if( data->at( i ).y() > y ) { - if (isize()-1) - return i+1; + if( i < data->size() - 1 ) + return i + 1; else - return data->size()-1; + return data->size() - 1; } } return -1; } /* inherits documentation from base class */ -QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +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); + return getKeyRange( foundRange, inSignDomain, true ); } /* inherits documentation from base class */ -QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const +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); + 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 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 + + if( inSignDomain == sdBoth ) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { current = it.value().key; - currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); - if (current-currentErrorMinus < range.lower || !haveLower) + currentErrorMinus = ( includeErrors ? it.value().keyErrorMinus : 0 ); + currentErrorPlus = ( includeErrors ? it.value().keyErrorPlus : 0 ); + if( current - currentErrorMinus < range.lower || !haveLower ) { - range.lower = current-currentErrorMinus; + range.lower = current - currentErrorMinus; haveLower = true; } - if (current+currentErrorPlus > range.upper || !haveUpper) + if( current + currentErrorPlus > range.upper || !haveUpper ) { - range.upper = current+currentErrorPlus; + range.upper = current + currentErrorPlus; haveUpper = true; } ++it; } - } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + } + else if( inSignDomain == sdNegative ) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { 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) + 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; + range.lower = current - currentErrorMinus; haveLower = true; } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + if( ( current + currentErrorPlus > range.upper || !haveUpper ) && current + currentErrorPlus < 0 ) { - range.upper = current+currentErrorPlus; + 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( 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) + 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().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) + if( ( current > range.upper || !haveUpper ) && current < 0 ) { range.upper = current; haveUpper = true; @@ -16576,104 +17273,108 @@ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool i ++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().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 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 + + if( inSignDomain == sdBoth ) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { current = it.value().value; - currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); - if (current-currentErrorMinus < range.lower || !haveLower) + currentErrorMinus = ( includeErrors ? it.value().valueErrorMinus : 0 ); + currentErrorPlus = ( includeErrors ? it.value().valueErrorPlus : 0 ); + if( current - currentErrorMinus < range.lower || !haveLower ) { - range.lower = current-currentErrorMinus; + range.lower = current - currentErrorMinus; haveLower = true; } - if (current+currentErrorPlus > range.upper || !haveUpper) + if( current + currentErrorPlus > range.upper || !haveUpper ) { - range.upper = current+currentErrorPlus; + range.upper = current + currentErrorPlus; haveUpper = true; } ++it; } - } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + } + else if( inSignDomain == sdNegative ) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { current = it.value().value; - currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); - currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); - if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) + 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; + range.lower = current - currentErrorMinus; haveLower = true; } - if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + if( ( current + currentErrorPlus > range.upper || !haveUpper ) && current + currentErrorPlus < 0 ) { - range.upper = current+currentErrorPlus; + 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( 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) + 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; - 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) + if( ( current > range.upper || !haveUpper ) && current < 0 ) { range.upper = current; haveUpper = true; @@ -16682,74 +17383,102 @@ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool ++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; + 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) +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) +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. - + \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.) - + the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, + QCustomPlot::removePlottable, etc.) + Usually, you first create an instance: \code QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode @@ -16767,25 +17496,24 @@ QCPCurveData::QCPCurveData(double t, double key, double 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) +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); + 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 + mSelectedPen.setWidthF( 2.5 ); + mSelectedPen.setColor( QColor( 80, 80, 255 ) ); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; - - setScatterStyle(QCPScatterStyle()); - setLineStyle(lsLine); + + setScatterStyle( QCPScatterStyle() ); + setLineStyle( lsLine ); } QCPCurve::~QCPCurve() @@ -16795,17 +17523,18 @@ QCPCurve::~QCPCurve() /*! 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) +void QCPCurve::setData( QCPCurveDataMap* data, bool copy ) { - if (copy) + if( copy ) { *mData = *data; - } else + } + else { delete mData; mData = data; @@ -16813,44 +17542,44 @@ void QCPCurve::setData(QCPCurveDataMap *data, bool copy) } /*! \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) +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()); + n = qMin( n, key.size() ); + n = qMin( n, value.size() ); QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); + mData->insertMulti( 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) +void QCPCurve::setData( const QVector& key, const QVector& value ) { mData->clear(); int n = key.size(); - n = qMin(n, value.size()); + n = qMin( n, value.size() ); QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); + mData->insertMulti( newData.t, newData ); } } @@ -16858,10 +17587,10 @@ void QCPCurve::setData(const QVector &key, const QVector &value) 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) +void QCPCurve::setScatterStyle( const QCPScatterStyle& style ) { mScatterStyle = style; } @@ -16870,10 +17599,10 @@ void QCPCurve::setScatterStyle(const QCPScatterStyle &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) +void QCPCurve::setLineStyle( QCPCurve::LineStyle style ) { mLineStyle = style; } @@ -16882,69 +17611,69 @@ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) Adds the provided data points in \a dataMap to the current data. \see removeData */ -void QCPCurve::addData(const QCPCurveDataMap &dataMap) +void QCPCurve::addData( const QCPCurveDataMap& dataMap ) { - mData->unite(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) +void QCPCurve::addData( const QCPCurveData& data ) { - mData->insertMulti(data.t, 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) +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); + 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) +void QCPCurve::addData( double key, double value ) { QCPCurveData newData; - if (!mData->isEmpty()) - newData.t = (mData->constEnd()-1).key()+1; + 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); + 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) +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()); + n = qMin( n, keys.size() ); + n = qMin( n, values.size() ); QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); + mData->insertMulti( newData.t, newData ); } } @@ -16952,53 +17681,55 @@ void QCPCurve::addData(const QVector &ts, const QVector &keys, c Removes all data points with curve parameter t smaller than \a t. \see addData, clearData */ -void QCPCurve::removeDataBefore(double t) +void QCPCurve::removeDataBefore( double t ) { QCPCurveDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < t) - it = mData->erase(it); + 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) +void QCPCurve::removeDataAfter( double t ) { - if (mData->isEmpty()) return; - QCPCurveDataMap::iterator it = mData->upperBound(t); - while (it != mData->end()) - it = mData->erase(it); + 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) +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); + 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) +void QCPCurve::removeData( double t ) { - mData->remove(t); + mData->remove( t ); } /*! @@ -17011,150 +17742,168 @@ void QCPCurve::clearData() } /* inherits documentation from base class */ -double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPCurve::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) + 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); + 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) +void QCPCurve::draw( QCPPainter* painter ) { - if (mData->isEmpty()) return; - + if( mData->isEmpty() ) + return; + // allocate line vector: - QVector *lineData = new QVector; - + QVector* lineData = new QVector; + // fill with curve data: - getCurveData(lineData); - - // check data validity if flag set: + getCurveData( lineData ); + +// check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPCurveDataMap::const_iterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++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(); + 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) + if( mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0 ) { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(QPolygonF(*lineData)); + 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) + if( mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0 ) { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); + 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)) + if( mParentPlot->plottingHints().testFlag( QCP::phFastPolylines ) && painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag( QCPPainter::pmVectorized ) && + !painter->modes().testFlag( QCPPainter::pmNoCaching ) ) { - for (int i=1; isize(); ++i) - painter->drawLine(lineData->at(i-1), lineData->at(i)); - } else + for( int i = 1; i < lineData->size(); ++i ) + painter->drawLine( lineData->at( i - 1 ), lineData->at( i ) ); + } + else { - painter->drawPolyline(QPolygonF(*lineData)); + painter->drawPolyline( QPolygonF( *lineData ) ); } } - + // draw scatters: - if (!mScatterStyle.isNone()) - drawScatterPlot(painter, lineData); - + 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 +void QCPCurve::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const { // draw fill: - if (mBrush.style() != Qt::NoBrush) + 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); + 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) + 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 + 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()) + if( !mScatterStyle.isNone() ) { - applyScattersAntialiasingHint(painter); + 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())) + 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 + 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()); + 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 +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) - mScatterStyle.drawShape(painter, pointData->at(i)); + applyScattersAntialiasingHint( painter ); + mScatterStyle.applyTo( painter, mPen ); + for( int i = 0; i < pointData->size(); ++i ) + mScatterStyle.drawShape( painter, pointData->at( i ) ); } /*! \internal - + called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the curve. Line segments that aren't visible in the current axis rect are handled in an optimized way. */ -void QCPCurve::getCurveData(QVector *lineData) const +void QCPCurve::getCurveData( QVector* lineData ) const { /* Extended sides of axis rect R divide space into 9 regions: 1__|_4_|__7 2__|_R_|__8 3 | 6 | 9 - General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner is removed. - Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and + General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner + is removed. + Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look + of lines and fills inside R consistent. The region R has index 5. */ - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - + QCPAxis* keyAxis = mKeyAxis.data(); + QCPAxis* valueAxis = mValueAxis.data(); + if( !keyAxis || !valueAxis ) + { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); - lineData->reserve(mData->size()); + lineData->reserve( mData->size() ); QCPCurveDataMap::const_iterator it; int lastRegion = 5; int currentRegion = 5; @@ -17162,40 +17911,42 @@ void QCPCurve::getCurveData(QVector *lineData) const double RRight = keyAxis->range().upper; double RBottom = valueAxis->range().lower; double RTop = valueAxis->range().upper; - double x, y; // current key/value + double x, y; // current key/value bool addedLastAlready = true; - bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly - for (it = mData->constBegin(); it != mData->constEnd(); ++it) + bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly + for( it = mData->constBegin(); it != mData->constEnd(); ++it ) { x = it.value().key; y = it.value().value; // determine current region: - if (x < RLeft) // region 123 + if( x < RLeft ) // region 123 { - if (y > RTop) + if( y > RTop ) currentRegion = 1; - else if (y < RBottom) + else if( y < RBottom ) currentRegion = 3; else currentRegion = 2; - } else if (x > RRight) // region 789 + } + else if( x > RRight ) // region 789 { - if (y > RTop) + if( y > RTop ) currentRegion = 7; - else if (y < RBottom) + else if( y < RBottom ) currentRegion = 9; else currentRegion = 8; - } else // region 456 + } + else // region 456 { - if (y > RTop) + if( y > RTop ) currentRegion = 4; - else if (y < RBottom) + else if( y < RBottom ) currentRegion = 6; else currentRegion = 5; } - + /* Watch out, the next part is very tricky. It modifies the curve such that it seems like the whole thing is still drawn, but actually the points outside the axisRect are simplified @@ -17203,90 +17954,110 @@ void QCPCurve::getCurveData(QVector *lineData) const thereby each subsequent point may be in a different region or even skip some. */ // determine whether to keep current point: - if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already + if( currentRegion == 5 || + ( firstPoint && + mBrush.style() != Qt::NoBrush ) ) // current is in R, add current and last if it wasn't added already { - if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly - lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector - else if (lastRegion != 5) // added last already. If that's the case, we probably added it at optimized position. So go back and make sure it's at original position (else the angle changes under which this segment enters R) + if( !addedLastAlready ) // in case curve just entered R, make sure the last point outside R is also drawn + // correctly + lineData->append( + coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); // add last point to vector + else if( lastRegion != 5 ) // added last already. If that's the case, we probably added it at optimized position. + // So go back and make sure it's at original position (else the angle changes under + // which this segment enters R) { - if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point - lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value)); + if( !firstPoint ) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is + // no last point + lineData->replace( lineData->size() - 1, coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); } - lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector - addedLastAlready = true; // so in next iteration, we don't add this point twice - } else if (currentRegion != lastRegion) // changed region, add current and last if not added already + lineData->append( coordsToPixels( it.value().key, it.value().value ) ); // add current point to vector + addedLastAlready = true; // so in next iteration, we don't add this point twice + } + else if( currentRegion != lastRegion ) // changed region, add current and last if not added already { - // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away) - - // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we can't place points optimized - if (lastRegion == 5 || // coming from R - ((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal - ((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal - ((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal - ((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal + // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside + // axisRect instead of potentially far away) + + // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we + // can't place points optimized + if( lastRegion == 5 || // coming from R + ( ( lastRegion == 2 && currentRegion == 4 ) || + ( lastRegion == 4 && currentRegion == 2 ) ) || // skip top left diagonal + ( ( lastRegion == 4 && currentRegion == 8 ) || + ( lastRegion == 8 && currentRegion == 4 ) ) || // skip top right diagonal + ( ( lastRegion == 8 && currentRegion == 6 ) || + ( lastRegion == 6 && currentRegion == 8 ) ) || // skip bottom right diagonal + ( ( lastRegion == 6 && currentRegion == 2 ) || + ( lastRegion == 2 && currentRegion == 6 ) ) // skip bottom left diagonal ) { // always add last point if not added already, original: - if (!addedLastAlready) - lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); + if( !addedLastAlready ) + lineData->append( coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); // add current point, original: - lineData->append(coordsToPixels(it.value().key, it.value().value)); - } else // no special case that forbids optimized point placement, so do it: + lineData->append( coordsToPixels( it.value().key, it.value().value ) ); + } + else // no special case that forbids optimized point placement, so do it: { // always add last point if not added already, optimized: - if (!addedLastAlready) - lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect)); + if( !addedLastAlready ) + lineData->append( + outsideCoordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value, currentRegion, axisRect ) ); // add current point, optimized: - lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect)); + lineData->append( outsideCoordsToPixels( it.value().key, it.value().value, currentRegion, axisRect ) ); } - addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice - } else // neither in R, nor crossed a region boundary, skip current point + addedLastAlready = + true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice + } + else // neither in R, nor crossed a region boundary, skip current point { addedLastAlready = false; } lastRegion = currentRegion; firstPoint = false; } - // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started inside R: - if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty()) - lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value)); + // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started + // inside R: + if( lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty() ) + lineData->append( + coordsToPixels( ( mData->constEnd() - 1 ).value().key, ( mData->constEnd() - 1 ).value().value ) ); } /*! \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 +double QCPCurve::pointDistance( const QPointF& pixelPoint ) const { - if (mData->isEmpty()) + if( mData->isEmpty() ) { qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; return 500; } - if (mData->size() == 1) + if( mData->size() == 1 ) { - QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); - return QVector2D(dataPoint-pixelPoint).length(); + 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); + QVector* lineData = new QVector; + getCurveData( lineData ); double minDistSqr = std::numeric_limits::max(); - for (int i=0; isize()-1; ++i) + for( int i = 0; i < lineData->size() - 1; ++i ) { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); - if (currentDistSqr < minDistSqr) + double currentDistSqr = distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); + if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } delete lineData; - return sqrt(minDistSqr); + return sqrt( minDistSqr ); } /*! \internal - + This is a specialized \ref coordsToPixels function for points that are outside the visible axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments to those line segments that cross region boundaries, see documentation there). It only uses the @@ -17296,49 +18067,66 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint) const in ones) significantly while keeping the illusion the whole curve and its filling is still being drawn for the viewer. */ -QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const +QPointF QCPCurve::outsideCoordsToPixels( double key, double value, int region, QRect axisRect ) const { - int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2; - QPointF result = coordsToPixels(key, value); - switch (region) + int margin = qCeil( qMax( mScatterStyle.size(), (double)mPen.widthF() ) ) + 2; + QPointF result = coordsToPixels( key, value ); + switch( region ) { - case 2: result.setX(axisRect.left()-margin); break; // left - case 8: result.setX(axisRect.right()+margin); break; // right - case 4: result.setY(axisRect.top()-margin); break; // top - case 6: result.setY(axisRect.bottom()+margin); break; // bottom - case 1: result.setX(axisRect.left()-margin); - result.setY(axisRect.top()-margin); break; // top left - case 7: result.setX(axisRect.right()+margin); - result.setY(axisRect.top()-margin); break; // top right - case 9: result.setX(axisRect.right()+margin); - result.setY(axisRect.bottom()+margin); break; // bottom right - case 3: result.setX(axisRect.left()-margin); - result.setY(axisRect.bottom()+margin); break; // bottom left + case 2: + result.setX( axisRect.left() - margin ); + break; // left + case 8: + result.setX( axisRect.right() + margin ); + break; // right + case 4: + result.setY( axisRect.top() - margin ); + break; // top + case 6: + result.setY( axisRect.bottom() + margin ); + break; // bottom + case 1: + result.setX( axisRect.left() - margin ); + result.setY( axisRect.top() - margin ); + break; // top left + case 7: + result.setX( axisRect.right() + margin ); + result.setY( axisRect.top() - margin ); + break; // top right + case 9: + result.setX( axisRect.right() + margin ); + result.setY( axisRect.bottom() + margin ); + break; // bottom right + case 3: + result.setX( axisRect.left() - margin ); + result.setY( axisRect.bottom() + margin ); + break; // bottom left } return result; } /* inherits documentation from base class */ -QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +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()) + while( it != mData->constEnd() ) { current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + if( inSignDomain == sdBoth || ( inSignDomain == sdNegative && current < 0 ) || + ( inSignDomain == sdPositive && current > 0 ) ) { - if (current < range.lower || !haveLower) + if( current < range.lower || !haveLower ) { range.lower = current; haveLower = true; } - if (current > range.upper || !haveUpper) + if( current > range.upper || !haveUpper ) { range.upper = current; haveUpper = true; @@ -17346,32 +18134,33 @@ QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const } ++it; } - + foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ -QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const +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()) + while( it != mData->constEnd() ) { current = it.value().value; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + if( inSignDomain == sdBoth || ( inSignDomain == sdNegative && current < 0 ) || + ( inSignDomain == sdPositive && current > 0 ) ) { - if (current < range.lower || !haveLower) + if( current < range.lower || !haveLower ) { range.lower = current; haveLower = true; } - if (current > range.upper || !haveUpper) + if( current > range.upper || !haveUpper ) { range.upper = current; haveUpper = true; @@ -17379,47 +18168,41 @@ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) cons } ++it; } - + foundRange = haveLower && haveUpper; return range; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// 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) +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) +QCPBarData::QCPBarData( double key, double value ) : key( key ), value( value ) { } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBars //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -17428,23 +18211,23 @@ QCPBarData::QCPBarData(double key, double value) : \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). - + Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear stacked. - + \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: \code QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode @@ -17460,14 +18243,14 @@ QCPBarData::QCPBarData(double key, double value) : /*! \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 */ @@ -17476,54 +18259,54 @@ QCPBarData::QCPBarData(double key, double 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) +QCPBars::QCPBars( QCPAxis* keyAxis, QCPAxis* valueAxis ) : QCPAbstractPlottable( keyAxis, valueAxis ) { mData = new QCPBarDataMap; - mPen.setColor(Qt::blue); - mPen.setStyle(Qt::SolidLine); - mBrush.setColor(QColor(40, 50, 255, 30)); - mBrush.setStyle(Qt::SolidPattern); + 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 + mSelectedPen.setWidthF( 2.5 ); + mSelectedPen.setColor( QColor( 80, 80, 255 ) ); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; - + mWidth = 0.75; } QCPBars::~QCPBars() { - if (mBarBelow || mBarAbove) - connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + if( mBarBelow || mBarAbove ) + connectBars( mBarBelow.data(), mBarAbove.data() ); // take this bar out of any stacking delete mData; } /*! Sets the width of the bars in plot (key) coordinates. */ -void QCPBars::setWidth(double width) +void QCPBars::setWidth( double width ) { mWidth = width; } /*! 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) +void QCPBars::setData( QCPBarDataMap* data, bool copy ) { - if (copy) + if( copy ) { *mData = *data; - } else + } + else { delete mData; mData = data; @@ -17531,22 +18314,22 @@ void QCPBars::setData(QCPBarDataMap *data, bool copy) } /*! \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) +void QCPBars::setData( const QVector& key, const QVector& value ) { mData->clear(); int n = key.size(); - n = qMin(n, value.size()); + n = qMin( n, value.size() ); QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); + mData->insertMulti( newData.key, newData ); } } @@ -17554,32 +18337,33 @@ void QCPBars::setData(const QVector &key, const QVector &value) 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) +void QCPBars::moveBelow( QCPBars* bars ) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + 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 + 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 ) { - if (bars->mBarBelow) - connectBars(bars->mBarBelow.data(), this); - connectBars(this, bars); + if( bars->mBarBelow ) + connectBars( bars->mBarBelow.data(), this ); + connectBars( this, bars ); } } @@ -17587,32 +18371,33 @@ void QCPBars::moveBelow(QCPBars *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 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, barBelow, barAbove */ -void QCPBars::moveAbove(QCPBars *bars) +void QCPBars::moveAbove( QCPBars* bars ) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + 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 + 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 ) { - if (bars->mBarAbove) - connectBars(this, bars->mBarAbove.data()); - connectBars(bars, this); + if( bars->mBarAbove ) + connectBars( this, bars->mBarAbove.data() ); + connectBars( bars, this ); } } @@ -17620,46 +18405,46 @@ void QCPBars::moveAbove(QCPBars *bars) Adds the provided data points in \a dataMap to the current data. \see removeData */ -void QCPBars::addData(const QCPBarDataMap &dataMap) +void QCPBars::addData( const QCPBarDataMap& dataMap ) { - mData->unite(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) +void QCPBars::addData( const QCPBarData& data ) { - mData->insertMulti(data.key, 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) +void QCPBars::addData( double key, double value ) { QCPBarData newData; newData.key = key; newData.value = value; - mData->insertMulti(newData.key, newData); + 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) +void QCPBars::addData( const QVector& keys, const QVector& values ) { int n = keys.size(); - n = qMin(n, values.size()); + n = qMin( n, values.size() ); QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); + mData->insertMulti( newData.key, newData ); } } @@ -17667,52 +18452,54 @@ void QCPBars::addData(const QVector &keys, const QVector &values Removes all data points with key smaller than \a key. \see addData, clearData */ -void QCPBars::removeDataBefore(double key) +void QCPBars::removeDataBefore( double key ) { QCPBarDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); + 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) +void QCPBars::removeDataAfter( double key ) { - if (mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); + 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) +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); + 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) +void QCPBars::removeData( double key ) { - mData->remove(key); + mData->remove( key ); } /*! @@ -17725,122 +18512,133 @@ void QCPBars::clearData() } /* inherits documentation from base class */ -double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPBars::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) + 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; double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - for (it = mData->constBegin(); it != mData->constEnd(); ++it) + pixelsToCoords( pos, posKey, posValue ); + for( it = mData->constBegin(); it != mData->constEnd(); ++it ) { - double baseValue = getBaseValue(it.key(), it.value().value >=0); - QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5); - QCPRange valueRange(baseValue, baseValue+it.value().value); - if (keyRange.contains(posKey) && valueRange.contains(posValue)) - return mParentPlot->selectionTolerance()*0.99; + double baseValue = getBaseValue( it.key(), it.value().value >= 0 ); + QCPRange keyRange( it.key() - mWidth * 0.5, it.key() + mWidth * 0.5 ); + QCPRange valueRange( baseValue, baseValue + it.value().value ); + if( keyRange.contains( posKey ) && valueRange.contains( posValue ) ) + return mParentPlot->selectionTolerance() * 0.99; } } return -1; } /* inherits documentation from base class */ -void QCPBars::draw(QCPPainter *painter) +void QCPBars::draw( QCPPainter* painter ) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mData->isEmpty()) return; - + if( !mKeyAxis || !mValueAxis ) + { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if( mData->isEmpty() ) + return; + QCPBarDataMap::const_iterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++it) + for( it = mData->constBegin(); it != mData->constEnd(); ++it ) { // skip bar if not visible in key axis range: - if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper) + if( it.key() + mWidth * 0.5 < mKeyAxis.data()->range().lower || + it.key() - mWidth * 0.5 > mKeyAxis.data()->range().upper ) continue; - // check data validity if flag set: +// 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(); + 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); + QPolygonF barPolygon = getBarPolygon( it.key(), it.value().value ); // draw bar fill: - if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + if( mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0 ) { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(barPolygon); + applyFillAntialiasingHint( painter ); + painter->setPen( Qt::NoPen ); + painter->setBrush( mainBrush() ); + painter->drawPolygon( barPolygon ); } // draw bar line: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + if( mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0 ) { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - painter->drawPolyline(barPolygon); + 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 +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); + 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 - + 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). */ -QPolygonF QCPBars::getBarPolygon(double key, double value) const +QPolygonF QCPBars::getBarPolygon( double key, double value ) const { QPolygonF result; - double baseValue = getBaseValue(key, value >= 0); - result << coordsToPixels(key-mWidth*0.5, baseValue); - result << coordsToPixels(key-mWidth*0.5, baseValue+value); - result << coordsToPixels(key+mWidth*0.5, baseValue+value); - result << coordsToPixels(key+mWidth*0.5, baseValue); + double baseValue = getBaseValue( key, value >= 0 ); + result << coordsToPixels( key - mWidth * 0.5, baseValue ); + result << coordsToPixels( key - mWidth * 0.5, baseValue + value ); + result << coordsToPixels( key + mWidth * 0.5, baseValue + value ); + result << coordsToPixels( key + mWidth * 0.5, baseValue ); return result; } /*! \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 0-value upwards, negative are stacked below 0-value 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::getBaseValue(double key, bool positive) const +double QCPBars::getBaseValue( double key, bool positive ) const { - if (mBarBelow) + if( mBarBelow ) { double max = 0; // find bars of mBarBelow that are approximately at key and find largest one: - QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1); - QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1); - while (it != itEnd) + QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound( key - mWidth * 0.1 ); + QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound( key + mWidth * 0.1 ); + while( it != itEnd ) { - if ((positive && it.value().value > max) || - (!positive && it.value().value < max)) + 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()->getBaseValue(key, positive); - } else + return max + mBarBelow.data()->getBaseValue( key, positive ); + } + else return 0; } @@ -17848,33 +18646,36 @@ double QCPBars::getBaseValue(double key, bool positive) const Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently below lower and 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) +void QCPBars::connectBars( QCPBars* lower, QCPBars* upper ) { - if (!lower && !upper) return; - - if (!lower) // disconnect upper at bottom + if( !lower && !upper ) + return; + + if( !lower ) // disconnect upper at bottom { // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == 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 + } + else if( !upper ) // disconnect lower at top { // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) + if( lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower ) lower->mBarAbove.data()->mBarBelow = 0; lower->mBarAbove = 0; - } else // connect lower and upper + } + else // connect lower and upper { // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == 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) + if( upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper ) upper->mBarBelow.data()->mBarAbove = 0; lower->mBarAbove = upper; upper->mBarBelow = lower; @@ -17882,59 +18683,61 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) } /* inherits documentation from base class */ -QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +QCPRange QCPBars::getKeyRange( bool& foundRange, SignDomain inSignDomain ) const { QCPRange range; bool haveLower = false; bool haveUpper = false; - + double current; - double barWidthHalf = mWidth*0.5; + double barWidthHalf = mWidth * 0.5; QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0)) + if( inSignDomain == sdBoth || ( inSignDomain == sdNegative && current + barWidthHalf < 0 ) || + ( inSignDomain == sdPositive && current - barWidthHalf > 0 ) ) { - if (current-barWidthHalf < range.lower || !haveLower) + if( current - barWidthHalf < range.lower || !haveLower ) { - range.lower = current-barWidthHalf; + range.lower = current - barWidthHalf; haveLower = true; } - if (current+barWidthHalf > range.upper || !haveUpper) + if( current + barWidthHalf > range.upper || !haveUpper ) { - range.upper = current+barWidthHalf; + range.upper = current + barWidthHalf; haveUpper = true; } } ++it; } - + foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ -QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const +QCPRange QCPBars::getValueRange( bool& foundRange, SignDomain inSignDomain ) const { QCPRange range; - bool haveLower = true; // set to true, because 0 should always be visible in bar charts - bool haveUpper = true; // set to true, because 0 should always be visible in bar charts - + bool haveLower = true; // set to true, because 0 should always be visible in bar charts + bool haveUpper = true; // set to true, because 0 should always be visible in bar charts + double current; - + QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) + while( it != mData->constEnd() ) { - current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0); - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + current = it.value().value + getBaseValue( it.value().key, it.value().value >= 0 ); + if( inSignDomain == sdBoth || ( inSignDomain == sdNegative && current < 0 ) || + ( inSignDomain == sdPositive && current > 0 ) ) { - if (current < range.lower || !haveLower) + if( current < range.lower || !haveLower ) { range.lower = current; haveLower = true; } - if (current > range.upper || !haveUpper) + if( current > range.upper || !haveUpper ) { range.upper = current; haveUpper = true; @@ -17942,12 +18745,11 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const } ++it; } - - foundRange = true; // return true because bar charts always have the 0-line visible + + foundRange = true; // return true because bar charts always have the 0-line visible return range; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBox //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -17956,7 +18758,7 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const \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 @@ -17964,34 +18766,34 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const \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 (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) - + Usually, you first create an instance: \code QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode @@ -18010,36 +18812,36 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const 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) +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); + 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) +void QCPStatisticalBox::setKey( double key ) { mKey = key; } @@ -18047,10 +18849,10 @@ void QCPStatisticalBox::setKey(double 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) +void QCPStatisticalBox::setMinimum( double value ) { mMinimum = value; } @@ -18059,10 +18861,10 @@ void QCPStatisticalBox::setMinimum(double 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) +void QCPStatisticalBox::setLowerQuartile( double value ) { mLowerQuartile = value; } @@ -18071,10 +18873,10 @@ void QCPStatisticalBox::setLowerQuartile(double 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) +void QCPStatisticalBox::setMedian( double value ) { mMedian = value; } @@ -18083,10 +18885,10 @@ void QCPStatisticalBox::setMedian(double 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) +void QCPStatisticalBox::setUpperQuartile( double value ) { mUpperQuartile = value; } @@ -18094,10 +18896,10 @@ void QCPStatisticalBox::setUpperQuartile(double 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) +void QCPStatisticalBox::setMaximum( double value ) { mMaximum = value; } @@ -18106,58 +18908,63 @@ void QCPStatisticalBox::setMaximum(double 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) +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) +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); + 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) +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) +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) +void QCPStatisticalBox::setWhiskerPen( const QPen& pen ) { mWhiskerPen = pen; } @@ -18165,10 +18972,10 @@ void QCPStatisticalBox::setWhiskerPen(const QPen &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) +void QCPStatisticalBox::setWhiskerBarPen( const QPen& pen ) { mWhiskerBarPen = pen; } @@ -18176,17 +18983,17 @@ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) /*! Sets the pen used for drawing the median indicator line inside the statistical box. */ -void QCPStatisticalBox::setMedianPen(const QPen &pen) +void QCPStatisticalBox::setMedianPen( const QPen& pen ) { mMedianPen = pen; } /*! Sets the appearance of the outlier data points. - + \see setOutliers */ -void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) +void QCPStatisticalBox::setOutlierStyle( const QCPScatterStyle& style ) { mOutlierStyle = style; } @@ -18194,169 +19001,182 @@ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) /* inherits documentation from base class */ void QCPStatisticalBox::clearData() { - setOutliers(QVector()); - setKey(0); - setMinimum(0); - setLowerQuartile(0); - setMedian(0); - setUpperQuartile(0); - setMaximum(0); + 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 +double QCPStatisticalBox::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) + 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); + 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; - + 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)); + 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) +void QCPStatisticalBox::draw( QCPPainter* painter ) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if( !mKeyAxis || !mValueAxis ) + { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } - // check data validity if flag set: +// 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->setClipRect( quartileBox, Qt::IntersectClip ); + drawMedian( painter ); painter->restore(); - - drawWhiskers(painter); - drawOutliers(painter); + + drawWhiskers( painter ); + drawOutliers( painter ); } /* inherits documentation from base class */ -void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +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); + 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 +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) + 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 +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); + 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 +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); + 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 +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); + if( mKey - mWidth * 0.5 > 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; @@ -18368,10 +19188,10 @@ QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomai } /* inherits documentation from base class */ -QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const +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); + 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: @@ -18379,57 +19199,56 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom bool haveLower = false; double upper = 0; double lower = 0; - for (int i=0; i 0) || - (inSignDomain == sdBoth)) + if( ( inSignDomain == sdNegative && values.at( i ) < 0 ) || ( inSignDomain == sdPositive && values.at( i ) > 0 ) || + ( inSignDomain == sdBoth ) ) { - if (values.at(i) > upper || !haveUpper) + if( values.at( i ) > upper || !haveUpper ) { - upper = values.at(i); + upper = values.at( i ); haveUpper = true; } - if (values.at(i) < lower || !haveLower) + if( values.at( i ) < lower || !haveLower ) { - lower = values.at(i); + lower = values.at( i ); haveLower = true; } } } // return the bounds if we found some sensible values: - if (haveLower && haveUpper) + if( haveLower && haveUpper ) { foundRange = true; - return QCPRange(lower, upper); - } else // might happen if all values are in other sign domain + 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, @@ -18445,7 +19264,7 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom /* 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). */ @@ -18456,37 +19275,33 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom 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) +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); + setSize( keySize, valueSize ); + fill( 0 ); } QCPColorMapData::~QCPColorMapData() { - if (mData) + 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) +QCPColorMapData::QCPColorMapData( const QCPColorMapData& other ) + : mKeySize( 0 ), mValueSize( 0 ), mIsEmpty( true ), mData( 0 ), mDataModified( true ) { *this = other; } @@ -18494,16 +19309,16 @@ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : /*! Overwrites this color map data instance with the data stored in \a other. */ -QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) +QCPColorMapData& QCPColorMapData::operator=( const QCPColorMapData& other ) { - if (&other != this) + 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); + setSize( keySize, valueSize ); + setRange( other.keyRange(), other.valueRange() ); + if( !mIsEmpty ) + memcpy( mData, other.mData, sizeof( mData[0] ) * keySize * valueSize ); mDataBounds = other.mDataBounds; mDataModified = true; } @@ -18511,21 +19326,22 @@ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) } /* undocumented getter */ -double QCPColorMapData::data(double key, double value) +double QCPColorMapData::data( double key, double value ) { - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (1.0-(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]; + int keyCell = ( key - mKeyRange.lower ) / ( mKeyRange.upper - mKeyRange.lower ) * ( mKeySize - 1 ) + 0.5; + int valueCell = + ( 1.0 - ( 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) +double QCPColorMapData::cell( int keyIndex, int valueIndex ) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - return mData[valueIndex*mKeySize + keyIndex]; + if( keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize ) + return mData[valueIndex * mKeySize + keyIndex]; else return 0; } @@ -18536,35 +19352,41 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) 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) +void QCPColorMapData::setSize( int keySize, int valueSize ) { - if (keySize != mKeySize || valueSize != mValueSize) + if( keySize != mKeySize || valueSize != mValueSize ) { mKeySize = keySize; mValueSize = valueSize; - if (mData) + if( mData ) delete[] mData; mIsEmpty = mKeySize == 0 || mValueSize == 0; - if (!mIsEmpty) + if( !mIsEmpty ) { #ifdef __EXCEPTIONS - try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message + try + { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif - mData = new double[mKeySize*mValueSize]; + mData = new double[mKeySize * mValueSize]; #ifdef __EXCEPTIONS - } catch (...) { mData = 0; } + } + catch( ... ) + { + mData = 0; + } #endif - if (mData) - fill(0); + if( mData ) + fill( 0 ); else - qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; - } else + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*" << mValueSize; + } + else mData = 0; mDataModified = true; } @@ -18575,14 +19397,14 @@ void QCPColorMapData::setSize(int keySize, int valueSize) 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) +void QCPColorMapData::setKeySize( int keySize ) { - setSize(keySize, mValueSize); + setSize( keySize, mValueSize ); } /*! @@ -18590,43 +19412,43 @@ void QCPColorMapData::setKeySize(int keySize) 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) +void QCPColorMapData::setValueSize( int valueSize ) { - setSize(mKeySize, 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) +void QCPColorMapData::setRange( const QCPRange& keyRange, const QCPRange& valueRange ) { - setKeyRange(keyRange); - setValueRange(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) +void QCPColorMapData::setKeyRange( const QCPRange& keyRange ) { mKeyRange = keyRange; } @@ -18634,14 +19456,14 @@ void QCPColorMapData::setKeyRange(const QCPRange &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) +void QCPColorMapData::setValueRange( const QCPRange& valueRange ) { mValueRange = valueRange; } @@ -18649,21 +19471,21 @@ void QCPColorMapData::setValueRange(const QCPRange &valueRange) /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. - + \see setCell, setRange */ -void QCPColorMapData::setData(double key, double value, double z) +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) + 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) + mData[valueCell * mKeySize + keyCell] = z; + if( z < mDataBounds.lower ) mDataBounds.lower = z; - if (z > mDataBounds.upper) + if( z > mDataBounds.upper ) mDataBounds.upper = z; - mDataModified = true; + mDataModified = true; } } @@ -18671,51 +19493,51 @@ void QCPColorMapData::setData(double key, double value, double z) 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) +void QCPColorMapData::setCell( int keyIndex, int valueIndex, double z ) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + if( keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize ) { - mData[valueIndex*mKeySize + keyIndex] = z; - if (z < mDataBounds.lower) + mData[valueIndex * mKeySize + keyIndex] = z; + if( z < mDataBounds.lower ) mDataBounds.lower = z; - if (z > mDataBounds.upper) + if( z > mDataBounds.upper ) mDataBounds.upper = z; - mDataModified = true; + 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) + if( mKeySize > 0 && mValueSize > 0 ) { double minHeight = mData[0]; double maxHeight = mData[0]; - const int dataCount = mValueSize*mKeySize; - for (int i=0; i maxHeight) + if( mData[i] > maxHeight ) maxHeight = mData[i]; - if (mData[i] < minHeight) + if( mData[i] < minHeight ) minHeight = mData[i]; } mDataBounds.lower = minHeight; @@ -18725,64 +19547,63 @@ void QCPColorMapData::recalculateDataBounds() /*! Frees the internal data memory. - + This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { - setSize(0, 0); + setSize( 0, 0 ); } /*! Sets all cells to the value \a z. */ -void QCPColorMapData::fill(double z) +void QCPColorMapData::fill( double z ) { - const int dataCount = mValueSize*mKeySize; - for (int i=0; ixAxis, customPlot->yAxis);\endcode @@ -18851,7 +19672,7 @@ void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, dou customPlot->rescaleAxes(); customPlot->replot(); \endcode - + \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 @@ -18862,10 +19683,10 @@ void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, dou /* start documentation of inline functions */ /*! \fn QCPColorMapData *QCPColorMap::data() const - + Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to modify data points (cells) and the color map key/value range. - + \see setData */ @@ -18874,23 +19695,23 @@ void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, dou /* start documentation of signals */ /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange); - + This signal is emitted when the data range changes. - + \see setDataRange */ /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the data scale type changes. - + \see setDataScaleType */ /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient); - + This signal is emitted when the gradient changes. - + \see setGradient */ @@ -18898,17 +19719,17 @@ void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, dou /*! Constructs a color map with the specified \a keyAxis and \a valueAxis. - + The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the color map. */ -QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mDataScaleType(QCPAxis::stLinear), - mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))), - mInterpolate(true), - mTightBoundary(false), - mMapImageInvalidated(true) +QCPColorMap::QCPColorMap( QCPAxis* keyAxis, QCPAxis* valueAxis ) + : QCPAbstractPlottable( keyAxis, valueAxis ), + mDataScaleType( QCPAxis::stLinear ), + mMapData( new QCPColorMapData( 10, 10, QCPRange( 0, 5 ), QCPRange( 0, 5 ) ) ), + mInterpolate( true ), + mTightBoundary( false ), + mMapImageInvalidated( true ) { } @@ -18919,17 +19740,18 @@ QCPColorMap::~QCPColorMap() /*! Replaces the current \ref data with the provided \a data. - + If \a copy is set to true, the \a data object will only be copied. if false, the color map takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ -void QCPColorMap::setData(QCPColorMapData *data, bool copy) +void QCPColorMap::setData( QCPColorMapData* data, bool copy ) { - if (copy) + if( copy ) { *mMapData = *data; - } else + } + else { delete mMapData; mMapData = data; @@ -18940,70 +19762,71 @@ void QCPColorMap::setData(QCPColorMapData *data, bool copy) /*! 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) +void QCPColorMap::setDataRange( const QCPRange& dataRange ) { - if (!QCPRange::validRange(dataRange)) return; - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + if( !QCPRange::validRange( dataRange ) ) + return; + if( mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper ) { - if (mDataScaleType == QCPAxis::stLogarithmic) + if( mDataScaleType == QCPAxis::stLogarithmic ) mDataRange = dataRange.sanitizedForLogScale(); else mDataRange = dataRange.sanitizedForLinScale(); mMapImageInvalidated = true; - emit dataRangeChanged(mDataRange); + 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) +void QCPColorMap::setDataScaleType( QCPAxis::ScaleType scaleType ) { - if (mDataScaleType != scaleType) + if( mDataScaleType != scaleType ) { mDataScaleType = scaleType; mMapImageInvalidated = true; - emit dataScaleTypeChanged(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); + 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) +void QCPColorMap::setGradient( const QCPColorGradient& gradient ) { - if (mGradient != gradient) + if( mGradient != gradient ) { mGradient = gradient; mMapImageInvalidated = true; - emit gradientChanged(mGradient); + 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) +void QCPColorMap::setInterpolate( bool enabled ) { mInterpolate = enabled; } @@ -19011,56 +19834,64 @@ void QCPColorMap::setInterpolate(bool enabled) /*! 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) +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) +void QCPColorMap::setColorScale( QCPColorScale* colorScale ) { - if (mColorScale) // unconnect signals from old color scale + 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))); + 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 + 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))); + 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 ) ) ); } } @@ -19068,7 +19899,7 @@ void QCPColorMap::setColorScale(QCPColorScale *colorScale) 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 @@ -19081,40 +19912,41 @@ void QCPColorMap::setColorScale(QCPColorScale *colorScale) 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) +void QCPColorMap::rescaleDataRange( bool recalculateDataBounds ) { - if (recalculateDataBounds) + if( recalculateDataBounds ) mMapData->recalculateDataBounds(); - setDataRange(mMapData->dataBounds()); + 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) +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 + 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); + 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 ); } } @@ -19128,118 +19960,139 @@ void QCPColorMap::clearData() } /* inherits documentation from base class */ -double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPColorMap::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) + 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; + 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). */ void QCPColorMap::updateMapImage() { - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) return; - + QCPAxis* keyAxis = mKeyAxis.data(); + if( !keyAxis ) + return; + // resize mMapImage to correct dimensions, according to key/value axes orientation: - if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize())) - mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32); - else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize())) - mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32); - + if( keyAxis->orientation() == Qt::Horizontal && + ( mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize() ) ) + mMapImage = QImage( QSize( mMapData->keySize(), mMapData->valueSize() ), QImage::Format_RGB32 ); + else if( keyAxis->orientation() == Qt::Vertical && + ( mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize() ) ) + mMapImage = QImage( QSize( mMapData->valueSize(), mMapData->keySize() ), QImage::Format_RGB32 ); + const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); - const double *rawData = mMapData->mData; - - if (keyAxis->orientation() == Qt::Horizontal) + const double* rawData = mMapData->mData; + + if( keyAxis->orientation() == Qt::Horizontal ) { const int lineCount = valueSize; const int rowCount = keySize; - for (int line=0; line(mMapImage.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); + QRgb* pixels = reinterpret_cast( + mMapImage.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 + } + else // keyAxis->orientation() == Qt::Vertical { const int lineCount = keySize; const int rowCount = valueSize; - for (int line=0; line(mMapImage.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); + QRgb* pixels = reinterpret_cast( + mMapImage.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 ); } } - + mMapData->mDataModified = false; mMapImageInvalidated = false; } /* inherits documentation from base class */ -void QCPColorMap::draw(QCPPainter *painter) +void QCPColorMap::draw( QCPPainter* painter ) { - if (mMapData->isEmpty()) return; - if (!mKeyAxis || !mValueAxis) return; - applyDefaultAntialiasingHint(painter); - - if (mMapData->mDataModified || mMapImageInvalidated) + if( mMapData->isEmpty() ) + return; + if( !mKeyAxis || !mValueAxis ) + return; + applyDefaultAntialiasingHint( painter ); + + if( mMapData->mDataModified || mMapImageInvalidated ) updateMapImage(); - + double halfSampleKey = 0; double halfSampleValue = 0; - if (mMapData->keySize() > 1) - halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1); - QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue), - coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue)); + if( mMapData->keySize() > 1 ) + halfSampleKey = 0.5 * mMapData->keyRange().size() / (double)( mMapData->keySize() - 1 ); + if( mMapData->valueSize() > 1 ) + halfSampleValue = 0.5 * mMapData->valueRange().size() / (double)( mMapData->valueSize() - 1 ); + QRectF imageRect( + coordsToPixels( mMapData->keyRange().lower - halfSampleKey, mMapData->valueRange().lower - halfSampleValue ), + coordsToPixels( mMapData->keyRange().upper + halfSampleKey, mMapData->valueRange().upper + halfSampleValue ) ); imageRect = imageRect.normalized(); - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform); - painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); + bool mirrorX = ( keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis() )->rangeReversed(); + bool mirrorY = ( valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis() )->rangeReversed(); + bool smoothBackup = painter->renderHints().testFlag( QPainter::SmoothPixmapTransform ); + painter->setRenderHint( QPainter::SmoothPixmapTransform, mInterpolate ); QRegion clipBackup; - if (mTightBoundary) + if( mTightBoundary ) { clipBackup = painter->clipRegion(); - painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip); + painter->setClipRect( QRectF( coordsToPixels( mMapData->keyRange().lower, mMapData->valueRange().lower ), + coordsToPixels( mMapData->keyRange().upper, mMapData->valueRange().upper ) ) + .normalized(), + Qt::IntersectClip ); } - painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); - if (mTightBoundary) - painter->setClipRegion(clipBackup); - painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); + painter->drawImage( imageRect, mMapImage.mirrored( mirrorX, mirrorY ) ); + if( mTightBoundary ) + painter->setClipRegion( clipBackup ); + painter->setRenderHint( QPainter::SmoothPixmapTransform, smoothBackup ); } /* inherits documentation from base class */ -void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +void QCPColorMap::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const { - applyDefaultAntialiasingHint(painter); + applyDefaultAntialiasingHint( painter ); // draw map thumbnail: - if (!mLegendIcon.isNull()) + 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); + 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: @@ -19250,50 +20103,51 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const } /* inherits documentation from base class */ -QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +QCPRange QCPColorMap::getKeyRange( bool& foundRange, SignDomain inSignDomain ) const { foundRange = true; QCPRange result = mMapData->keyRange(); result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) + 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) + 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) + } + 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) + 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 +QCPRange QCPColorMap::getValueRange( bool& foundRange, SignDomain inSignDomain ) const { foundRange = true; QCPRange result = mMapData->valueRange(); result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) + 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) + 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) + } + 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) + 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; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19301,26 +20155,25 @@ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) c /*! \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." + \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("point1")), - point2(createPosition("point2")) +QCPItemStraightLine::QCPItemStraightLine( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), point1( createPosition( "point1" ) ), point2( createPosition( "point2" ) ) { - point1->setCoords(0, 0); - point2->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + point1->setCoords( 0, 0 ); + point2->setCoords( 1, 1 ); + + setPen( QPen( Qt::black ) ); + setSelectedPen( QPen( Qt::blue, 2 ) ); } QCPItemStraightLine::~QCPItemStraightLine() @@ -19329,47 +20182,49 @@ QCPItemStraightLine::~QCPItemStraightLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ -void QCPItemStraightLine::setPen(const QPen &pen) +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) +void QCPItemStraightLine::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } /* inherits documentation from base class */ -double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemStraightLine::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); + + return distToStraightLine( QVector2D( point1->pixelPoint() ), + QVector2D( point2->pixelPoint() - point1->pixelPoint() ), QVector2D( pos ) ); } /* inherits documentation from base class */ -void QCPItemStraightLine::draw(QCPPainter *painter) +void QCPItemStraightLine::draw( QCPPainter* painter ) { - QVector2D start(point1->pixelPoint()); - QVector2D end(point2->pixelPoint()); + 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)); + QLineF line = + getRectClippedStraightLine( start, end - start, clipRect().adjusted( -clipPad, -clipPad, clipPad, clipPad ) ); // paint visible segment, if existent: - if (!line.isNull()) + if( !line.isNull() ) { - painter->setPen(mainPen()); - painter->drawLine(line); + painter->setPen( mainPen() ); + painter->drawLine( line ); } } @@ -19377,95 +20232,105 @@ void QCPItemStraightLine::draw(QCPPainter *painter) 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 +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(); + 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 +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) + if( vec.x() == 0 && vec.y() == 0 ) return result; - if (qFuzzyIsNull(vec.x())) // line is vertical + 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 + 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 + 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)); + 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)); + 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)); + 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)); - + 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) + if( pointVectors.size() == 2 ) { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else 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: + // 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) + double distSqr = ( pointVectors.at( i ) - pointVectors.at( k ) ).lengthSquared(); + if( distSqr > distSqrMax ) { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); + pv1 = pointVectors.at( i ); + pv2 = pointVectors.at( k ); distSqrMax = distSqr; } } } - result.setPoints(pv1.toPointF(), pv2.toPointF()); + result.setPoints( pv1.toPointF(), pv2.toPointF() ); } } return result; @@ -19481,7 +20346,6 @@ QPen QCPItemStraightLine::mainPen() const return mSelected ? mSelectedPen : mPen; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemLine //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19492,25 +20356,23 @@ QPen QCPItemStraightLine::mainPen() const \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("start")), - end(createPosition("end")) +QCPItemLine::QCPItemLine( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), start( createPosition( "start" ) ), end( createPosition( "end" ) ) { - start->setCoords(0, 0); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords( 0, 0 ); + end->setCoords( 1, 1 ); + + setPen( QPen( Qt::black ) ); + setSelectedPen( QPen( Qt::blue, 2 ) ); } QCPItemLine::~QCPItemLine() @@ -19519,81 +20381,81 @@ QCPItemLine::~QCPItemLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ -void QCPItemLine::setPen(const QPen &pen) +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) +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) +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) +void QCPItemLine::setTail( const QCPLineEnding& tail ) { mTail = tail; } /* inherits documentation from base class */ -double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemLine::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); + + return qSqrt( distSqrToLine( start->pixelPoint(), end->pixelPoint(), pos ) ); } /* inherits documentation from base class */ -void QCPItemLine::draw(QCPPainter *painter) +void QCPItemLine::draw( QCPPainter* painter ) { - QVector2D startVec(start->pixelPoint()); - QVector2D endVec(end->pixelPoint()); - if (startVec.toPoint() == endVec.toPoint()) + 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)); + 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()) + 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); + 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 ); } } @@ -19601,98 +20463,100 @@ void QCPItemLine::draw(QCPPainter *painter) 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 +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()); - + 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; + QVector2D vec = end - start; double bx, by; double gamma, mu; QLineF result; QList pointVectors; - if (!qFuzzyIsNull(vec.y())) // line is not horizontal + 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) + 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)); + 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) + 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)); + 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 + 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) + 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)); + 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) + 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)); + 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); - + + if( containsStart ) + pointVectors.append( start ); + if( containsEnd ) + pointVectors.append( end ); + // evaluate points: - if (pointVectors.size() == 2) + if( pointVectors.size() == 2 ) { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else 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: + // 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) + double distSqr = ( pointVectors.at( i ) - pointVectors.at( k ) ).lengthSquared(); + if( distSqr > distSqrMax ) { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); + pv1 = pointVectors.at( i ); + pv2 = pointVectors.at( k ); distSqrMax = distSqr; } } } - result.setPoints(pv1.toPointF(), pv2.toPointF()); + result.setPoints( pv1.toPointF(), pv2.toPointF() ); } return result; } @@ -19707,7 +20571,6 @@ QPen QCPItemLine::mainPen() const return mSelected ? mSelectedPen : mPen; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemCurve //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19720,10 +20583,10 @@ QPen QCPItemLine::mainPen() const 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. @@ -19731,23 +20594,23 @@ QPen QCPItemLine::mainPen() const /*! 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("start")), - startDir(createPosition("startDir")), - endDir(createPosition("endDir")), - end(createPosition("end")) +QCPItemCurve::QCPItemCurve( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + start( createPosition( "start" ) ), + startDir( createPosition( "startDir" ) ), + endDir( createPosition( "endDir" ) ), + end( createPosition( "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)); + 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() @@ -19756,103 +20619,103 @@ QCPItemCurve::~QCPItemCurve() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ -void QCPItemCurve::setPen(const QPen &pen) +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) +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) +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) +void QCPItemCurve::setTail( const QCPLineEnding& tail ) { mTail = tail; } /* inherits documentation from base class */ -double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemCurve::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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); - + 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 + QPointF startVec( start->pixelPoint() ); + 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); + 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 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)) + 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); + 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 ); } } @@ -19866,7 +20729,6 @@ QPen QCPItemCurve::mainPen() const return mSelected ? mSelectedPen : mPen; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19881,27 +20743,27 @@ QPen QCPItemCurve::mainPen() const /*! 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("topLeft")), - bottomRight(createPosition("bottomRight")), - top(createAnchor("top", aiTop)), - topRight(createAnchor("topRight", aiTopRight)), - right(createAnchor("right", aiRight)), - bottom(createAnchor("bottom", aiBottom)), - bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), - left(createAnchor("left", aiLeft)) +QCPItemRect::QCPItemRect( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + topLeft( createPosition( "topLeft" ) ), + bottomRight( createPosition( "bottomRight" ) ), + top( createAnchor( "top", aiTop ) ), + topRight( createAnchor( "topRight", aiTopRight ) ), + right( createAnchor( "right", aiRight ) ), + bottom( createAnchor( "bottom", aiBottom ) ), + bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), + left( createAnchor( "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); + 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() @@ -19910,20 +20772,20 @@ 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) +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) +void QCPItemRect::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } @@ -19931,10 +20793,10 @@ void QCPItemRect::setSelectedPen(const QPen &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) +void QCPItemRect::setBrush( const QBrush& brush ) { mBrush = brush; } @@ -19942,58 +20804,64 @@ void QCPItemRect::setBrush(const QBrush &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) +void QCPItemRect::setSelectedBrush( const QBrush& brush ) { mSelectedBrush = brush; } /* inherits documentation from base class */ -double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemRect::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); + + QRectF rect = QRectF( topLeft->pixelPoint(), bottomRight->pixelPoint() ).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); + return rectSelectTest( rect, pos, filledRect ); } /* inherits documentation from base class */ -void QCPItemRect::draw(QCPPainter *painter) +void QCPItemRect::draw( QCPPainter* painter ) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) + if( p1.toPoint() == p2.toPoint() ) return; - QRectF rect = QRectF(p1, p2).normalized(); + 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 + 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); + painter->setPen( mainPen() ); + painter->setBrush( mainBrush() ); + painter->drawRect( rect ); } } /* inherits documentation from base class */ -QPointF QCPItemRect::anchorPixelPoint(int anchorId) const +QPointF QCPItemRect::anchorPixelPoint( int anchorId ) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) + 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; + 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(); } @@ -20018,7 +20886,6 @@ QBrush QCPItemRect::mainBrush() const return mSelected ? mSelectedBrush : mBrush; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -20030,43 +20897,43 @@ QBrush QCPItemRect::mainBrush() const 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("position")), - topLeft(createAnchor("topLeft", aiTopLeft)), - top(createAnchor("top", aiTop)), - topRight(createAnchor("topRight", aiTopRight)), - right(createAnchor("right", aiRight)), - bottomRight(createAnchor("bottomRight", aiBottomRight)), - bottom(createAnchor("bottom", aiBottom)), - bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), - left(createAnchor("left", aiLeft)) +QCPItemText::QCPItemText( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + position( createPosition( "position" ) ), + topLeft( createAnchor( "topLeft", aiTopLeft ) ), + top( createAnchor( "top", aiTop ) ), + topRight( createAnchor( "topRight", aiTopRight ) ), + right( createAnchor( "right", aiRight ) ), + bottomRight( createAnchor( "bottomRight", aiBottomRight ) ), + bottom( createAnchor( "bottom", aiBottom ) ), + bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), + left( createAnchor( "left", aiLeft ) ) { - position->setCoords(0, 0); - - setRotation(0); - setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); - setPositionAlignment(Qt::AlignCenter); - setText("text"); - - setPen(Qt::NoPen); - setSelectedPen(Qt::NoPen); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setColor(Qt::black); - setSelectedColor(Qt::blue); + position->setCoords( 0, 0 ); + + setRotation( 0 ); + setTextAlignment( Qt::AlignTop | Qt::AlignHCenter ); + setPositionAlignment( Qt::AlignCenter ); + setText( "text" ); + + setPen( Qt::NoPen ); + setSelectedPen( Qt::NoPen ); + setBrush( Qt::NoBrush ); + setSelectedBrush( Qt::NoBrush ); + setColor( Qt::black ); + setSelectedColor( Qt::blue ); } QCPItemText::~QCPItemText() @@ -20076,7 +20943,7 @@ QCPItemText::~QCPItemText() /*! Sets the color of the text. */ -void QCPItemText::setColor(const QColor &color) +void QCPItemText::setColor( const QColor& color ) { mColor = color; } @@ -20084,7 +20951,7 @@ void QCPItemText::setColor(const QColor &color) /*! Sets the color of the text that will be used when the item is selected. */ -void QCPItemText::setSelectedColor(const QColor &color) +void QCPItemText::setSelectedColor( const QColor& color ) { mSelectedColor = color; } @@ -20092,10 +20959,10 @@ void QCPItemText::setSelectedColor(const QColor &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) +void QCPItemText::setPen( const QPen& pen ) { mPen = pen; } @@ -20103,10 +20970,10 @@ void QCPItemText::setPen(const QPen &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) +void QCPItemText::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } @@ -20114,10 +20981,10 @@ void QCPItemText::setSelectedPen(const QPen &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) +void QCPItemText::setBrush( const QBrush& brush ) { mBrush = brush; } @@ -20125,30 +20992,30 @@ void QCPItemText::setBrush(const QBrush &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) +void QCPItemText::setSelectedBrush( const QBrush& brush ) { mSelectedBrush = brush; } /*! Sets the font of the text. - + \see setSelectedFont, setColor */ -void QCPItemText::setFont(const QFont &font) +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) +void QCPItemText::setSelectedFont( const QFont& font ) { mSelectedFont = font; } @@ -20156,35 +21023,36 @@ void QCPItemText::setSelectedFont(const QFont &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) +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) +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). + 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) +void QCPItemText::setTextAlignment( Qt::Alignment alignment ) { mTextAlignment = alignment; } @@ -20193,7 +21061,7 @@ void QCPItemText::setTextAlignment(Qt::Alignment 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) +void QCPItemText::setRotation( double degrees ) { mRotation = degrees; } @@ -20202,122 +21070,132 @@ void QCPItemText::setRotation(double 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) +void QCPItemText::setPadding( const QMargins& padding ) { mPadding = padding; } /* inherits documentation from base class */ -double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemText::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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()); + 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()); + 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); + return rectSelectTest( textBoxRect, rotatedPos, true ); } /* inherits documentation from base class */ -void QCPItemText::draw(QCPPainter *painter) +void QCPItemText::draw( QCPPainter* painter ) { - QPointF pos(position->pixelPoint()); + 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()); + 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()))) + 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->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->setPen( mainPen() ); + painter->setBrush( mainBrush() ); + painter->drawRect( textBoxRect ); } - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(mainColor())); - painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); + 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 +QPointF QCPItemText::anchorPixelPoint( int anchorId ) const { // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPoint()); + 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) + 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; + 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 +QPointF QCPItemText::getTextDrawPoint( const QPointF& pos, const QRectF& rect, Qt::Alignment positionAlignment ) const { - if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) + 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)) + + 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)) + if( positionAlignment.testFlag( Qt::AlignVCenter ) ) + result.ry() -= rect.height() / 2.0; + else if( positionAlignment.testFlag( Qt::AlignBottom ) ) result.ry() -= rect.height(); return result; } @@ -20362,7 +21240,6 @@ QBrush QCPItemText::mainBrush() const return mSelected ? mSelectedBrush : mBrush; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -20377,30 +21254,30 @@ QBrush QCPItemText::mainBrush() const /*! 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("topLeft")), - bottomRight(createPosition("bottomRight")), - topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)), - top(createAnchor("top", aiTop)), - topRightRim(createAnchor("topRightRim", aiTopRightRim)), - right(createAnchor("right", aiRight)), - bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)), - bottom(createAnchor("bottom", aiBottom)), - bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)), - left(createAnchor("left", aiLeft)), - center(createAnchor("center", aiCenter)) +QCPItemEllipse::QCPItemEllipse( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + topLeft( createPosition( "topLeft" ) ), + bottomRight( createPosition( "bottomRight" ) ), + topLeftRim( createAnchor( "topLeftRim", aiTopLeftRim ) ), + top( createAnchor( "top", aiTop ) ), + topRightRim( createAnchor( "topRightRim", aiTopRightRim ) ), + right( createAnchor( "right", aiRight ) ), + bottomRightRim( createAnchor( "bottomRightRim", aiBottomRightRim ) ), + bottom( createAnchor( "bottom", aiBottom ) ), + bottomLeftRim( createAnchor( "bottomLeftRim", aiBottomLeftRim ) ), + left( createAnchor( "left", aiLeft ) ), + center( createAnchor( "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); + 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() @@ -20409,20 +21286,20 @@ 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) +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) +void QCPItemEllipse::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } @@ -20430,10 +21307,10 @@ void QCPItemEllipse::setSelectedPen(const QPen &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) +void QCPItemEllipse::setBrush( const QBrush& brush ) { mBrush = brush; } @@ -20441,87 +21318,98 @@ void QCPItemEllipse::setBrush(const QBrush &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) +void QCPItemEllipse::setSelectedBrush( const QBrush& brush ) { mSelectedBrush = brush; } /* inherits documentation from base class */ -double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemEllipse::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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(); - + 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); + 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( 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; + 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) +void QCPItemEllipse::draw( QCPPainter* painter ) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) + 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 + 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()); + painter->setPen( mainPen() ); + painter->setBrush( mainBrush() ); #ifdef __EXCEPTIONS - try // drawEllipse sometimes throws exceptions if ellipse is too big + try // drawEllipse sometimes throws exceptions if ellipse is too big { #endif - painter->drawEllipse(ellipseRect); + painter->drawEllipse( ellipseRect ); #ifdef __EXCEPTIONS - } catch (...) + } + catch( ... ) { qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; - setVisible(false); + setVisible( false ); } #endif } } /* inherits documentation from base class */ -QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const +QPointF QCPItemEllipse::anchorPixelPoint( int anchorId ) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) + 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; + 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(); } @@ -20546,7 +21434,6 @@ QBrush QCPItemEllipse::mainBrush() const return mSelected ? mSelectedBrush : mBrush; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -20559,7 +21446,7 @@ QBrush QCPItemEllipse::mainBrush() const 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. @@ -20567,26 +21454,26 @@ QBrush QCPItemEllipse::mainBrush() const /*! 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("topLeft")), - bottomRight(createPosition("bottomRight")), - top(createAnchor("top", aiTop)), - topRight(createAnchor("topRight", aiTopRight)), - right(createAnchor("right", aiRight)), - bottom(createAnchor("bottom", aiBottom)), - bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), - left(createAnchor("left", aiLeft)) +QCPItemPixmap::QCPItemPixmap( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + topLeft( createPosition( "topLeft" ) ), + bottomRight( createPosition( "bottomRight" ) ), + top( createAnchor( "top", aiTop ) ), + topRight( createAnchor( "topRight", aiTopRight ) ), + right( createAnchor( "right", aiRight ) ), + bottom( createAnchor( "bottom", aiBottom ) ), + bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), + left( createAnchor( "left", aiLeft ) ) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(Qt::NoPen); - setSelectedPen(QPen(Qt::blue)); - setScaled(false, Qt::KeepAspectRatio); + topLeft->setCoords( 0, 1 ); + bottomRight->setCoords( 1, 0 ); + + setPen( Qt::NoPen ); + setSelectedPen( QPen( Qt::blue ) ); + setScaled( false, Qt::KeepAspectRatio ); } QCPItemPixmap::~QCPItemPixmap() @@ -20596,10 +21483,10 @@ QCPItemPixmap::~QCPItemPixmap() /*! Sets the pixmap that will be displayed. */ -void QCPItemPixmap::setPixmap(const QPixmap &pixmap) +void QCPItemPixmap::setPixmap( const QPixmap& pixmap ) { mPixmap = pixmap; - if (mPixmap.isNull()) + if( mPixmap.isNull() ) qDebug() << Q_FUNC_INFO << "pixmap is null"; } @@ -20607,7 +21494,7 @@ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) 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) +void QCPItemPixmap::setScaled( bool scaled, Qt::AspectRatioMode aspectRatioMode ) { mScaled = scaled; mAspectRatioMode = aspectRatioMode; @@ -20616,164 +21503,173 @@ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode) /*! Sets the pen that will be used to draw a border around the pixmap. - + \see setSelectedPen, setBrush */ -void QCPItemPixmap::setPen(const QPen &pen) +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) +void QCPItemPixmap::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } /* inherits documentation from base class */ -double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemPixmap::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - return rectSelectTest(getFinalRect(), pos, true); + + return rectSelectTest( getFinalRect(), pos, true ); } /* inherits documentation from base class */ -void QCPItemPixmap::draw(QCPPainter *painter) +void QCPItemPixmap::draw( QCPPainter* painter ) { bool flipHorz = false; bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); + 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())) + QRect boundingRect = rect.adjusted( -clipPad, -clipPad, clipPad, clipPad ); + if( boundingRect.intersects( clipRect() ) ) { - updateScaledPixmap(rect, flipHorz, flipVert); - painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + updateScaledPixmap( rect, flipHorz, flipVert ); + painter->drawPixmap( rect.topLeft(), mScaled ? mScaledPixmap : mPixmap ); QPen pen = mainPen(); - if (pen.style() != Qt::NoPen) + if( pen.style() != Qt::NoPen ) { - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawRect(rect); + painter->setPen( pen ); + painter->setBrush( Qt::NoBrush ); + painter->drawRect( rect ); } } } /* inherits documentation from base class */ -QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const +QPointF QCPItemPixmap::anchorPixelPoint( int anchorId ) const { bool flipHorz; bool flipVert; - QRect rect = getFinalRect(&flipHorz, &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) + 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;; + 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) +void QCPItemPixmap::updateScaledPixmap( QRect finalRect, bool flipHorz, bool flipVert ) { - if (mPixmap.isNull()) + if( mPixmap.isNull() ) return; - - if (mScaled) + + if( mScaled ) { - if (finalRect.isNull()) - finalRect = getFinalRect(&flipHorz, &flipVert); - if (finalRect.size() != mScaledPixmap.size()) + if( finalRect.isNull() ) + finalRect = getFinalRect( &flipHorz, &flipVert ); + if( finalRect.size() != mScaledPixmap.size() ) { - mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation); - if (flipHorz || flipVert) - mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); + mScaledPixmap = mPixmap.scaled( finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation ); + if( flipHorz || flipVert ) + mScaledPixmap = QPixmap::fromImage( mScaledPixmap.toImage().mirrored( flipHorz, flipVert ) ); } - } else if (!mScaledPixmap.isNull()) + } + else if( !mScaledPixmap.isNull() ) mScaledPixmap = QPixmap(); } /*! \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 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) + if( p1 == p2 ) + return QRect( p1, QSize( 0, 0 ) ); + if( mScaled ) { - QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); + QSize newSize = QSize( p2.x() - p1.x(), p2.y() - p1.y() ); QPoint topLeft = p1; - if (newSize.width() < 0) + if( newSize.width() < 0 ) { flipHorz = true; newSize.rwidth() *= -1; - topLeft.setX(p2.x()); + topLeft.setX( p2.x() ); } - if (newSize.height() < 0) + if( newSize.height() < 0 ) { flipVert = true; newSize.rheight() *= -1; - topLeft.setY(p2.y()); + topLeft.setY( p2.y() ); } QSize scaledSize = mPixmap.size(); - scaledSize.scale(newSize, mAspectRatioMode); - result = QRect(topLeft, scaledSize); - } else - { - result = QRect(p1, mPixmap.size()); + scaledSize.scale( newSize, mAspectRatioMode ); + result = QRect( topLeft, scaledSize ); } - if (flippedHorz) + else + { + result = QRect( p1, mPixmap.size() ); + } + if( flippedHorz ) *flippedHorz = flipHorz; - if (flippedVert) + if( flippedVert ) *flippedVert = flipVert; return result; } @@ -20788,7 +21684,6 @@ QPen QCPItemPixmap::mainPen() const return mSelected ? mSelectedPen : mPen; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -20804,19 +21699,19 @@ QPen QCPItemPixmap::mainPen() const 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 @@ -20825,24 +21720,22 @@ QPen QCPItemPixmap::mainPen() const /*! 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("position")), - mGraph(0) +QCPItemTracer::QCPItemTracer( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), position( createPosition( "position" ) ), mGraph( 0 ) { - position->setCoords(0, 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); + 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() @@ -20851,40 +21744,40 @@ 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) +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) +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) +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) +void QCPItemTracer::setSelectedBrush( const QBrush& brush ) { mSelectedBrush = brush; } @@ -20893,18 +21786,18 @@ void QCPItemTracer::setSelectedBrush(const QBrush &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) +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) +void QCPItemTracer::setStyle( QCPItemTracer::TracerStyle style ) { mStyle = style; } @@ -20912,26 +21805,28 @@ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle 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) +void QCPItemTracer::setGraph( QCPGraph* graph ) { - if (graph) + if( graph ) { - if (graph->parentPlot() == mParentPlot) + if( graph->parentPlot() == mParentPlot ) { - position->setType(QCPItemPosition::ptPlotCoords); - position->setAxes(graph->keyAxis(), graph->valueAxis()); + position->setType( QCPItemPosition::ptPlotCoords ); + position->setAxes( graph->keyAxis(), graph->valueAxis() ); mGraph = graph; updatePosition(); - } else + } + else qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; - } else + } + else { mGraph = 0; } @@ -20940,13 +21835,13 @@ void QCPItemTracer::setGraph(QCPGraph *graph) /*! 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) +void QCPItemTracer::setGraphKey( double key ) { mGraphKey = key; } @@ -20954,57 +21849,60 @@ void QCPItemTracer::setGraphKey(double 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) +void QCPItemTracer::setInterpolating( bool enabled ) { mInterpolating = enabled; } /* inherits documentation from base class */ -double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemTracer::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - QPointF center(position->pixelPoint()); - double w = mSize/2.0; + QPointF center( position->pixelPoint() ); + double w = mSize / 2.0; QRect clip = clipRect(); - switch (mStyle) + switch( mStyle ) { - case tsNone: return -1; + 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))); + 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))); + 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())) + if( clip.intersects( QRectF( center - QPointF( w, w ), center + QPointF( w, w ) ).toRect() ) ) { // distance to border: - double centerDist = QVector2D(center-pos).length(); + double centerDist = QVector2D( center - pos ).length(); double circleLine = w; - double result = qAbs(centerDist-circleLine); + 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( result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush && + mBrush.color().alpha() != 0 ) { - if (centerDist <= circleLine) - result = mParentPlot->selectionTolerance()*0.99; + if( centerDist <= circleLine ) + result = mParentPlot->selectionTolerance() * 0.99; } return result; } @@ -21012,11 +21910,11 @@ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVaria } case tsSquare: { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + if( clip.intersects( QRectF( center - QPointF( w, w ), center + QPointF( w, w ) ).toRect() ) ) { - QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); + 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); + return rectSelectTest( rect, pos, filledRect ); } break; } @@ -21025,47 +21923,48 @@ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVaria } /* inherits documentation from base class */ -void QCPItemTracer::draw(QCPPainter *painter) +void QCPItemTracer::draw( QCPPainter* painter ) { updatePosition(); - if (mStyle == tsNone) + if( mStyle == tsNone ) return; - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - QPointF center(position->pixelPoint()); - double w = mSize/2.0; + painter->setPen( mainPen() ); + painter->setBrush( mainBrush() ); + QPointF center( position->pixelPoint() ); + double w = mSize / 2.0; QRect clip = clipRect(); - switch (mStyle) + switch( mStyle ) { - case tsNone: return; + case tsNone: + return; case tsPlus: { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + 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))); + 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())); + 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); + 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))); + 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; } } @@ -21074,59 +21973,64 @@ void QCPItemTracer::draw(QCPPainter *painter) /*! 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( mGraph ) { - if (mParentPlot->hasPlottable(mGraph)) + if( mParentPlot->hasPlottable( mGraph ) ) { - if (mGraph->data()->size() > 1) + 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); + 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 it = mGraph->data()->lowerBound( mGraphKey ); + if( it != first ) // mGraphKey is somewhere between iterators { - QCPDataMap::const_iterator prevIt = it-1; - if (mInterpolating) + 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 + 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) + if( mGraphKey < ( prevIt.key() + it.key() ) * 0.5 ) it = prevIt; - position->setCoords(it.key(), it.value().value); + position->setCoords( it.key(), it.value().value ); } - } else // mGraphKey is exactly on first iterator - 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) + } + else if( mGraph->data()->size() == 1 ) { QCPDataMap::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it.key(), it.value().value); - } else + position->setCoords( it.key(), it.value().value ); + } + else qDebug() << Q_FUNC_INFO << "graph has no data"; - } else + } + else qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } } @@ -21151,7 +22055,6 @@ QBrush QCPItemTracer::mainBrush() const return mSelected ? mSelectedBrush : mBrush; } - //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -21164,36 +22067,36 @@ QBrush QCPItemTracer::mainBrush() const 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("left")), - right(createPosition("right")), - center(createAnchor("center", aiCenter)) +QCPItemBracket::QCPItemBracket( QCustomPlot* parentPlot ) + : QCPAbstractItem( parentPlot ), + left( createPosition( "left" ) ), + right( createPosition( "right" ) ), + center( createAnchor( "center", aiCenter ) ) { - left->setCoords(0, 0); - right->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setLength(8); - setStyle(bsCalligraphic); + left->setCoords( 0, 0 ); + right->setCoords( 1, 1 ); + + setPen( QPen( Qt::black ) ); + setSelectedPen( QPen( Qt::blue, 2 ) ); + setLength( 8 ); + setStyle( bsCalligraphic ); } QCPItemBracket::~QCPItemBracket() @@ -21202,24 +22105,24 @@ 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) +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) +void QCPItemBracket::setSelectedPen( const QPen& pen ) { mSelectedPen = pen; } @@ -21227,109 +22130,120 @@ void QCPItemBracket::setSelectedPen(const QPen &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) +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) +void QCPItemBracket::setStyle( QCPItemBracket::BracketStyle style ) { mStyle = style; } /* inherits documentation from base class */ -double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +double QCPItemBracket::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED( details ) + if( onlySelectable && !mSelectable ) return -1; - - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) + + 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; - - return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos)); + + QVector2D widthVec = ( rightVec - leftVec ) * 0.5f; + QVector2D lengthVec( -widthVec.y(), widthVec.x() ); + lengthVec = lengthVec.normalized() * mLength; + QVector2D centerVec = ( rightVec + leftVec ) * 0.5f - lengthVec; + + return qSqrt( distSqrToLine( ( centerVec - widthVec ).toPointF(), ( centerVec + widthVec ).toPointF(), pos ) ); } /* inherits documentation from base class */ -void QCPItemBracket::draw(QCPPainter *painter) +void QCPItemBracket::draw( QCPPainter* painter ) { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) + 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; + + 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())) + 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) + 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()); + 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); + 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); + 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); + 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); + 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())); + 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); + 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; } } @@ -21337,19 +22251,19 @@ void QCPItemBracket::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const +QPointF QCPItemBracket::anchorPixelPoint( int anchorId ) const { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - if (leftVec.toPoint() == rightVec.toPoint()) + 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) + + 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(); @@ -21365,6 +22279,5 @@ QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const */ QPen QCPItemBracket::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } - diff --git a/app/external/qcustomplot.h b/app/external/qcustomplot.h index 2ec78b0..de6d57f 100644 --- a/app/external/qcustomplot.h +++ b/app/external/qcustomplot.h @@ -45,13 +45,13 @@ #include #include #include -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) -# include -# include -# include +#if QT_VERSION < QT_VERSION_CHECK( 5, 0, 0 ) +#include +#include +#include #else -# include -# include +#include +#include #endif class QCPPainter; @@ -73,17 +73,15 @@ class QCPAbstractLegendItem; class QCPColorMap; class QCPColorScale; - /*! \file */ - // decl definitions for shared library compilation/usage: -#if defined(QCUSTOMPLOT_COMPILE_LIBRARY) -# define QCP_LIB_DECL Q_DECL_EXPORT -#elif defined(QCUSTOMPLOT_USE_LIBRARY) -# define QCP_LIB_DECL Q_DECL_IMPORT +#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 +#define QCP_LIB_DECL #endif /*! @@ -93,147 +91,209 @@ 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) +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) +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) +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) +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) +inline bool isInvalidData( double value ) { - return qIsNaN(value) || qIsInf(value); + return qIsNaN( value ) || qIsInf( value ); } /*! \internal \overload - + Checks two arguments instead of one. */ -inline bool isInvalidData(double value1, double value2) +inline bool isInvalidData( double value1, double value2 ) { - return isInvalidData(value1) || isInvalidData(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) +inline void setMarginValue( QMargins& margins, QCP::MarginSide side, int value ) { - switch (side) + 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; + 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) +inline int getMarginValue( const QMargins& margins, QCP::MarginSide side ) { - switch (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; + 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) +} // 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: + public: /*! Defines the shape used for scatter points. @@ -241,35 +301,58 @@ public: \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) - }; + 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); - + 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; } @@ -277,23 +360,22 @@ public: 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); + 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; + 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: + protected: // property members: double mSize; ScatterShape mShape; @@ -301,105 +383,110 @@ protected: QBrush mBrush; QPixmap mPixmap; QPainterPath mCustomPath; - + // non-property members: bool mPenDefined; }; -Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); - +Q_DECLARE_TYPEINFO( QCPScatterStyle, Q_MOVABLE_TYPE ); class QCP_LIB_DECL QCPPainter : public QPainter { Q_GADGET -public: + public: /*! - Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + 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; } + 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); + 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));} + 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: + + protected: // property members: PainterModes mModes; bool mIsAntialiasing; - + // non-property members: QStack mAntialiasingStack; }; -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) - +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) + 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); + public: + QCPLayer( QCustomPlot* parentPlot, const QString& layerName ); ~QCPLayer(); - + // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } + 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: + void setVisible( bool visible ); + + protected: // property members: - QCustomPlot *mParentPlot; + 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) - + void addChild( QCPLayerable* layerable, bool prepend ); + void removeChild( QCPLayerable* layerable ); + + private: + Q_DISABLE_COPY( QCPLayer ) + friend class QCustomPlot; friend class QCPLayerable; }; @@ -408,128 +495,146 @@ 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) + 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="", QCPLayerable *parentLayerable=0); + public: + QCPLayerable( QCustomPlot* plot, QString targetLayer = "", 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; } + 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); - + 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; - + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + // non-property methods: bool realVisibility() const; - -signals: - void layerChanged(QCPLayer *newLayer); - -protected: + + signals: + void layerChanged( QCPLayer* newLayer ); + + protected: // property members: bool mVisible; - QCustomPlot *mParentPlot; + QCustomPlot* mParentPlot; QPointer mParentLayerable; - QCPLayer *mLayer; + QCPLayer* mLayer; bool mAntialiased; - + // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); + 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; + 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); - + 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) - + 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: + public: double lower, upper; - + QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) { 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); - + QCPRange( double lower, double upper ); + + bool operator==( const QCPRange& other ) { return lower == other.lower && upper == other.upper; } + bool operator!=( const QCPRange& other ) { 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; + 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; - + 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); +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. */ @@ -538,9 +643,9 @@ Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(const QCPRange& range, double value) +inline const QCPRange operator+( const QCPRange& range, double value ) { - QCPRange result(range); + QCPRange result( range ); result += value; return result; } @@ -548,9 +653,9 @@ inline const QCPRange operator+(const QCPRange& range, double value) /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(double value, const QCPRange& range) +inline const QCPRange operator+( double value, const QCPRange& range ) { - QCPRange result(range); + QCPRange result( range ); result += value; return result; } @@ -558,9 +663,9 @@ inline const QCPRange operator+(double value, const QCPRange& range) /*! Subtracts \a value from both boundaries of the range. */ -inline const QCPRange operator-(const QCPRange& range, double value) +inline const QCPRange operator-( const QCPRange& range, double value ) { - QCPRange result(range); + QCPRange result( range ); result -= value; return result; } @@ -568,9 +673,9 @@ inline const QCPRange operator-(const QCPRange& range, double value) /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(const QCPRange& range, double value) +inline const QCPRange operator*( const QCPRange& range, double value ) { - QCPRange result(range); + QCPRange result( range ); result *= value; return result; } @@ -578,9 +683,9 @@ inline const QCPRange operator*(const QCPRange& range, double value) /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(double value, const QCPRange& range) +inline const QCPRange operator*( double value, const QCPRange& range ) { - QCPRange result(range); + QCPRange result( range ); result *= value; return result; } @@ -588,71 +693,74 @@ inline const QCPRange operator*(double value, const QCPRange& range) /*! Divides both boundaries of the range by \a value. */ -inline const QCPRange operator/(const QCPRange& range, double value) +inline const QCPRange operator/( const QCPRange& range, double value ) { - QCPRange result(range); + QCPRange result( range ); result /= value; return result; } - class QCP_LIB_DECL QCPMarginGroup : public QObject { Q_OBJECT -public: - QCPMarginGroup(QCustomPlot *parentPlot); + public: + QCPMarginGroup( QCustomPlot* parentPlot ); ~QCPMarginGroup(); - + // non-virtual methods: - QList elements(QCP::MarginSide side) const { return mChildren.value(side); } + QList elements( QCP::MarginSide side ) const { return mChildren.value( side ); } bool isEmpty() const; void clear(); - -protected: + + protected: // non-property members: - QCustomPlot *mParentPlot; + 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) - + 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) + 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: + 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) + 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); + explicit QCPLayoutElement( QCustomPlot* parentPlot = 0 ); virtual ~QCPLayoutElement(); - + // getters: - QCPLayout *layout() const { return mParentLayout; } + QCPLayout* layout() const { return mParentLayout; } QRect rect() const { return mRect; } QRect outerRect() const { return mOuterRect; } QMargins margins() const { return mMargins; } @@ -660,114 +768,113 @@ public: 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); } + 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); - + 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 void update( UpdatePhase phase ); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; - virtual QList elements(bool recursive) const; - + virtual QList elements( bool recursive ) const; + // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - -protected: + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + + protected: // property members: - QCPLayout *mParentLayout; + 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) - + // 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: + public: explicit QCPLayout(); - + // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; - + 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 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); + bool removeAt( int index ); + bool remove( QCPLayoutElement* element ); void clear(); - -protected: + + 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) + 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) + 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: + public: explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid(); - + // getters: int rowCount() const; int columnCount() const; @@ -775,171 +882,182 @@ public: 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); - + 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 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: + 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) -}; + // 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: + 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 - }; - + 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; - + 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); - + 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 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; - + 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: + 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) -}; + private: + Q_DISABLE_COPY( QCPLayoutInset ) +}; class QCP_LIB_DECL QCPLineEnding { Q_GADGET -public: + 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 + + \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) - }; - + 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); - + 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); - + 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: + 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); +Q_DECLARE_TYPEINFO( QCPLineEnding, Q_MOVABLE_TYPE ); - -class QCP_LIB_DECL QCPGrid :public QCPLayerable +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) + 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); - + public: + QCPGrid( QCPAxis* parentAxis ); + // getters: bool subGridVisible() const { return mSubGridVisible; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } @@ -947,139 +1065,156 @@ public: 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: + 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; - + QCPAxis* mParentAxis; + // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - + virtual void applyDefaultAntialiasingHint( QCPPainter* painter ) const; + virtual void draw( QCPPainter* painter ); + // non-virtual methods: - void drawGridLines(QCPPainter *painter) const; - void drawSubGridLines(QCPPainter *painter) const; - + 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(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) + 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( 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: + 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) + 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) + 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 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) + 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); + 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; } + QCPAxisRect* axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } double scaleLogBase() const { return mScaleLogBase; } const QCPRange range() const { return mRange; } @@ -1128,112 +1263,114 @@ public: QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPLineEnding lowerEnding() const; QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - + 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 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); - + 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 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; - + 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; + 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: + 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 + QCPAxisRect* mAxisRect; + // int mOffset; // in QCPAxisPainter int mPadding; Qt::Orientation mOrientation; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter // axis label: - //int mLabelPadding; // in QCPAxisPainter + // int mLabelPadding; // in QCPAxisPainter QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter + // int mTickLabelPadding; // in QCPAxisPainter bool mTickLabels, mAutoTickLabels; - //double mTickLabelRotation; // in QCPAxisPainter + // double mTickLabelRotation; // in QCPAxisPainter LabelType mTickLabelType; QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; @@ -1242,13 +1379,13 @@ protected: int mNumberPrecision; char mNumberFormatChar; bool mNumberBeautifulPowers; - //bool mNumberMultiplyCross; // QCPAxisPainter + // bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; double mTickStep; int mSubTickCount, mAutoTickCount; bool mAutoTicks, mAutoTickStep, mAutoSubTicks; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + // int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: @@ -1256,35 +1393,35 @@ protected: bool mRangeReversed; ScaleType mScaleType; double mScaleLogBase, mScaleLogBaseLogInv; - + // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; + 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 calculateAutoSubTickCount( double tickStep ) const; virtual int calculateMargin(); - + // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); + 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); - + 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; + 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; @@ -1292,59 +1429,57 @@ protected: QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; - -private: - Q_DISABLE_COPY(QCPAxis) - + + 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) - +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); + public: + explicit QCPAxisPainterPrivate( QCustomPlot* parentPlot ); virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); + + 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 + 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 + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // 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 + 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 alignmentRect, viewportRect; - double offset; // directly accessed by QCPAxis setters/getters + double offset; // directly accessed by QCPAxis setters/getters bool abbreviateDecimalPowers; bool reversedEndings; - + QVector subTickPositions; QVector tickPositions; QVector tickLabels; - -protected: + + protected: struct CachedLabel { QPointF offset; @@ -1356,41 +1491,44 @@ protected: QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + 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; -}; + 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) + 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); - + public: + QCPAbstractPlottable( QCPAxis* keyAxis, QCPAxis* valueAxis ); + // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } @@ -1400,49 +1538,52 @@ public: 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(); } + 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); + 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 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: + 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 - }; - + 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; @@ -1450,253 +1591,263 @@ protected: QBrush mBrush, mSelectedBrush; QPointer mKeyAxis, mValueAxis; bool mSelectable, mSelected; - + // reimplemented virtual methods: virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 0; + virtual void draw( QCPPainter* painter ) = 0; virtual QCP::Interaction selectionCategory() const; - void applyDefaultAntialiasingHint(QCPPainter *painter) const; + void applyDefaultAntialiasingHint( QCPPainter* painter ) const; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - + 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; - + 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; + 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; + 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 ) -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); + 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: + + protected: // property members: QString mName; - + // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; + QCustomPlot* mParentPlot; + QCPAbstractItem* mParentItem; int mAnchorId; QSet mChildren; - + // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return 0; } - + virtual QCPItemPosition* toQCPItemPosition() { return 0; } // non-virtual methods: - void addChild(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChild(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - -private: - Q_DISABLE_COPY(QCPItemAnchor) - + void addChild( QCPItemPosition* pos ); // called from pos when this anchor is set as parent + void removeChild( 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: + 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); + 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 mPositionType; } - QCPItemAnchor *parentAnchor() const { return mParentAnchor; } + QCPItemAnchor* parentAnchor() const { return mParentAnchor; } 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; + 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); - bool setParentAnchor(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: + void setType( PositionType type ); + bool setParentAnchor( 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 mPositionType; QPointer mKeyAxis, mValueAxis; QPointer mAxisRect; double mKey, mValue; - QCPItemAnchor *mParentAnchor; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return this; } - -private: - Q_DISABLE_COPY(QCPItemPosition) - -}; + QCPItemAnchor* mParentAnchor; + // 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) + 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); + public: + QCPAbstractItem( QCustomPlot* parentPlot ); virtual ~QCPAbstractItem(); - + // getters: bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; + 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); - + 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; - + 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: + 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; + 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); - + 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; - + 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) - + 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) + 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: + 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) - + 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); + 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; } + QCPLayoutGrid* plotLayout() const { return mPlotLayout; } QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } @@ -1705,125 +1856,134 @@ public: 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); - + 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& notAntialiasedElements ); + 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); + 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; - + 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); + 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); + 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; - + 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); + 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); - + 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; + QCPAxisRect* axisRect( int index = 0 ) const; QList axisRects() const; - QCPLayoutElement* layoutElementAt(const QPointF &pos) const; - Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); - + 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="", const QString &pdfTitle=""); - 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); - + + bool savePdf( const QString& fileName, + bool noCosmeticPen = false, + int width = 0, + int height = 0, + const QString& pdfCreator = "", + const QString& pdfTitle = "" ); + 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); - + 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: + + protected: // property members: QRect mViewport; - QCPLayoutGrid *mPlotLayout; + QCPLayoutGrid* mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph QList mItems; QList mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; @@ -1835,168 +1995,191 @@ protected: QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; + 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); - + 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); - + 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); - + 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: + 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) - + 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); } - + 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); - + 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 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: + + 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) + 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); + 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); - + 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); - + 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; + 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); - QList addAxes(QCPAxis::AxisTypes types); - bool removeAxis(QCPAxis *axis); - QCPLayoutInset *insetLayout() const { return mInsetLayout; } - - void setupFullAxesBox(bool connectRanges=false); + QCPAxis* addAxis( QCPAxis::AxisType type ); + 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(); } @@ -2010,19 +2193,18 @@ public: 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; + virtual void update( UpdatePhase phase ); + virtual QList elements( bool recursive ) const; -protected: + protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; + QCPLayoutInset* mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; @@ -2032,151 +2214,150 @@ protected: 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); + 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); - + 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) - + 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) + 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); - + public: + explicit QCPAbstractLegendItem( QCPLegend* parent ); + // getters: - QCPLegend *parentLegend() const { return mParentLegend; } + 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); - + 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: + 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; + 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 void applyDefaultAntialiasingHint( QCPPainter* painter ) const; virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 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); - -private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - + 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); - + public: + QCPPlottableLegendItem( QCPLegend* parent, QCPAbstractPlottable* plottable ); + // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - -protected: + QCPAbstractPlottable* plottable() { return mPlottable; } + protected: // property members: - QCPAbstractPlottable *mPlottable; - + QCPAbstractPlottable* mPlottable; + // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + 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) + 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: + 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) - + 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; } @@ -2192,44 +2373,43 @@ public: 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); - + 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; - + 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; + 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); + 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: + + signals: + void selectionChanged( QCPLegend::SelectableParts parts ); + void selectableChanged( QCPLegend::SelectableParts parts ); + + protected: // property members: QPen mBorderPen, mIconBorderPen; QBrush mBrush; @@ -2242,46 +2422,45 @@ protected: QBrush mSelectedBrush; QFont mSelectedFont; QColor mSelectedTextColor; - + // reimplemented virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual void parentPlotInitialized( QCustomPlot* parentPlot ); virtual QCP::Interaction selectionCategory() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); + 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); - + 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) - + + private: + Q_DISABLE_COPY( QCPLegend ) + friend class QCustomPlot; friend class QCPAbstractLegendItem; }; -Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) -Q_DECLARE_METATYPE(QCPLegend::SelectablePart) - +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) + 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); - + public: + explicit QCPPlotTitle( QCustomPlot* parentPlot ); + explicit QCPPlotTitle( QCustomPlot* parentPlot, const QString& text ); + // getters: QString text() const { return mText; } QFont font() const { return mFont; } @@ -2290,24 +2469,23 @@ public: 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); - + 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: + 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; @@ -2316,32 +2494,32 @@ protected: QColor mSelectedTextColor; QRect mTextBoundingRect; bool mSelectable, mSelected; - + // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); + 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); - + 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) -}; + private: + Q_DISABLE_COPY( QCPPlotTitle ) +}; class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT -public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); -protected: - QCPColorScale *mParentColorScale; + 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 @@ -2351,110 +2529,106 @@ protected: using QCPAxisRect::mouseReleaseEvent; using QCPAxisRect::wheelEvent; using QCPAxisRect::update; - virtual void draw(QCPPainter *painter); + virtual void draw( QCPPainter* painter ); void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + 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) + 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); + public: + explicit QCPColorScale( QCustomPlot* parentPlot ); virtual ~QCPColorScale(); - + // getters: - QCPAxis *axis() const { return mColorAxis.data(); } + 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; } + 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); - + 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); + void rescaleDataRange( bool onlyVisibleMaps ); -protected: + // 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; + 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) - + 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: + public: QCPData(); - QCPData(double key, double value); + QCPData( double key, double value ); double key, value; double keyErrorPlus, keyErrorMinus; double valueErrorPlus, valueErrorMinus; }; -Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO( QCPData, Q_MOVABLE_TYPE ); /*! \typedef QCPDataMap Container for storing 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 */ @@ -2462,100 +2636,125 @@ 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) + 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: + 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) + 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); + 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; } + 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(); } + 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); - + 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); - + 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; + 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: + 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; + QCPDataMap* mData; QPen mErrorPen; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; @@ -2564,66 +2763,69 @@ protected: 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 - + 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; - + 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; - + 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: + public: QCPCurveData(); - QCPCurveData(double t, double key, double value); + QCPCurveData( double t, double key, double value ); double t, key, value; }; -Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO( QCPCurveData, Q_MOVABLE_TYPE ); /*! \typedef QCPCurveDataMap Container for storing 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 */ @@ -2632,95 +2834,93 @@ 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) + Q_PROPERTY( QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle ) + Q_PROPERTY( LineStyle lineStyle READ lineStyle WRITE setLineStyle ) /// \endcond -public: + 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); + 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; } + 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); - + 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); - + 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: + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + + protected: // property members: - QCPCurveDataMap *mData; + 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; - + 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; - + virtual void drawScatterPlot( QCPPainter* painter, const QVector* pointData ) const; + // non-virtual methods: - void getCurveData(QVector *lineData) const; - double pointDistance(const QPointF &pixelPoint) const; - QPointF outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const; - + void getCurveData( QVector* lineData ) const; + double pointDistance( const QPointF& pixelPoint ) const; + QPointF outsideCoordsToPixels( double key, double value, int region, QRect axisRect ) const; + friend class QCustomPlot; friend class QCPLegend; }; - /*! \file */ - - class QCP_LIB_DECL QCPBarData { -public: + public: QCPBarData(); - QCPBarData(double key, double value); + QCPBarData( double key, double value ); double key, value; }; -Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO( QCPBarData, Q_MOVABLE_TYPE ); /*! \typedef QCPBarDataMap Container for storing 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 */ @@ -2728,93 +2928,88 @@ 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(QCPBars* barBelow READ barBelow) - Q_PROPERTY(QCPBars* barAbove READ barAbove) + Q_PROPERTY( double width READ width WRITE setWidth ) + Q_PROPERTY( QCPBars* barBelow READ barBelow ) + Q_PROPERTY( QCPBars* barAbove READ barAbove ) /// \endcond -public: - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + public: + explicit QCPBars( QCPAxis* keyAxis, QCPAxis* valueAxis ); virtual ~QCPBars(); - + // getters: double width() const { return mWidth; } - QCPBars *barBelow() const { return mBarBelow.data(); } - QCPBars *barAbove() const { return mBarAbove.data(); } - QCPBarDataMap *data() const { return mData; } - + QCPBars* barBelow() const { return mBarBelow.data(); } + QCPBars* barAbove() const { return mBarAbove.data(); } + QCPBarDataMap* data() const { return mData; } // setters: - void setWidth(double width); - void setData(QCPBarDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &value); - + void setWidth( double width ); + 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); - + 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: + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + + protected: // property members: - QCPBarDataMap *mData; + QCPBarDataMap* mData; double mWidth; 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; - + 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: - QPolygonF getBarPolygon(double key, double value) const; - double getBaseValue(double key, bool positive) const; - static void connectBars(QCPBars* lower, QCPBars* upper); - + QPolygonF getBarPolygon( double key, double value ) const; + double getBaseValue( double key, bool positive ) const; + static void connectBars( QCPBars* lower, QCPBars* upper ); + friend class QCustomPlot; friend class QCPLegend; }; - /*! \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) + 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); - + public: + explicit QCPStatisticalBox( QCPAxis* keyAxis, QCPAxis* valueAxis ); + // getters: double key() const { return mKey; } double minimum() const { return mMinimum; } @@ -2829,28 +3024,27 @@ public: 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); - + 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: + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + + protected: // property members: QVector mOutliers; double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; @@ -2858,124 +3052,122 @@ protected: 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; - + 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; - + 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); + public: + QCPColorMapData( int keySize, int valueSize, const QCPRange& keyRange, const QCPRange& valueRange ); ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - + 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); - + 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); - + 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); + 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: + 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; + 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) + 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); + public: + explicit QCPColorMap( QCPAxis* keyAxis, QCPAxis* valueAxis ); virtual ~QCPColorMap(); - + // getters: - QCPColorMapData *data() const { return mMapData; } + 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(); } - + 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); - + 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)); - + 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: + 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; + QCPColorMapData* mMapData; QCPColorGradient mGradient; bool mInterpolate; bool mTightBoundary; @@ -2984,227 +3176,226 @@ protected: QImage mMapImage; 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; - + 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; }; - 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) + Q_PROPERTY( QPen pen READ pen WRITE setPen ) + Q_PROPERTY( QPen selectedPen READ selectedPen WRITE setSelectedPen ) /// \endcond -public: - QCPItemStraightLine(QCustomPlot *parentPlot); + 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); - + 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: + 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); - + 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; + 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) + 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); + 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); - + 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: + 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); - + virtual void draw( QCPPainter* painter ); + // non-virtual methods: - QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; + 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) + 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); + 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); - + 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: + 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); - + 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) + 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); + 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); - + 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}; - + 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; - + 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) + 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); + public: + QCPItemText( QCustomPlot* parentPlot ); virtual ~QCPItemText(); - + // getters: QColor color() const { return mColor; } QColor selectedColor() const { return mSelectedColor; } @@ -3219,38 +3410,47 @@ public: 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); - + 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}; - + 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; @@ -3261,166 +3461,186 @@ protected: Qt::Alignment mTextAlignment; double mRotation; QMargins mPadding; - + // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - + 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; + 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) + 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); + 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); - + 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}; - + 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; - + 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(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + 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( QPen pen READ pen WRITE setPen ) + Q_PROPERTY( QPen selectedPen READ selectedPen WRITE setSelectedPen ) /// \endcond -public: - QCPItemPixmap(QCustomPlot *parentPlot); + public: + QCPItemPixmap( QCustomPlot* parentPlot ); virtual ~QCPItemPixmap(); - + // getters: QPixmap pixmap() const { return mPixmap; } bool scaled() const { return mScaled; } Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } 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); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - + void setPixmap( const QPixmap& pixmap ); + void setScaled( bool scaled, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio ); + 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}; - + 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; Qt::AspectRatioMode mAspectRatioMode; QPen mPen, mSelectedPen; - + // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - + 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; + 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) + 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: + 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) + 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); + QCPItemTracer( QCustomPlot* parentPlot ); virtual ~QCPItemTracer(); // getters: @@ -3430,100 +3650,104 @@ public: QBrush selectedBrush() const { return mSelectedBrush; } double size() const { return mSize; } TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } + 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); + 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; - + virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const; + // non-virtual methods: void updatePosition(); - QCPItemPosition * const position; + QCPItemPosition* const position; -protected: + protected: // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; double mSize; TracerStyle mStyle; - QCPGraph *mGraph; + QCPGraph* mGraph; double mGraphKey; bool mInterpolating; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + 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) + 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 + 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); + 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); - + 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: + 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}; + enum AnchorIndex + { + aiCenter + }; QPen mPen, mSelectedPen; double mLength; BracketStyle mStyle; - + // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - + virtual void draw( QCPPainter* painter ); + virtual QPointF anchorPixelPoint( int anchorId ) const; + // non-virtual methods: QPen mainPen() const; }; -#endif // QCUSTOMPLOT_H - +#endif // QCUSTOMPLOT_H diff --git a/app/main.cpp b/app/main.cpp index fdadc31..ad6191a 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,10 +36,10 @@ #endif #if _WIN32 -#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") +#pragma comment( linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup" ) #endif -int main( int argc, char *argv[] ) +int main( int argc, char* argv[] ) { qRegisterMetaType(); qRegisterMetaTypeStreamOperators(); @@ -48,7 +48,7 @@ int main( int argc, char *argv[] ) QApplication application( argc, argv ); QApplication::setApplicationName( "PlaYUVer" ); - QApplication::setApplicationVersion (PLAYUVER_VERSION_STRING); + QApplication::setApplicationVersion( PLAYUVER_VERSION_STRING ); QApplication::setOrganizationName( "PixLRA" ); #ifdef USE_QTDBUS @@ -56,10 +56,9 @@ int main( int argc, char *argv[] ) * use dbus, if available * allows for resuse of running Kate instances */ - QDBusConnectionInterface * const sessionBusInterface = QDBusConnection::sessionBus().interface(); + QDBusConnectionInterface* const sessionBusInterface = QDBusConnection::sessionBus().interface(); if( sessionBusInterface ) { - Bool force_new = false; QStringList filenameList; for( Int i = 1; i < argc; i++ ) @@ -71,7 +70,7 @@ int main( int argc, char *argv[] ) force_new = true; } - //check again if service is still running + // check again if service is still running bool foundRunningService = false; if( !force_new ) { @@ -82,8 +81,9 @@ int main( int argc, char *argv[] ) if( foundRunningService ) { // open given session - QDBusMessage m = QDBusMessage::createMethodCall( PLAYUVER_DBUS_SESSION_NAME, QStringLiteral( PLAYUVER_DBUS_PATH ), - QStringLiteral( PLAYUVER_DBUS_SESSION_NAME ), QStringLiteral( "activate" ) ); + QDBusMessage m = + QDBusMessage::createMethodCall( PLAYUVER_DBUS_SESSION_NAME, QStringLiteral( PLAYUVER_DBUS_PATH ), + QStringLiteral( PLAYUVER_DBUS_SESSION_NAME ), QStringLiteral( "activate" ) ); QDBusConnection::sessionBus().call( m ); @@ -93,25 +93,26 @@ int main( int argc, char *argv[] ) QStringList tokens; // open given files... - foreach(const QString & file, filenameList) + foreach( const QString& file, filenameList ) { - QDBusMessage m = QDBusMessage::createMethodCall(PLAYUVER_DBUS_SESSION_NAME, - QStringLiteral(PLAYUVER_DBUS_PATH), QStringLiteral(PLAYUVER_DBUS_SESSION_NAME), QStringLiteral("loadFile")); + QDBusMessage m = QDBusMessage::createMethodCall( + PLAYUVER_DBUS_SESSION_NAME, QStringLiteral( PLAYUVER_DBUS_PATH ), + QStringLiteral( PLAYUVER_DBUS_SESSION_NAME ), QStringLiteral( "loadFile" ) ); QList dbusargs; dbusargs.append( file ); - m.setArguments(dbusargs); + m.setArguments( dbusargs ); - QDBusMessage res = QDBusConnection::sessionBus().call(m); - if (res.type() == QDBusMessage::ReplyMessage) + QDBusMessage res = QDBusConnection::sessionBus().call( m ); + if( res.type() == QDBusMessage::ReplyMessage ) { - if (res.arguments().count() == 1) + if( res.arguments().count() == 1 ) { QVariant v = res.arguments()[0]; - if (v.isValid()) + if( v.isValid() ) { QString s = v.toString(); - if ((!s.isEmpty()) && (s != QStringLiteral("ERROR"))) + if( ( !s.isEmpty() ) && ( s != QStringLiteral( "ERROR" ) ) ) { tokens << s; } @@ -137,7 +138,8 @@ int main( int argc, char *argv[] ) } #ifdef USE_FERVOR - FvUpdater::sharedUpdater()->SetFeedURL( "http://192.168.96.201/share/PlaYUVerProject/PlaYUVerUpdate-" UPDATE_CHANNEL ".xml" ); + FvUpdater::sharedUpdater()->SetFeedURL( "http://192.168.96.201/share/PlaYUVerProject/PlaYUVerUpdate-" UPDATE_CHANNEL + ".xml" ); FvUpdater::sharedUpdater()->SetDependencies( "ALL" ); #endif diff --git a/config.h.in b/config.h.in index 1869bd1..8fdf85c 100644 --- a/config.h.in +++ b/config.h.in @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify diff --git a/examples/modules/AbsoluteFrameDifferenceExample.cpp b/examples/modules/AbsoluteFrameDifferenceExample.cpp index 033f221..be0f7cc 100644 --- a/examples/modules/AbsoluteFrameDifferenceExample.cpp +++ b/examples/modules/AbsoluteFrameDifferenceExample.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,18 +30,18 @@ REGISTER_CLASS_MAKER( AbsoluteFrameDifferenceExample ) AbsoluteFrameDifferenceExample::AbsoluteFrameDifferenceExample() { /* Module Definition */ - m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). - // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. - m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "AbsoluteFrameDifferenceExampleExample"; // Name - m_pchModuleTooltip = "Measure the absolute difference " // Description - "between two images (Y plane), e. g., abs( Y1 - Y2 )"; - m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + // See this example for details on the functions prototype + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "AbsoluteFrameDifferenceExampleExample"; // Name + m_pchModuleTooltip = + "Measure the absolute difference " // Description + "between two images (Y plane), e. g., abs( Y1 - Y2 )"; + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. m_pcFrameDifference = NULL; - } Bool AbsoluteFrameDifferenceExample::create( std::vector apcFrameList ) @@ -49,10 +49,13 @@ Bool AbsoluteFrameDifferenceExample::create( std::vector apcFram _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) return false; - m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcFrameDifference = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); return true; } @@ -72,7 +75,7 @@ PlaYUVerFrame* AbsoluteFrameDifferenceExample::process( std::vector -class AbsoluteFrameDifferenceExample: public PlaYUVerModuleIf +class AbsoluteFrameDifferenceExample : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( AbsoluteFrameDifferenceExample ) + REGISTER_CLASS_FACTORY( AbsoluteFrameDifferenceExample ) -private: + private: PlaYUVerFrame* m_pcFrameDifference; -public: + public: AbsoluteFrameDifferenceExample(); - virtual ~AbsoluteFrameDifferenceExample() - { - } + virtual ~AbsoluteFrameDifferenceExample() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __ABSOLUTEFRAMEDIFFERENCEEXAMPLE_H__ - +#endif // __ABSOLUTEFRAMEDIFFERENCEEXAMPLE_H__ diff --git a/examples/modules/FrameBinarization_APIv1.cpp b/examples/modules/FrameBinarization_APIv1.cpp index 1ce3531..6f5c47d 100644 --- a/examples/modules/FrameBinarization_APIv1.cpp +++ b/examples/modules/FrameBinarization_APIv1.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,8 +36,8 @@ FrameBinarization::FrameBinarization() m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" ); + m_cModuleOptions.addOptions() /**/ + ( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" ); m_pcBinFrame = NULL; m_uiThreshold = 128; @@ -67,4 +67,3 @@ Void FrameBinarization::destroy() delete m_pcBinFrame; m_pcBinFrame = NULL; } - diff --git a/examples/modules/FrameBinarization_APIv1.h b/examples/modules/FrameBinarization_APIv1.h index e3b74e1..6a67115 100644 --- a/examples/modules/FrameBinarization_APIv1.h +++ b/examples/modules/FrameBinarization_APIv1.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -27,23 +27,20 @@ #include "PlaYUVerModuleIf.h" -class FrameBinarization: public PlaYUVerModuleIf +class FrameBinarization : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameBinarization ) + REGISTER_CLASS_FACTORY( FrameBinarization ) -private: + private: PlaYUVerFrame* m_pcBinFrame; UInt m_uiThreshold; - public: + + public: FrameBinarization(); - virtual ~FrameBinarization() - { - } + virtual ~FrameBinarization() {} Void create( PlaYUVerFrame* ); PlaYUVerFrame* process( PlaYUVerFrame* ); Void destroy(); - }; -#endif // __FRAMEBINARIZATION_H__ - +#endif // __FRAMEBINARIZATION_H__ diff --git a/lib/LibMemory.h b/lib/LibMemory.h index 00523dc..27fcf33 100644 --- a/lib/LibMemory.h +++ b/lib/LibMemory.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -37,8 +37,8 @@ typedef size_t SizeT; #ifdef _MSC_VER typedef __int64 Int64; -#if _MSC_VER <= 1200 // MS VC6 -typedef __int64 UInt64; // MS VC6 does not support unsigned __int64 to double conversion +#if _MSC_VER <= 1200 // MS VC6 +typedef __int64 UInt64; // MS VC6 does not support unsigned __int64 to double conversion #else typedef unsigned __int64 UInt64; #endif @@ -47,19 +47,19 @@ typedef long long Int64; typedef unsigned long long UInt64; #endif -#define DATA_ALIGN 1 ///< use 32-bit aligned malloc/free -#if DATA_ALIGN && _WIN32 && ( _MSC_VER > 1300 ) -#define xMalloc( len ) _aligned_malloc( len, 32 ) -#define xFreeMem( ptr ) _aligned_free ( ptr ) +#define DATA_ALIGN 1 ///< use 32-bit aligned malloc/free +#if DATA_ALIGN && _WIN32 && ( _MSC_VER > 1300 ) +#define xMalloc( len ) _aligned_malloc( len, 32 ) +#define xFreeMem( ptr ) _aligned_free( ptr ) #else -#define xMalloc( len ) malloc ( len ) -#define xFreeMem( ptr ) free ( ptr ) +#define xMalloc( len ) malloc( len ) +#define xFreeMem( ptr ) free( ptr ) #endif -#define xMemSet( type, len, ptr ) memset ( ptr, 0, (len)*sizeof(type) ) +#define xMemSet( type, len, ptr ) memset( ptr, 0, ( len ) * sizeof( type ) ) static inline Void* xMallocMem( SizeT nitems ) { - Void *d; + Void* d; if( ( d = xMalloc( nitems ) ) == NULL ) { printf( "malloc failed.\n" ); @@ -71,42 +71,42 @@ static inline Void* xMallocMem( SizeT nitems ) static inline Void* xCallocMem( SizeT nitems, SizeT size ) { size_t padded_size = nitems * size; - Void *d = xMallocMem( padded_size ); - memset( d, 0, ( int )padded_size ); + Void* d = xMallocMem( padded_size ); + memset( d, 0, (int)padded_size ); return d; } -template -Int getMem1D( T **array1D, Int dim0 ) +template +Int getMem1D( T** array1D, Int dim0 ) { - if( ( *array1D = ( T* )xCallocMem( dim0, sizeof(T) ) ) == NULL ) + if( ( *array1D = (T*)xCallocMem( dim0, sizeof( T ) ) ) == NULL ) return 0; - return ( sizeof(T*) + dim0 * sizeof(T) ); + return ( sizeof( T* ) + dim0 * sizeof( T ) ); } -template +template Int getMem2D( T*** array2D, Int dim0, Int dim1 ) { Int i; - if( ( *array2D = ( T** )xMallocMem( dim0 * sizeof(T*) ) ) == NULL ) + if( ( *array2D = (T**)xMallocMem( dim0 * sizeof( T* ) ) ) == NULL ) printf( "get_mem2Dint: array2D" ); - if( ( *( *array2D ) = ( T* )xCallocMem( dim0 * dim1, sizeof(T) ) ) == NULL ) + if( ( *( *array2D ) = (T*)xCallocMem( dim0 * dim1, sizeof( T ) ) ) == NULL ) printf( "get_mem2Dint: array2D" ); for( i = 1; i < dim0; i++ ) ( *array2D )[i] = ( *array2D )[i - 1] + dim1; - return dim0 * ( sizeof(T*) + dim1 * sizeof(T) ); + return dim0 * ( sizeof( T* ) + dim1 * sizeof( T ) ); } -template +template Int getMem3D( T**** array3D, Int dim0, Int dim1, Int dim2 ) { - Int i, mem_size = dim0 * sizeof(T**); + Int i, mem_size = dim0 * sizeof( T ** ); - if( ( ( *array3D ) = ( T*** )xMallocMem( dim0 * sizeof(T**) ) ) == NULL ) + if( ( ( *array3D ) = (T***)xMallocMem( dim0 * sizeof( T** ) ) ) == NULL ) printf( "get_mem3Dint: array3D" ); mem_size += getMem2D( *array3D, dim0 * dim1, dim2 ); @@ -117,12 +117,12 @@ Int getMem3D( T**** array3D, Int dim0, Int dim1, Int dim2 ) return mem_size; } -template +template Int getMem4D( T***** array4D, Int dim0, Int dim1, Int dim2, Int dim3 ) { - int i, mem_size = dim0 * sizeof(int***); + int i, mem_size = dim0 * sizeof( int *** ); - if( ( ( *array4D ) = ( T**** )xMallocMem( dim0 * sizeof(T***) ) ) == NULL ) + if( ( ( *array4D ) = (T****)xMallocMem( dim0 * sizeof( T*** ) ) ) == NULL ) printf( "get_mem4Dint: array4D" ); mem_size += getMem3D( *array4D, dim0 * dim1, dim2, dim3 ); @@ -133,12 +133,12 @@ Int getMem4D( T***** array4D, Int dim0, Int dim1, Int dim2, Int dim3 ) return mem_size; } -template +template Int getMem5D( T****** array5D, Int dim0, Int dim1, Int dim2, Int dim3, Int dim4 ) { - int i, mem_size = dim0 * sizeof(T****); + int i, mem_size = dim0 * sizeof( T **** ); - if( ( ( *array5D ) = ( T***** )xMallocMem( dim0 * sizeof(T****) ) ) == NULL ) + if( ( ( *array5D ) = (T*****)xMallocMem( dim0 * sizeof( T**** ) ) ) == NULL ) printf( "get_mem5Dint: array5D" ); mem_size += getMem4D( *array5D, dim0 * dim1, dim2, dim3, dim4 ); @@ -149,8 +149,8 @@ Int getMem5D( T****** array5D, Int dim0, Int dim1, Int dim2, Int dim3, Int dim4 return mem_size; } -template -Void freeMem1D( T *array1D ) +template +Void freeMem1D( T* array1D ) { if( array1D ) { @@ -158,7 +158,7 @@ Void freeMem1D( T *array1D ) } } -template +template Void freeMem2D( T** array2D ) { if( array2D ) @@ -176,7 +176,7 @@ Void freeMem2D( T** array2D ) } } -template +template Void freeMem3D( T*** array3D ) { if( array3D ) @@ -190,7 +190,7 @@ Void freeMem3D( T*** array3D ) } } -template +template Void freeMem4D( T**** array4D ) { if( array4D ) @@ -204,7 +204,7 @@ Void freeMem4D( T**** array4D ) } } -template +template Void freeMem5D( T***** array5D ) { if( array5D ) @@ -218,4 +218,4 @@ Void freeMem5D( T***** array5D ) } } -#endif // __LIBMEMORY_H__ +#endif // __LIBMEMORY_H__ diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index 7461c49..c2e4951 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -58,8 +58,8 @@ typedef std::string String; #ifdef _MSC_VER typedef __int64 Int64; -#if _MSC_VER <= 1200 // MS VC6 -typedef __int64 UInt64; // MS VC6 does not support unsigned __int64 to double conversion +#if _MSC_VER <= 1200 // MS VC6 +typedef __int64 UInt64; // MS VC6 does not support unsigned __int64 to double conversion #else typedef unsigned __int64 UInt64; #endif @@ -75,7 +75,7 @@ typedef unsigned long long UInt64; // Type definition // ==================================================================================================================== -typedef UShort Pel; ///< 16-bit pixel type +typedef UShort Pel; ///< 16-bit pixel type typedef UChar Byte; // ==================================================================================================================== @@ -87,7 +87,6 @@ typedef UChar Byte; // #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of signed 64-bit integer // #define MAX_DOUBLE 1.7e+308 ///< max. value of double-type value - // ==================================================================================================================== // PlaYUVer definitions // ==================================================================================================================== @@ -121,7 +120,6 @@ enum Endianness PLAYUVER_LITTLE_ENDIAN = 1, }; - inline String lowercase( const String& in ) { String out; @@ -136,22 +134,15 @@ inline String uppercase( const String& in ) return out; } -struct PlaYUVerFailure: public std::exception +struct PlaYUVerFailure : public std::exception { String m_class_name; String m_error_msg; - PlaYUVerFailure( String error_msg ) throw() : - m_error_msg( error_msg ) - { - } - PlaYUVerFailure( String class_name, String error_msg ) throw() : - m_class_name( class_name ), - m_error_msg( error_msg ) - { - } - ~PlaYUVerFailure() throw() + PlaYUVerFailure( String error_msg ) throw() : m_error_msg( error_msg ) {} + PlaYUVerFailure( String class_name, String error_msg ) throw() : m_class_name( class_name ), m_error_msg( error_msg ) { } + ~PlaYUVerFailure() throw() {} const Char* what() const throw() { String* msg = new String( "[" + m_class_name + "] " + m_error_msg ); @@ -159,4 +150,4 @@ struct PlaYUVerFailure: public std::exception } }; -#endif // __PLAYUVERDEFS_H__ +#endif // __PLAYUVERDEFS_H__ diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index dfa487c..3d828d9 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -40,9 +40,7 @@ std::vector PlaYUVerFrame::supportedColorSpacesListNames() { return std::vector{ - "YUV", - "RGB", - "GRAY", + "YUV", "RGB", "GRAY", }; } @@ -86,10 +84,10 @@ static Int getImgMemory( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeig total_mem_size += getMem2D( array3D, dim0, dim1 ); - if( ( ( *array3D )[0][0] = ( Pel* )xCallocMem( mem_size, sizeof(Pel) ) ) == NULL ) + if( ( ( *array3D )[0][0] = (Pel*)xCallocMem( mem_size, sizeof( Pel ) ) ) == NULL ) printf( "getImgMemory: array1D" ); - total_mem_size += mem_size * sizeof(Pel); + total_mem_size += mem_size * sizeof( Pel ); // Luma for( i = 1; i < dim1; i++ ) @@ -130,12 +128,12 @@ struct PlaYUVerFramePrivate const PlaYUVerPixFmtDescriptor* m_pcPelFormat; String m_cPelFmtName; - UInt m_uiWidth; //!< Width of the frame - UInt m_uiHeight; //!< Height of the frame - Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) + UInt m_uiWidth; //!< Width of the frame + UInt m_uiHeight; //!< Height of the frame + Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) Int m_iNumberChannels; //!< Number of channels - UInt m_uiBitsPel; //!< Bits per pixel/channel -// Int m_iEndianness; //!< Endiannes of bytes + UInt m_uiBitsPel; //!< Bits per pixel/channel + // Int m_iEndianness; //!< Endiannes of bytes UInt m_uiHalfPelValue; //!< Bits per pixel/channel Pel*** m_pppcInputPel; @@ -191,7 +189,8 @@ struct PlaYUVerFramePrivate } else { - getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, m_pcPelFormat->log2ChromaWidth ); + getImgMemory( &m_pppcInputPel, m_uiHeight, m_uiWidth, m_pcPelFormat->log2ChromaHeight, + m_pcPelFormat->log2ChromaWidth ); } getMem1D( &m_pcARGB32, m_uiHeight * m_uiWidth * 4 ); @@ -200,7 +199,8 @@ struct PlaYUVerFramePrivate m_uiHistoSegments = 1 << m_uiBitsPel; - if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB || m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_ARGB ) + if( m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB || + m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_ARGB ) m_uiHistoChannels = m_pcPelFormat->numberChannels + 1; else m_uiHistoChannels = m_pcPelFormat->numberChannels; @@ -215,22 +215,18 @@ struct PlaYUVerFramePrivate * \brief Constructors */ -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) : - d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) : d( new PlaYUVerFramePrivate ) { d->init( width, height, pelFormat, bitsPixel ); } -PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other ) : -d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other ) : d( new PlaYUVerFramePrivate ) { d->init( other.getWidth(), other.getHeight(), other.getPelFormat(), other.getBitsPel() ); copyFrom( &other ); } - -PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other ) : - d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame* other ) : d( new PlaYUVerFramePrivate ) { if( other ) { @@ -239,8 +235,8 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other ) : } } -PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt width, UInt height ) : - d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt width, UInt height ) + : d( new PlaYUVerFramePrivate ) { const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other.getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) @@ -264,8 +260,8 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt w copyFrom( other, x, y ); } -PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame *other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) : - d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame* other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) + : d( new PlaYUVerFramePrivate ) { if( !other ) return; @@ -329,7 +325,7 @@ Bool PlaYUVerFrame::haveSameFmt( const PlaYUVerFrame& other, UInt match ) const } Bool PlaYUVerFrame::haveSameFmt( const PlaYUVerFrame* other, UInt match ) const - { +{ Bool bRet = false; if( other ) { @@ -359,16 +355,16 @@ UInt PlaYUVerFrame::getNumberChannels() const } UInt PlaYUVerFrame::getWidth( Int channel ) const - { +{ return CHROMASHIFT( d->m_uiWidth, channel > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0 ); } UInt PlaYUVerFrame::getHeight( Int channel ) const - { +{ return CHROMASHIFT( d->m_uiHeight, channel > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0 ); } UInt PlaYUVerFrame::getPixels( Int channel ) const - { +{ return getWidth( channel ) * getWidth( channel ); } @@ -418,7 +414,8 @@ UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelF UInt64 numberBytes = uiWidth * uiHeight; if( pcPelFormat->numberChannels > 1 ) { - UInt64 numberBytesChroma = CHROMASHIFT( uiWidth, pcPelFormat->log2ChromaWidth ) * CHROMASHIFT( uiHeight, pcPelFormat->log2ChromaHeight ); + UInt64 numberBytesChroma = + CHROMASHIFT( uiWidth, pcPelFormat->log2ChromaWidth ) * CHROMASHIFT( uiHeight, pcPelFormat->log2ChromaHeight ); numberBytes += ( pcPelFormat->numberChannels - 1 ) * numberBytesChroma; } return numberBytes * bytesPerPixel; @@ -472,7 +469,8 @@ UChar* PlaYUVerFrame::getRGBBuffer() PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos ) { - PlaYUVerPixel PixelValue( d->m_pcPelFormat->colorSpace, d->m_uiHalfPelValue, d->m_uiHalfPelValue, d->m_uiHalfPelValue ); + PlaYUVerPixel PixelValue( d->m_pcPelFormat->colorSpace, d->m_uiHalfPelValue, d->m_uiHalfPelValue, + d->m_uiHalfPelValue ); for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; @@ -513,7 +511,7 @@ Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame& other ) return; d->m_bHasRGBPel = false; d->m_bHasHistogram = false; - memcpy( *d->m_pppcInputPel[LUMA], other.getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof(Pel) ); + memcpy( *d->m_pppcInputPel[LUMA], other.getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); } Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other ) @@ -526,28 +524,28 @@ Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame& other, UInt xPos, UInt yPos ) { if( haveSameFmt( other, MATCH_ALL ) ) return; - Pel ***pInput = other.getPelBufferYUV(); + Pel*** pInput = other.getPelBufferYUV(); for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) { Int ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; Int ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; for( UInt i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ); i++ ) { - memcpy( d->m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), ( d->m_uiWidth >> ratioW ) * sizeof(Pel) ); + memcpy( d->m_pppcInputPel[ch][i], &( pInput[ch][( yPos >> ratioH ) + i][( xPos >> ratioW )] ), + ( d->m_uiWidth >> ratioW ) * sizeof( Pel ) ); } } d->m_bHasRGBPel = false; d->m_bHasHistogram = false; } - Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other, UInt x, UInt y ) { if( other ) copyFrom( *other, x, y ); } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness, UInt64 uiBuffSize ) +Void PlaYUVerFrame::frameFromBuffer( Byte* Buff, Int iEndianness, UInt64 uiBuffSize ) { if( uiBuffSize != getBytesPerFrame() ) return; @@ -555,7 +553,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness, UInt64 uiBuffS frameFromBuffer( Buff, iEndianness ); } -Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness ) +Void PlaYUVerFrame::frameFromBuffer( Byte* Buff, Int iEndianness ) { Byte* ppBuff[MAX_NUMBER_PLANES]; Byte* pTmpBuff; @@ -567,7 +565,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness ) Int endByte = bytesPixel; Int incByte = 1; Int b; - Int maxval = pow(2, d->m_uiBitsPel) - 1; + Int maxval = pow( 2, d->m_uiBitsPel ) - 1; if( iEndianness == 0 ) { @@ -601,7 +599,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness ) *pPel += *pTmpBuff << ( b * 8 ); pTmpBuff++; // Check max value and bound it to "maxval" to prevent segfault when calculating histogram - if(*pPel > maxval) + if( *pPel > maxval ) *pPel = 0; // ----- } @@ -613,7 +611,7 @@ Void PlaYUVerFrame::frameFromBuffer( Byte *Buff, Int iEndianness ) d->m_bHasHistogram = false; } -Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer, Int iEndianness ) +Void PlaYUVerFrame::frameToBuffer( Byte* output_buffer, Int iEndianness ) { UInt bytesPixel = ( d->m_uiBitsPel - 1 ) / 8 + 1; Byte* ppBuff[MAX_NUMBER_PLANES]; @@ -665,18 +663,18 @@ Void PlaYUVerFrame::frameToBuffer( Byte *output_buffer, Int iEndianness ) Void PlaYUVerFrame::fillRGBBuffer() { -#define CLAMP_YUV2RGB(X) X = X < 0 ? 0 : X > 255 ? 255 : X; -#define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ -iR = iY + ( ( 1436 * ( iV - 128) ) >> 10 ); \ -iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); \ -iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); \ -CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) +#define CLAMP_YUV2RGB( X ) X = X < 0 ? 0 : X > 255 ? 255 : X; +#define YUV2RGB( iY, iU, iV, iR, iG, iB ) \ + iR = iY + ( ( 1436 * ( iV - 128 ) ) >> 10 ); \ + iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); \ + iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ); \ + CLAMP_YUV2RGB( iR ) CLAMP_YUV2RGB( iG ) CLAMP_YUV2RGB( iB ) if( d->m_bHasRGBPel ) return; Int iR, iG, iB; Int shiftBits = d->m_uiBitsPel - 8; - UInt* pARGB = ( UInt* )d->m_pcARGB32; + UInt* pARGB = (UInt*)d->m_pcARGB32; if( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) { Pel* pY = d->m_pppcInputPel[LUMA][0]; @@ -720,7 +718,7 @@ CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) UInt y, x; Int i, j; - for( y = 0; y < d->m_uiHeight >> d->m_pcPelFormat->log2ChromaHeight; y++ ) + for( y = 0; ym_uiHeight>> d->m_pcPelFormat->log2ChromaHeight; y++ ) { for( i = 0; i < 1 << d->m_pcPelFormat->log2ChromaHeight; i++ ) { @@ -728,7 +726,7 @@ CLAMP_YUV2RGB(iR) CLAMP_YUV2RGB(iG) CLAMP_YUV2RGB(iB) pU = pLineU; pV = pLineV; pARGB = pARGBLine; - for( x = 0; x < d->m_uiWidth >> d->m_pcPelFormat->log2ChromaWidth; x++ ) + for( x = 0; xm_uiWidth>> d->m_pcPelFormat->log2ChromaWidth; x++ ) { iU = *pU++; iU >>= shiftBits; @@ -778,7 +776,7 @@ Void PlaYUVerFrame::calcHistogram() Int colorSpace = d->m_pcPelFormat->colorSpace; if( colorSpace == PlaYUVerPixel::COLOR_YUV ) { - const Pel *data[3]; + const Pel* data[3]; data[LUMA] = d->m_pppcInputPel[LUMA][0]; data[CHROMA_U] = d->m_pppcInputPel[CHROMA_U][0]; data[CHROMA_V] = d->m_pppcInputPel[CHROMA_V][0]; @@ -835,59 +833,59 @@ Int getRealHistoChannel( Int colorSpace, Int channel ) switch( colorSpace ) { - case PlaYUVerPixel::COLOR_GRAY: - if( channel != LUMA ) - { - return -1; - } - histoChannel = 0; - break; - case PlaYUVerPixel::COLOR_RGB: - if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != LUMA ) - { - return -1; - } - else - { -// if( channel == LUMA ) -// { -// histoChannel = 3; -// } -// else + case PlaYUVerPixel::COLOR_GRAY: + if( channel != LUMA ) { - histoChannel = channel; + return -1; } - } - break; - case PlaYUVerPixel::COLOR_ARGB: - if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != COLOR_A && channel != LUMA ) - { - return -1; - } - else - { - if( channel == LUMA ) + histoChannel = 0; + break; + case PlaYUVerPixel::COLOR_RGB: + if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != LUMA ) { - histoChannel = 4; + return -1; + } + else + { + // if( channel == LUMA ) + // { + // histoChannel = 3; + // } + // else + { + histoChannel = channel; + } + } + break; + case PlaYUVerPixel::COLOR_ARGB: + if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != COLOR_A && channel != LUMA ) + { + return -1; + } + else + { + if( channel == LUMA ) + { + histoChannel = 4; + } + else + { + histoChannel = channel; + } + } + break; + case PlaYUVerPixel::COLOR_YUV: + if( channel != LUMA && channel != CHROMA_U && channel != CHROMA_V ) + { + return -1; } else { histoChannel = channel; } - } - break; - case PlaYUVerPixel::COLOR_YUV: - if( channel != LUMA && channel != CHROMA_U && channel != CHROMA_V ) - { - return -1; - } - else - { - histoChannel = channel; - } - break; - default: - histoChannel = -1; + break; + default: + histoChannel = -1; } return histoChannel; } @@ -914,7 +912,7 @@ UInt PlaYUVerFrame::getMin( Int channel ) for( value = 0; value <= d->m_uiHistoSegments; value++ ) { - if( d->m_puiHistogram[indexStart + value] > 0) + if( d->m_puiHistogram[indexStart + value] > 0 ) { break; } @@ -944,7 +942,7 @@ UInt PlaYUVerFrame::getMax( Int channel ) for( value = d->m_uiHistoSegments - 1; value >= 0; value-- ) { - if( d->m_puiHistogram[indexStart + value] > 0) + if( d->m_puiHistogram[indexStart + value] > 0 ) { break; } @@ -1093,7 +1091,6 @@ Double PlaYUVerFrame::getStdDev( Int channel, UInt start, UInt end ) } return sqrt( ( dev - count * mean * mean ) / ( count - 1 ) ); - } Double PlaYUVerFrame::getHistogramValue( Int channel, UInt bin ) @@ -1159,14 +1156,17 @@ Bool PlaYUVerFrame::toMat( cv::Mat& cvMat, Bool convertToGray ) { Bool bRet = false; #ifdef USE_OPENCV - if( convertToGray && !( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) ) + if( convertToGray && + !( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || + d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_GRAY ) ) { return bRet; } Int cvType = CV_MAKETYPE( CV_8U, convertToGray ? 1 : d->m_pcPelFormat->numberChannels ); cvMat.create( d->m_uiHeight, d->m_uiWidth, cvType ); UChar* pCvPel = cvMat.data; - if( !convertToGray && ( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) ) + if( !convertToGray && ( d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_YUV || + d->m_pcPelFormat->colorSpace == PlaYUVerPixel::COLOR_RGB ) ) { fillRGBBuffer(); UChar* pARGB = d->m_pcARGB32; @@ -1207,13 +1207,13 @@ Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) switch( cvMat.channels() ) { case 1: - d->m_iPixelFormat = findPixelFormat( "GRAY" ); - break; + d->m_iPixelFormat = findPixelFormat( "GRAY" ); + break; case 3: - d->m_iPixelFormat = findPixelFormat( "BGR24" ); - break; + d->m_iPixelFormat = findPixelFormat( "BGR24" ); + break; default: - return false; + return false; } } d->init( cvMat.cols, cvMat.rows, d->m_iPixelFormat, 8 ); @@ -1257,10 +1257,8 @@ Bool PlaYUVerFrame::fromMat( cv::Mat& cvMat ) std::vector PlaYUVerFrame::supportedQualityMetricsList() { - return std::vector { - "PSNR", - "MSE", - "SSIM", + return std::vector{ + "PSNR", "MSE", "SSIM", }; } @@ -1268,17 +1266,17 @@ Double PlaYUVerFrame::getQuality( Int Metric, PlaYUVerFrame* Org, Int component { switch( Metric ) { - case PSNR_METRIC: - return getPSNR( Org, component ); - break; - case MSE_METRIC: - return getMSE( Org, component ); - break; - case SSIM_METRIC: - return getSSIM( Org, component ); - break; - default: - assert( 0 ); + case PSNR_METRIC: + return getPSNR( Org, component ); + break; + case MSE_METRIC: + return getMSE( Org, component ); + break; + case SSIM_METRIC: + return getSSIM( Org, component ); + break; + default: + assert( 0 ); }; return 0; } @@ -1327,12 +1325,19 @@ Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) return dPSNR; } -float compute_ssim( Pel **refImg, Pel **encImg, Int width, Int height, Int win_width, Int win_height, Int max_pel_value_comp, Int overlapSize ) +float compute_ssim( Pel** refImg, + Pel** encImg, + Int width, + Int height, + Int win_width, + Int win_height, + Int max_pel_value_comp, + Int overlapSize ) { static const float K1 = 0.01f, K2 = 0.03f; float max_pix_value_sqd; float C1, C2; - float win_pixels = ( float )( win_width * win_height ); + float win_pixels = (float)( win_width * win_height ); #ifdef UNBIASED_VARIANCE float win_pixels_bias = win_pixels - 1; #else @@ -1344,7 +1349,7 @@ float compute_ssim( Pel **refImg, Pel **encImg, Int width, Int height, Int win_w float cur_distortion = 0.0; int i, j, n, m, win_cnt = 0; - max_pix_value_sqd = ( float )( max_pel_value_comp * max_pel_value_comp ); + max_pix_value_sqd = (float)( max_pel_value_comp * max_pel_value_comp ); C1 = K1 * K1 * max_pix_value_sqd; C2 = K2 * K2 * max_pix_value_sqd; @@ -1370,22 +1375,22 @@ float compute_ssim( Pel **refImg, Pel **encImg, Int width, Int height, Int win_w } } - meanOrg = ( float )imeanOrg / win_pixels; - meanEnc = ( float )imeanEnc / win_pixels; + meanOrg = (float)imeanOrg / win_pixels; + meanEnc = (float)imeanEnc / win_pixels; - varOrg = ( ( float )ivarOrg - ( ( float )imeanOrg ) * meanOrg ) / win_pixels_bias; - varEnc = ( ( float )ivarEnc - ( ( float )imeanEnc ) * meanEnc ) / win_pixels_bias; - covOrgEnc = ( ( float )icovOrgEnc - ( ( float )imeanOrg ) * meanEnc ) / win_pixels_bias; + varOrg = ( (float)ivarOrg - ( (float)imeanOrg ) * meanOrg ) / win_pixels_bias; + varEnc = ( (float)ivarEnc - ( (float)imeanEnc ) * meanEnc ) / win_pixels_bias; + covOrgEnc = ( (float)icovOrgEnc - ( (float)imeanOrg ) * meanEnc ) / win_pixels_bias; - mb_ssim = ( float )( ( 2.0 * meanOrg * meanEnc + C1 ) * ( 2.0 * covOrgEnc + C2 ) ); - mb_ssim /= ( float )( meanOrg * meanOrg + meanEnc * meanEnc + C1 ) * ( varOrg + varEnc + C2 ); + mb_ssim = (float)( ( 2.0 * meanOrg * meanEnc + C1 ) * ( 2.0 * covOrgEnc + C2 ) ); + mb_ssim /= (float)( meanOrg * meanOrg + meanEnc * meanEnc + C1 ) * ( varOrg + varEnc + C2 ); cur_distortion += mb_ssim; win_cnt++; } } - cur_distortion /= ( float )win_cnt; + cur_distortion /= (float)win_cnt; if( cur_distortion >= 1.0 && cur_distortion < 1.01 ) // avoid float accuracy problem at very low QP(e.g.2) cur_distortion = 1.0; @@ -1398,12 +1403,13 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) Double dSSIM = 1; if( component == LUMA ) { - dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], d->m_uiWidth, d->m_uiHeight, 8, 8, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], d->m_uiWidth, d->m_uiHeight, + 8, 8, 255, 8 ); } else { - dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], getChromaWidth(), getChromaHeight(), 4, 4, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], getChromaWidth(), + getChromaHeight(), 4, 4, 255, 8 ); } return dSSIM; } - diff --git a/lib/PlaYUVerFrame.h b/lib/PlaYUVerFrame.h index ced24be..9f460ce 100644 --- a/lib/PlaYUVerFrame.h +++ b/lib/PlaYUVerFrame.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,7 +36,7 @@ class Mat; struct PlaYUVerPixFmtDescriptor; struct PlaYUVerFramePrivate; -#define CHROMASHIFT( SIZE, SHIFT ) UInt( -( ( - ( Int( SIZE ) ) ) >> ( SHIFT ) ) ) +#define CHROMASHIFT( SIZE, SHIFT ) UInt( -( ( -( Int( SIZE ) ) ) >> ( SHIFT ) ) ) /** * \class PlaYUVerFrame @@ -45,8 +45,7 @@ struct PlaYUVerFramePrivate; */ class PlaYUVerFrame { -public: - + public: /** ColorSpace Enum * List of supported pixel formats - do not change order */ @@ -109,7 +108,7 @@ public: * @param other existing frame to copy from */ PlaYUVerFrame( const PlaYUVerFrame& other ); - PlaYUVerFrame( const PlaYUVerFrame *other ); + PlaYUVerFrame( const PlaYUVerFrame* other ); /** * Creates and new frame with the configuration of an @@ -192,7 +191,6 @@ public: */ static UInt64 getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ); - /** * Reset frame pixels to zero */ @@ -265,8 +263,8 @@ public: /** @} */ -private: + private: PlaYUVerFramePrivate* d; }; -#endif // __PLAYUVERFRAME_H__ +#endif // __PLAYUVERFRAME_H__ diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index 07c3b9e..f0d2d6d 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -199,8 +199,7 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI } #endif -const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_PEL_FORMATS] = -{ +const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_PEL_FORMATS] = { { "YUV420p", PlaYUVerPixel::COLOR_YUV, @@ -210,9 +209,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 1, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), { - { 0, 0, 1 }, /* Y */ - { 1, 0, 1 }, /* U */ - { 2, 0, 1 }, /* V */ + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ }, }, { @@ -224,9 +223,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), { - { 0, 0, 1 }, /* Y */ - { 1, 0, 1 }, /* U */ - { 2, 0, 1 }, /* V */ + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ }, }, { @@ -238,9 +237,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), { - { 0, 0, 1 }, /* Y */ - { 1, 0, 1 }, /* U */ - { 2, 0, 1 }, /* V */ + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ }, }, { @@ -252,9 +251,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), { - { 0, 1, 1 }, /* Y */ - { 0, 3, 2 }, /* U */ - { 0, 3, 4 }, /* V */ + {0, 1, 1}, /* Y */ + {0, 3, 2}, /* U */ + {0, 3, 4}, /* V */ }, }, { @@ -265,21 +264,21 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), - { { 0, 0, 1 } }, /* Y */ + {{0, 0, 1}}, /* Y */ }, { - "RGBp", - PlaYUVerPixel::COLOR_RGB, - 3, - 3, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), - { - { 0, 0, 1 }, /* R */ - { 1, 0, 1 }, /* G */ - { 2, 0, 1 }, /* B */ - }, + "RGBp", + PlaYUVerPixel::COLOR_RGB, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + { + {0, 0, 1}, /* R */ + {1, 0, 1}, /* G */ + {2, 0, 1}, /* B */ + }, }, { "RGB", @@ -290,9 +289,9 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), { - { 0, 2, 1 }, /* R */ - { 0, 2, 2 }, /* G */ - { 0, 2, 3 }, /* B */ + {0, 2, 1}, /* R */ + {0, 2, 2}, /* G */ + {0, 2, 3}, /* B */ }, }, { @@ -304,10 +303,8 @@ const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NU 0, ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), { - { 0, 2, 3}, /* B */ - { 0, 2, 2}, /* R */ - { 0, 2, 1}, /* G */ + {0, 2, 3}, /* B */ + {0, 2, 2}, /* R */ + {0, 2, 1}, /* G */ }, - } -}; - + }}; diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index fa8426b..b8c6471 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -33,8 +33,7 @@ #define CHROMARATIO( SIZE, RATIO ) ( RATIO > 1 ? ( ( SIZE + 1 ) / RATIO ) : SIZE ) -#define PEL_RGB( r, g, b ) \ - ( 0xffu << 24 ) | ( ( r & 0xff ) << 16 ) | ( ( g & 0xff ) << 8 ) | ( b & 0xff ) +#define PEL_RGB( r, g, b ) ( 0xffu << 24 ) | ( ( r & 0xff ) << 16 ) | ( ( g & 0xff ) << 8 ) | ( b & 0xff ) typedef struct PlaYUVerComponentDescriptor { @@ -68,7 +67,7 @@ typedef struct PlaYUVerComponentDescriptor */ typedef struct PlaYUVerPixFmtDescriptor { - const char *name; + const char* name; Int colorSpace; @@ -112,4 +111,4 @@ typedef struct PlaYUVerPixFmtDescriptor extern const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[]; -#endif // __PLAYUVERFRAMEPIXELFORMATS_H__ +#endif // __PLAYUVERFRAMEPIXELFORMATS_H__ diff --git a/lib/PlaYUVerLib.h b/lib/PlaYUVerLib.h index e64d719..5e090c3 100644 --- a/lib/PlaYUVerLib.h +++ b/lib/PlaYUVerLib.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -56,4 +56,4 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerStream.h" -#endif // __PLAYUVERLIB_H_ +#endif // __PLAYUVERLIB_H_ diff --git a/lib/PlaYUVerModuleIf.h b/lib/PlaYUVerModuleIf.h index fa73c46..1a42d78 100644 --- a/lib/PlaYUVerModuleIf.h +++ b/lib/PlaYUVerModuleIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -39,20 +39,18 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerOptions.h" -#define REGISTER_CLASS_MAKER(X) \ +#define REGISTER_CLASS_MAKER( X ) \ extern "C" PlaYUVerModuleIf* Maker() { return new X; } - -#define REGISTER_CLASS_FACTORY(X) \ -public: \ +#define REGISTER_CLASS_FACTORY( X ) \ + public: \ static PlaYUVerModuleIf* Create() { return new X(); } \ void Delete() { delete this; } - -#define _BASIC_MODULE_API_2_CHECK_ \ -if( apcFrameList.size() != m_uiNumberOfFrames ) \ - return false; \ -for( UInt i = 0; i < apcFrameList.size(); i++ ) \ - if( !apcFrameList[i] ) \ - return false; +#define _BASIC_MODULE_API_2_CHECK_ \ + if( apcFrameList.size() != m_uiNumberOfFrames ) \ + return false; \ + for( UInt i = 0; i < apcFrameList.size(); i++ ) \ + if( !apcFrameList[i] ) \ + return false; /** Module_API_Version Enum * \ingroup PlaYUVerLib_Modules @@ -122,8 +120,7 @@ enum Module_Key_Supported */ class PlaYUVerModuleIf { -public: - + public: Int m_iModuleAPI; Int m_iModuleType; const Char* m_pchModuleCategory; @@ -142,50 +139,23 @@ public: m_iModuleAPI = MODULE_API_1; m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; } - virtual ~PlaYUVerModuleIf() - { - } - + virtual ~PlaYUVerModuleIf() {} virtual void Delete() = 0; virtual Void destroy() = 0; /** * Module API version 1 */ - virtual Void create( PlaYUVerFrame* ) - { - } - virtual PlaYUVerFrame* process( PlaYUVerFrame* ) - { - return NULL; - } - virtual Double measure( PlaYUVerFrame* ) - { - return 0; - } - + virtual Void create( PlaYUVerFrame* ) {} + virtual PlaYUVerFrame* process( PlaYUVerFrame* ) { return NULL; } + virtual Double measure( PlaYUVerFrame* ) { return 0; } /** * Module API version 2 */ - virtual Bool create( std::vector apcFrameList ) - { - return false; - } - virtual PlaYUVerFrame* process( std::vector ) - { - return NULL; - } - virtual Double measure( std::vector ) - { - return 0; - } - - virtual Bool keyPressed( enum Module_Key_Supported ) - { - return false; - } - + virtual Bool create( std::vector apcFrameList ) { return false; } + virtual PlaYUVerFrame* process( std::vector ) { return NULL; } + virtual Double measure( std::vector ) { return 0; } + virtual Bool keyPressed( enum Module_Key_Supported ) { return false; } }; -#endif // __PLAYUVERMODULESIF_H__ - +#endif // __PLAYUVERMODULESIF_H__ diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index 550fa6b..f3d47f6 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -47,48 +47,30 @@ using namespace std; -struct ParseFailure: public std::exception +struct ParseFailure : public std::exception { String arg; String val; - ParseFailure( String arg0, String val0 ) throw() : - arg( arg0 ), - val( val0 ) - { - } - ~ParseFailure() throw() - { - } - const Char* what() const throw() - { - return "Option Parse Failure"; - } + ParseFailure( String arg0, String val0 ) throw() : arg( arg0 ), val( val0 ) {} + ~ParseFailure() throw() {} + const Char* what() const throw() { return "Option Parse Failure"; } }; /** Type specific option storage */ -class BoolOption: public OptionBase +class BoolOption : public OptionBase { -public: - BoolOption( const String& name, const String& desc ) : - OptionBase( name, desc ) - { - is_binary = true; - } - - void parse( const String& arg ) - { - arg_count++; - } + public: + BoolOption( const String& name, const String& desc ) : OptionBase( name, desc ) { is_binary = true; } + void parse( const String& arg ) { arg_count++; } }; /** Type specific option storage */ -template -class StandardOption: public OptionBase +template +class StandardOption : public OptionBase { -public: - StandardOption( const String& name, T& storage, const String& desc ) : - OptionBase( name, desc ), - opt_storage( storage ) + public: + StandardOption( const String& name, T& storage, const String& desc ) + : OptionBase( name, desc ), opt_storage( storage ) { is_binary = false; } @@ -99,7 +81,7 @@ public: }; /* Generic parsing */ -template +template inline void StandardOption::parse( const String& arg ) { if( !is_binary ) @@ -118,7 +100,7 @@ inline void StandardOption::parse( const String& arg ) arg_count++; } -template<> +template <> inline void StandardOption >::parse( const String& arg ) { UInt aux_opt_storage; @@ -136,7 +118,7 @@ inline void StandardOption >::parse( const String& arg ) arg_count++; } -template<> +template <> inline void StandardOption >::parse( const String& arg ) { Int aux_opt_storage; @@ -155,7 +137,7 @@ inline void StandardOption >::parse( const String& arg ) } /* string parsing is specialized */ -template<> +template <> inline void StandardOption::parse( const String& arg ) { opt_storage = arg; @@ -163,7 +145,7 @@ inline void StandardOption::parse( const String& arg ) } /* string vector parsing is specialized */ -template<> +template <> inline void StandardOption >::parse( const String& arg ) { opt_storage.push_back( arg ); @@ -171,15 +153,13 @@ inline void StandardOption >::parse( const String& arg ) } /** Option class for argument handling using a user provided function */ -struct FunctionOption: public OptionBase +struct FunctionOption : public OptionBase { -public: - typedef Void (Func)( PlaYUVerOptions&, const String& ); + public: + typedef Void( Func )( PlaYUVerOptions&, const String& ); - FunctionOption( const String& name, PlaYUVerOptions& parent_, Func *func_, const String& desc ) : - OptionBase( name, desc ), - parent( parent_ ), - func( func_ ) + FunctionOption( const String& name, PlaYUVerOptions& parent_, Func* func_, const String& desc ) + : OptionBase( name, desc ), parent( parent_ ), func( func_ ) { is_binary = false; } @@ -190,9 +170,9 @@ public: arg_count++; } -private: + private: PlaYUVerOptions& parent; - void (*func)( PlaYUVerOptions&, const String& ); + void ( *func )( PlaYUVerOptions&, const String& ); }; /* Helper method to initiate adding options to Options */ @@ -214,7 +194,7 @@ PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, const String& * with storage for the option's value * with desc as an optional help description */ -template +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, T& storage, const String& desc ) { addOption( new StandardOption( name, storage, desc ) ); @@ -226,9 +206,15 @@ template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, UInt& template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int& storage, const String& desc ); template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int64& storage, const String& desc ); template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, String& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + std::vector& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + std::vector& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + std::vector& storage, + const String& desc ); /** * Add option described by name to the parent Options list, @@ -293,13 +279,13 @@ Bool PlaYUVerOptions::hasOpt( const String& optName ) Void PlaYUVerOptions::addDefaultOptions() { - addOptions()/**/ - ( "help,h", "produce help message" )/**/ - ( "version", "show version and exit" )/**/ - ( "pel_fmts", "list pixel formats" ) /**/ - ( "quality_metrics", "list supported quality metrics" )/**/ - ( "module_list", "list supported modules" ) /**/ - ( "module_list_full", "detailed list supported modules" ); + addOptions() /**/ + ( "help,h", "produce help message" ) /**/ + ( "version", "show version and exit" ) /**/ + ( "pel_fmts", "list pixel formats" ) /**/ + ( "quality_metrics", "list supported quality metrics" ) /**/ + ( "module_list", "list supported modules" ) /**/ + ( "module_list_full", "detailed list supported modules" ); } PlaYUVerOptions& PlaYUVerOptions::addOptions() @@ -307,7 +293,7 @@ PlaYUVerOptions& PlaYUVerOptions::addOptions() return *this; } -void PlaYUVerOptions::addOption( OptionBase *opt ) +void PlaYUVerOptions::addOption( OptionBase* opt ) { Option* names = new Option(); names->opt = opt; @@ -377,12 +363,7 @@ Bool PlaYUVerOptions::storePair( Bool allow_long, Bool allow_short, const string if( !m_bAllowUnkonw ) { /* not found */ - cerr << "Unknown option: `" - << name - << "' (value:`" - << value - << "')" - << endl; + cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl; } return false; } @@ -413,8 +394,8 @@ UInt PlaYUVerOptions::parseLONG( UInt argc, Char* argv[] ) UInt extra_argc_consumed = 0; if( arg_opt_sep == string::npos ) { - /* no argument found => argument in argv[1] (maybe) */ - /* xxx, need to handle case where option isn't required */ +/* no argument found => argument in argv[1] (maybe) */ +/* xxx, need to handle case where option isn't required */ #if 0 /* commented out, to return to true GNU style processing * where longopts have to include an =, otherwise they are @@ -484,10 +465,7 @@ UInt PlaYUVerOptions::parseSHORT( UInt argc, Char* argv[] ) /* xxx, need to handle case where option isn't required */ if( argc == 1 ) { - cerr << "Not processing option without argument `" - << option - << "'" - << endl; + cerr << "Not processing option without argument `" << option << "'" << endl; return 0; /* run out of argv for argument */ } storePair( false, true, option, string( argv[1] ) ); @@ -495,7 +473,7 @@ UInt PlaYUVerOptions::parseSHORT( UInt argc, Char* argv[] ) return 1; } -Bool PlaYUVerOptions::parse( UInt argc, Char *argv[] ) +Bool PlaYUVerOptions::parse( UInt argc, Char* argv[] ) { try { @@ -508,9 +486,7 @@ Bool PlaYUVerOptions::parse( UInt argc, Char *argv[] ) } catch( std::exception& e ) { - std::cerr << "error: " - << e.what() - << "\n"; + std::cerr << "error: " << e.what() << "\n"; return false; } catch( ... ) @@ -520,7 +496,7 @@ Bool PlaYUVerOptions::parse( UInt argc, Char *argv[] ) return true; } -list PlaYUVerOptions::scanArgv( UInt argc, Char *argv[] ) +list PlaYUVerOptions::scanArgv( UInt argc, Char* argv[] ) { /* a list for anything that didn't get handled as an option */ list non_option_arguments; @@ -542,7 +518,7 @@ list PlaYUVerOptions::scanArgv( UInt argc, Char *argv[] ) if( argv[i][1] != '-' ) { - /* handle short (single dash) options */ +/* handle short (single dash) options */ #if 0 i += parsePOSIX( opts, argc - i, &argv[i] ); #else @@ -587,9 +563,8 @@ static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, UInt if( !entry.opt_short.empty() ) { - UInt pad = max( ( int )pad_short - ( int )entry.opt_short.front().size(), 0 ); - out << "-" - << entry.opt_short.front(); + UInt pad = max( (int)pad_short - (int)entry.opt_short.front().size(), 0 ); + out << "-" << entry.opt_short.front(); if( !entry.opt_long.empty() ) { out << ", "; @@ -604,8 +579,7 @@ static void doHelpOpt( ostream& out, const PlaYUVerOptions::Option& entry, UInt if( !entry.opt_long.empty() ) { - out << "--" - << entry.opt_long.front(); + out << "--" << entry.opt_long.front(); } } @@ -619,7 +593,7 @@ Void PlaYUVerOptions::doHelp( ostream& out, UInt columns ) { ostringstream line( ios_base::out ); doHelpOpt( line, **it, pad_short ); - max_width = max( max_width, ( UInt )line.tellp() ); + max_width = max( max_width, (UInt)line.tellp() ); } UInt opt_width = min( max_width + 2, 28u + pad_short ) + 2; @@ -640,8 +614,7 @@ Void PlaYUVerOptions::doHelp( ostream& out, UInt columns ) if( opt_desc.empty() ) { /* no help text: output option, skip further processing */ - cout << line.str() - << endl; + cout << line.str() << endl; continue; } size_t currlength = size_t( line.tellp() ); @@ -703,8 +676,7 @@ Void PlaYUVerOptions::doHelp( ostream& out, UInt columns ) line << endl; } - cout << line.str() - << endl; + cout << line.str() << endl; } } @@ -714,9 +686,7 @@ Bool PlaYUVerOptions::checkListingOpts() if( hasOpt( "version" ) ) { - std::cout << "PlaYUVer version " - << PLAYUVER_VERSION_STRING - << "\n"; + std::cout << "PlaYUVer version " << PLAYUVER_VERSION_STRING << "\n"; bRet |= true; } if( hasOpt( "pel_fmts" ) ) @@ -786,12 +756,12 @@ Void PlaYUVerOptions::listModules() printf( " %-40s", ModuleNameString ); switch( pcCurrModuleIf->m_iModuleType ) { - case FRAME_PROCESSING_MODULE: - printf( " Processing " ); - break; - case FRAME_MEASUREMENT_MODULE: - printf( " Measurement " ); - break; + case FRAME_PROCESSING_MODULE: + printf( " Processing " ); + break; + case FRAME_MEASUREMENT_MODULE: + printf( " Measurement " ); + break; } printf( " %s", pcCurrModuleIf->m_pchModuleTooltip ); pcCurrModuleIf->Delete(); @@ -799,4 +769,3 @@ Void PlaYUVerOptions::listModules() printf( "\n" ); } } - diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index c6118d7..ac7db10 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -50,29 +50,13 @@ */ class OptionBase { -public: - OptionBase( const String& name, const String& desc ) : - arg_count( 0 ), - opt_string( name ), - opt_desc( desc ) - { - } - - virtual ~OptionBase() - { - } - + public: + OptionBase( const String& name, const String& desc ) : arg_count( 0 ), opt_string( name ), opt_desc( desc ) {} + virtual ~OptionBase() {} /* parse argument arg, to obtain a value for the option */ virtual void parse( const String& arg ) = 0; - Int count() - { - return arg_count; - } - Bool isBinary() - { - return is_binary; - } - + Int count() { return arg_count; } + Bool isBinary() { return is_binary; } int arg_count; String opt_string; String opt_desc; @@ -81,14 +65,10 @@ public: class PlaYUVerOptions { -public: - + public: struct Option { - Option() : - opt( 0 ) - { - } + Option() : opt( 0 ) {} ~Option() { if( opt ) @@ -104,14 +84,10 @@ public: PlaYUVerOptions( const String& name = "" ); ~PlaYUVerOptions(); - Bool parse( UInt argc, Char *argv[] ); + Bool parse( UInt argc, Char* argv[] ); Void parse( std::vector args_array ); - std::list& getUnhandledArgs() - { - return m_aUnhandledArgs; - } - + std::list& getUnhandledArgs() { return m_aUnhandledArgs; } Void doHelp( std::ostream& out, unsigned columns = 80 ); OptionBase* operator[]( const String& optName ); @@ -119,14 +95,10 @@ public: Bool hasOpt( const String& optName ); - OptionsList getOptionList() - { - return opt_list; - } - + OptionsList getOptionList() { return opt_list; } Void addDefaultOptions(); PlaYUVerOptions& addOptions(); - void addOption( OptionBase *opt ); + void addOption( OptionBase* opt ); /** * Add option described by name to the parent Options list, @@ -134,8 +106,7 @@ public: * with default_val as the default value * with desc as an optional help description */ - PlaYUVerOptions& - operator()( const String& name, const String& desc ); + PlaYUVerOptions& operator()( const String& name, const String& desc ); /** * Add option described by name to the parent Options list, @@ -143,9 +114,8 @@ public: * with default_val as the default value * with desc as an optional help description */ - template - PlaYUVerOptions& - operator()( const String& name, T& storage, const String& desc ); + template + PlaYUVerOptions& operator()( const String& name, T& storage, const String& desc ); /** * Add option described by name to the parent Options list, @@ -154,13 +124,13 @@ public: * OptionFunc::Func is called. It is upto this function to correctly * handle evaluating the option's value. */ -// PlaYUVerOptions& -// operator()( const String& name, OptionFunc::Func *func, const String& desc ); + // PlaYUVerOptions& + // operator()( const String& name, OptionFunc::Func *func, const String& desc ); Bool checkListingOpts(); Void listModules(); -private: + private: typedef std::map OptionMap; OptionMap opt_long_map; OptionMap opt_short_map; @@ -177,7 +147,6 @@ private: UInt parseLONG( String arg ); UInt parseSHORT( UInt argc, Char* argv[] ); std::list scanArgv( UInt argc, Char* argv[] ); - }; -#endif // __PROGRAMOPTIONS_H__ +#endif // __PROGRAMOPTIONS_H__ diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index 4f85907..aca4381 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -27,8 +27,7 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" -PlaYUVerPixel::PlaYUVerPixel() : - m_iColorSpace( COLOR_INVALID ) +PlaYUVerPixel::PlaYUVerPixel() : m_iColorSpace( COLOR_INVALID ) { m_iColorSpace = COLOR_INVALID; PixelComponents[0] = 0; @@ -108,7 +107,7 @@ Pel& PlaYUVerPixel::B() } Pel PlaYUVerPixel::operator[]( const Int& channel ) const - { +{ return PixelComponents[channel]; } Pel& PlaYUVerPixel::operator[]( const Int& channel ) @@ -158,4 +157,3 @@ PlaYUVerPixel PlaYUVerPixel::ConvertPixel( ColorSpace eOutputSpace ) } return outPixel; } - diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index ca3281a..5e2200d 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,7 +31,7 @@ #include #include "PlaYUVerDefs.h" -static inline Void YuvToRgb( const Int &iY, const Int &iU, const Int &iV, Int &iR, Int &iG, Int &iB ) +static inline Void YuvToRgb( const Int& iY, const Int& iU, const Int& iV, Int& iR, Int& iG, Int& iB ) { iR = iY + ( ( 1436 * ( iV - 128 ) ) >> 10 ); iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); @@ -41,7 +41,7 @@ static inline Void YuvToRgb( const Int &iY, const Int &iU, const Int &iV, Int &i iB = iB < 0 ? 0 : iB > 255 ? 255 : iB; } -static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int &iY, Int &iU, Int &iV ) +static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int& iY, Int& iU, Int& iV ) { iY = ( 299 * iR + 587 * iG + 114 * iB + 500 ) / 1000; iU = ( 1000 * ( iB - iY ) + 226816 ) / 1772; @@ -55,8 +55,7 @@ static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int &i */ class PlaYUVerPixel { -public: - + public: static const UInt MAX_NUMBER_COMPONENTS = 5; /** ColorSpace list @@ -65,11 +64,11 @@ public: enum ColorSpace { COLOR_INVALID = -1, //!< Invalid - COLOR_YUV = 0, //!< YUV - COLOR_RGB = 1, //!< RGB - COLOR_GRAY = 2, //!< Grayscale - COLOR_ARGB = 3, //!< RGB + Alpha - COLOR_MAX = 255, //!< Accouunt for future formats + COLOR_YUV = 0, //!< YUV + COLOR_RGB = 1, //!< RGB + COLOR_GRAY = 2, //!< Grayscale + COLOR_ARGB = 3, //!< RGB + Alpha + COLOR_MAX = 255, //!< Accouunt for future formats }; PlaYUVerPixel(); @@ -110,9 +109,9 @@ public: */ PlaYUVerPixel ConvertPixel( ColorSpace eOutputSpace ); -private: + private: Int m_iColorSpace; Pel PixelComponents[MAX_NUMBER_COMPONENTS]; }; -#endif // __PLAYUVERPIXEL_H__ +#endif // __PLAYUVERPIXEL_H__ diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index ff26c03..d233d1d 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -42,7 +42,6 @@ #include "StreamHandlerOpenCV.h" #endif - std::vector PlaYUVerStream::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -78,12 +77,11 @@ std::vector PlaYUVerStream::supportedWriteFormats() std::vector PlaYUVerStream::stdResolutionSizes() { - -#define REGIST_PLAYUVER_STANDARD_RESOLUTION( name, width, height) \ - stdResElement.shortName = name; \ - stdResElement.uiWidth = width; \ - stdResElement.uiHeight = height; \ - stdResList.push_back( stdResElement ); +#define REGIST_PLAYUVER_STANDARD_RESOLUTION( name, width, height ) \ + stdResElement.shortName = name; \ + stdResElement.uiWidth = width; \ + stdResElement.uiHeight = height; \ + stdResList.push_back( stdResElement ); std::vector stdResList; PlaYUVerStdResolution stdResElement; @@ -122,10 +120,10 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo { return supportedFmts[i].formatFct; } -// else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) -// { -// return supportedFmts[i].formatFct; -// } + // else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) + // { + // return supportedFmts[i].formatFct; + // } } return &StreamHandlerRaw::Create; } @@ -162,7 +160,13 @@ String PlaYUVerStream::getCodecName() return !m_pcHandler ? "" : m_pcHandler->getCodecName(); } -Bool PlaYUVerStream::open( String filename, String resolution, String input_format_name, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( String filename, + String resolution, + String input_format_name, + UInt bitsPel, + Int endianness, + UInt frame_rate, + Bool bInput ) { UInt width = 0; UInt height = 0; @@ -187,7 +191,14 @@ Bool PlaYUVerStream::open( String filename, String resolution, String input_form return open( filename, width, height, input_format, bitsPel, endianness, frame_rate, bInput ); } -Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ) +Bool PlaYUVerStream::open( String filename, + UInt width, + UInt height, + Int input_format, + UInt bitsPel, + Int endianness, + UInt frame_rate, + Bool bInput ) { if( m_bInit ) { @@ -240,7 +251,8 @@ Bool PlaYUVerStream::open( String filename, UInt width, UInt height, Int input_f { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, + m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); } catch( PlaYUVerFailure& e ) { @@ -292,8 +304,8 @@ Bool PlaYUVerStream::reload() m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); - if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 - || m_pcHandler->m_iPixelFormat < 0 || m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) + if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 || + m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) { return false; } @@ -362,7 +374,12 @@ Int PlaYUVerStream::getCurrFrameNum() return m_iCurrFrameNum; } -Void PlaYUVerStream::getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ) +Void PlaYUVerStream::getFormat( UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBitsPerPel, + Int& rEndianness, + UInt& rFrameRate ) { if( m_bInit ) { @@ -404,7 +421,8 @@ Void PlaYUVerStream::loadAll() getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, + m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); if( !m_ppcFrameBuffer[i] ) { close(); @@ -428,25 +446,25 @@ Void PlaYUVerStream::loadAll() Void PlaYUVerStream::getDuration( Int* duration_array ) { -// Int hours, mins, secs = 0; -// #ifdef USE_FFMPEG -// if( m_iStreamHandler == FFMPEG ) -// { -// secs = m_cLibAvContext->getStreamDuration(); -// } -// else -// #endif -// if( m_iStreamHandler == YUV_IO ) -// { -// secs = m_uiTotalFrameNum / m_dFrameRate; -// } -// mins = secs / 60; -// secs %= 60; -// hours = mins / 60; -// mins %= 60; -// *duration_array++ = hours; -// *duration_array++ = mins; -// *duration_array++ = secs; + // Int hours, mins, secs = 0; + // #ifdef USE_FFMPEG + // if( m_iStreamHandler == FFMPEG ) + // { + // secs = m_cLibAvContext->getStreamDuration(); + // } + // else + // #endif + // if( m_iStreamHandler == YUV_IO ) + // { + // secs = m_uiTotalFrameNum / m_dFrameRate; + // } + // mins = secs / 60; + // secs %= 60; + // hours = mins / 60; + // mins %= 60; + // *duration_array++ = hours; + // *duration_array++ = mins; + // *duration_array++ = secs; } Void PlaYUVerStream::readFrameFillRGBBuffer() @@ -483,7 +501,7 @@ Void PlaYUVerStream::writeFrame() writeFrame( m_pcCurrFrame ); } -Void PlaYUVerStream::writeFrame( PlaYUVerFrame *pcFrame ) +Void PlaYUVerStream::writeFrame( PlaYUVerFrame* pcFrame ) { if( !m_pcHandler->write( pcFrame ) ) { @@ -497,11 +515,11 @@ Bool PlaYUVerStream::saveFrame( const String& filename ) return saveFrame( filename, m_pcCurrFrame ); } -Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame *saveFrame ) +Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame* saveFrame ) { PlaYUVerStream auxSaveStream; - if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), saveFrame->getBitsPel(), - PLAYUVER_LITTLE_ENDIAN, 1, false ) ) + if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), + saveFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ) ) { return false; } @@ -538,7 +556,7 @@ Bool PlaYUVerStream::setNextFrame() return bEndOfSeq; } -PlaYUVerFrame* PlaYUVerStream::getCurrFrame( PlaYUVerFrame *pyuv_image ) +PlaYUVerFrame* PlaYUVerStream::getCurrFrame( PlaYUVerFrame* pyuv_image ) { if( pyuv_image == NULL ) pyuv_image = new PlaYUVerFrame( m_pcCurrFrame ); @@ -578,7 +596,7 @@ Bool PlaYUVerStream::seekInputRelative( Bool bIsFoward ) Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) { - if( !m_bInit || new_frame_num >= m_uiTotalFrameNum || ( Int64 )new_frame_num == m_iCurrFrameNum ) + if( !m_bInit || new_frame_num >= m_uiTotalFrameNum || (Int64)new_frame_num == m_iCurrFrameNum ) return false; m_iCurrFrameNum = new_frame_num - 1; @@ -607,4 +625,3 @@ Bool PlaYUVerStream::seekInput( UInt64 new_frame_num ) readFrame(); return true; } - diff --git a/lib/PlaYUVerStream.h b/lib/PlaYUVerStream.h index 2be47e0..8e140fc 100644 --- a/lib/PlaYUVerStream.h +++ b/lib/PlaYUVerStream.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -37,7 +37,7 @@ typedef struct UInt uiHeight; } PlaYUVerStdResolution; -typedef PlaYUVerStreamHandlerIf* (*CreateStreamHandlerFn)( void ); +typedef PlaYUVerStreamHandlerIf* ( *CreateStreamHandlerFn )( void ); typedef struct { @@ -46,23 +46,22 @@ typedef struct CreateStreamHandlerFn formatFct; } PlaYUVerSupportedFormat; -#define INI_REGIST_PLAYUVER_SUPPORTED_FMT \ +#define INI_REGIST_PLAYUVER_SUPPORTED_FMT \ std::vector formatsList; \ PlaYUVerSupportedFormat formatElem; -#define END_REGIST_PLAYUVER_SUPPORTED_FMT \ - return formatsList; +#define END_REGIST_PLAYUVER_SUPPORTED_FMT return formatsList; #define REGIST_PLAYUVER_SUPPORTED_FMT( handler, name, ext ) \ - formatElem.formatName = name; \ - formatElem.formatExt = lowercase( ext ); \ - formatElem.formatFct = handler; \ - formatsList.push_back( formatElem ); + formatElem.formatName = name; \ + formatElem.formatExt = lowercase( ext ); \ + formatElem.formatFct = handler; \ + formatsList.push_back( formatElem ); -#define APPEND_PLAYUVER_SUPPORTED_FMT( class_name, fct ) \ - { \ +#define APPEND_PLAYUVER_SUPPORTED_FMT( class_name, fct ) \ + { \ std::vector new_fmts = class_name::supported##fct##Formats(); \ - formatsList.insert( formatsList.end(), new_fmts.begin(), new_fmts.end() ); \ + formatsList.insert( formatsList.end(), new_fmts.begin(), new_fmts.end() ); \ } /** @@ -72,8 +71,7 @@ typedef struct */ class PlaYUVerStream { -public: - + public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); @@ -96,8 +94,21 @@ public: String getFormatName(); String getCodecName(); - Bool open( String filename, String resolution, String input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); - Bool open( String filename, UInt width, UInt height, Int input_format, UInt bitsPel, Int endianness, UInt frame_rate, Bool bInput ); + Bool open( String filename, + String resolution, + String input_format, + UInt bitsPel, + Int endianness, + UInt frame_rate, + Bool bInput ); + Bool open( String filename, + UInt width, + UInt height, + Int input_format, + UInt bitsPel, + Int endianness, + UInt frame_rate, + Bool bInput ); Bool reload(); Void close(); @@ -108,35 +119,35 @@ public: Int getEndianess() const; Int getCurrFrameNum(); Double getFrameRate(); - Void getFormat( UInt& rWidth, UInt& rHeight, Int& rInputFormat, UInt& rBitsPerPel, Int& rEndianness, UInt& rFrameRate ); + Void getFormat( UInt& rWidth, + UInt& rHeight, + Int& rInputFormat, + UInt& rBitsPerPel, + Int& rEndianness, + UInt& rFrameRate ); Void loadAll(); Void readFrame(); Void readFrameFillRGBBuffer(); Void writeFrame(); - Void writeFrame( PlaYUVerFrame *pcFrame ); + Void writeFrame( PlaYUVerFrame* pcFrame ); Bool saveFrame( const String& filename ); - static Bool saveFrame( const String& filename, PlaYUVerFrame *saveFrame ); + static Bool saveFrame( const String& filename, PlaYUVerFrame* saveFrame ); Bool setNextFrame(); PlaYUVerFrame* getCurrFrame(); - PlaYUVerFrame* getCurrFrame( PlaYUVerFrame * ); + PlaYUVerFrame* getCurrFrame( PlaYUVerFrame* ); PlaYUVerFrame* getNextFrame(); Bool seekInputRelative( Bool bIsFoward ); Bool seekInput( UInt64 new_frame_num ); - Bool isInit() - { - return m_bInit; - } - + Bool isInit() { return m_bInit; } Void getDuration( Int* duration_array ); -private: - + private: Bool m_bInit; CreateStreamHandlerFn m_pfctCreateHandler; PlaYUVerStreamHandlerIf* m_pcHandler; @@ -149,12 +160,11 @@ private: Bool m_bLoadAll; UInt m_uiFrameBufferSize; - PlaYUVerFrame **m_ppcFrameBuffer; - PlaYUVerFrame *m_pcCurrFrame; - PlaYUVerFrame *m_pcNextFrame; + PlaYUVerFrame** m_ppcFrameBuffer; + PlaYUVerFrame* m_pcCurrFrame; + PlaYUVerFrame* m_pcNextFrame; UInt m_uiFrameBufferIndex; UInt64 m_uiCurrFrameFileIdx; - }; -#endif // __PLAYUVERSTREAM_H__ +#endif // __PLAYUVERSTREAM_H__ diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index e886c12..3d73c2c 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,11 +30,10 @@ class PlaYUVerFrame; -#define REGISTER_STREAM_HANDLER(X) \ - public: \ - static PlaYUVerStreamHandlerIf* Create() { return new X(); } \ - void Delete() { delete this; } - +#define REGISTER_STREAM_HANDLER( X ) \ + public: \ + static PlaYUVerStreamHandlerIf* Create() { return new X(); } \ + void Delete() { delete this; } /** * \class PlaYUVerStreamHandlerIf * \ingroup PlaYUVerLib_Stream @@ -43,7 +42,8 @@ class PlaYUVerFrame; class PlaYUVerStreamHandlerIf { friend class PlaYUVerStream; - public: + + public: PlaYUVerStreamHandlerIf() { m_bIsInput = true; @@ -54,10 +54,7 @@ class PlaYUVerStreamHandlerIf m_iEndianness = -1; m_dFrameRate = 30; } - virtual ~PlaYUVerStreamHandlerIf() - { - } - + virtual ~PlaYUVerStreamHandlerIf() {} virtual void Delete() = 0; virtual Bool openHandler( String strFilename, Bool bInput ) = 0; @@ -68,20 +65,10 @@ class PlaYUVerStreamHandlerIf virtual Bool read( PlaYUVerFrame* pcFrame ) = 0; virtual Bool write( PlaYUVerFrame* pcFrame ) = 0; - Void setBytesPerFrame( UInt64 uiNBytes ) - { - m_uiNBytesPerFrame = uiNBytes; - } - String getFormatName() - { - return m_strFormatName; - } - String getCodecName() - { - return m_strCodecName; - } - -protected: + Void setBytesPerFrame( UInt64 uiNBytes ) { m_uiNBytesPerFrame = uiNBytes; } + String getFormatName() { return m_strFormatName; } + String getCodecName() { return m_strCodecName; } + protected: Bool m_bIsInput; String m_cFilename; UInt m_uiWidth; @@ -97,5 +84,4 @@ protected: String m_strCodecName; }; -#endif // __PLAYUVERSTREAMHANDLERIF_H__ - +#endif // __PLAYUVERSTREAMHANDLERIF_H__ diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 8afb14f..aa373b3 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -35,12 +35,12 @@ std::vector StreamHandlerLibav::supportedReadFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Tagged Image File Format", "tiff" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -50,12 +50,12 @@ std::vector StreamHandlerLibav::supportedWriteFormats() END_REGIST_PLAYUVER_SUPPORTED_FMT; } -static int open_codec_context( int *stream_idx, AVFormatContext *m_cFmtCtx, enum AVMediaType type ) +static int open_codec_context( int* stream_idx, AVFormatContext* m_cFmtCtx, enum AVMediaType type ) { int ret; - AVStream *st; - AVCodecContext *dec_ctx = NULL; - AVCodec *dec = NULL; + AVStream* st; + AVCodecContext* dec_ctx = NULL; + AVCodec* dec = NULL; ret = av_find_best_stream( m_cFmtCtx, type, -1, -1, NULL, 0 ); if( ret < 0 ) @@ -93,43 +93,43 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) m_cFmtCtx = NULL; m_cCodecCtx = NULL; m_cStream = NULL; -// video_dst_data[0] = NULL; -// video_dst_data[1] = NULL; -// video_dst_data[2] = NULL; -// video_dst_data[3] = NULL; + // video_dst_data[0] = NULL; + // video_dst_data[1] = NULL; + // video_dst_data[2] = NULL; + // video_dst_data[3] = NULL; m_iStreamIdx = -1; m_cFrame = NULL; m_bHasStream = false; - AVDictionary *format_opts = NULL; + AVDictionary* format_opts = NULL; /* register all formats and codecs */ av_register_all(); -// if( width > 0 && height > 0 ) -// { -// Char aux_string[10]; -// sprintf( aux_string, "%dx%d", width, height ); -// av_dict_set( &format_opts, "video_size", aux_string, 0 ); -// } + // if( width > 0 && height > 0 ) + // { + // Char aux_string[10]; + // sprintf( aux_string, "%dx%d", width, height ); + // av_dict_set( &format_opts, "video_size", aux_string, 0 ); + // } -// Int ffmpeg_pel_format = g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; -// if( ffmpeg_pel_format >= 0 ) -// { -// av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( AVPixelFormat( ffmpeg_pel_format ) ), 0 ); -// } + // Int ffmpeg_pel_format = g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; + // if( ffmpeg_pel_format >= 0 ) + // { + // av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( AVPixelFormat( ffmpeg_pel_format ) ), 0 ); + // } /* open input file, and allocate format context */ if( avformat_open_input( &m_cFmtCtx, filename, NULL, &format_opts ) < 0 ) { - //qDebug( ) << " Could not open source file %s !!!" << filename << endl; + // qDebug( ) << " Could not open source file %s !!!" << filename << endl; return false; } /* retrieve stream information */ if( avformat_find_stream_info( m_cFmtCtx, NULL ) < 0 ) { - //qDebug( ) << " Could not find stream information !!!" << endl; + // qDebug( ) << " Could not find stream information !!!" << endl; return false; } @@ -138,23 +138,24 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) m_cStream = m_cFmtCtx->streams[m_iStreamIdx]; m_cCodecCtx = m_cStream->codec; -// /* allocate image where the decoded image will be put */ -// ret = av_image_alloc( video_dst_data, video_dst_linesize, m_cCodecCtx->width, m_cCodecCtx->height, m_cCodecCtx->pix_fmt, 1 ); -// if( ret < 0 ) -// { -// //qDebug( ) << " Could not allocate raw video buffer !!!" << endl; -// closeAvFormat(); -// return false; -// } -// video_dst_bufsize = ret; + // /* allocate image where the decoded image will be put */ + // ret = av_image_alloc( video_dst_data, video_dst_linesize, m_cCodecCtx->width, m_cCodecCtx->height, + // m_cCodecCtx->pix_fmt, 1 ); + // if( ret < 0 ) + // { + // //qDebug( ) << " Could not allocate raw video buffer !!!" << endl; + // closeAvFormat(); + // return false; + // } + // video_dst_bufsize = ret; m_uiFrameBufferSize = av_image_get_buffer_size( m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); - const char *name = avcodec_get_name( m_cCodecCtx->codec_id ); -// sprintf( m_acCodecName, "%s", name ); + const char* name = avcodec_get_name( m_cCodecCtx->codec_id ); + // sprintf( m_acCodecName, "%s", name ); m_strCodecName = name; Double fr = 30; @@ -181,24 +182,24 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) */ switch( pix_fmt ) { - case AV_PIX_FMT_YUVJ420P: - pix_fmt = AV_PIX_FMT_YUV420P; - break; - case AV_PIX_FMT_YUVJ422P: - pix_fmt = AV_PIX_FMT_YUV422P; - break; - case AV_PIX_FMT_YUVJ444P: - pix_fmt = AV_PIX_FMT_YUV444P; - break; - case AV_PIX_FMT_GRAY16LE: - m_uiBitsPerPixel = 16; - m_iEndianness = 1; - pix_fmt = AV_PIX_FMT_GRAY8; - break; - case AV_PIX_FMT_GRAY16BE: - m_uiBitsPerPixel = 16; - m_iEndianness = 0; - pix_fmt = AV_PIX_FMT_GRAY8; + case AV_PIX_FMT_YUVJ420P: + pix_fmt = AV_PIX_FMT_YUV420P; + break; + case AV_PIX_FMT_YUVJ422P: + pix_fmt = AV_PIX_FMT_YUV422P; + break; + case AV_PIX_FMT_YUVJ444P: + pix_fmt = AV_PIX_FMT_YUV444P; + break; + case AV_PIX_FMT_GRAY16LE: + m_uiBitsPerPixel = 16; + m_iEndianness = 1; + pix_fmt = AV_PIX_FMT_GRAY8; + break; + case AV_PIX_FMT_GRAY16BE: + m_uiBitsPerPixel = 16; + m_iEndianness = 0; + pix_fmt = AV_PIX_FMT_GRAY8; } m_uiWidth = m_cCodecCtx->width; @@ -223,7 +224,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) av_dump_format( m_cFmtCtx, 0, filename, 0 ); if( !m_cStream ) { - //qDebug( ) << " Could not find audio or video stream in the input, aborting !!!" << endl; + // qDebug( ) << " Could not find audio or video stream in the input, aborting !!!" << endl; closeHandler(); return false; } @@ -265,7 +266,6 @@ Void StreamHandlerLibav::closeHandler() if( m_pStreamBuffer ) freeMem1D( m_pStreamBuffer ); - } Bool StreamHandlerLibav::configureBuffer( PlaYUVerFrame* pcFrame ) @@ -276,11 +276,11 @@ Bool StreamHandlerLibav::configureBuffer( PlaYUVerFrame* pcFrame ) UInt64 StreamHandlerLibav::calculateFrameNumber() { UInt64 num_frames; -// if( m_cStream->nb_frames ) -// { * -// num_frames = m_cStream->nb_frames; -// } -// else + // if( m_cStream->nb_frames ) + // { * + // num_frames = m_cStream->nb_frames; + // } + // else if( m_cFmtCtx->duration != AV_NOPTS_VALUE ) { Int64 duration = m_cFmtCtx->duration + 5000; @@ -334,8 +334,7 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) bGotFrame |= decodeVideoPkt(); if( bGotFrame ) break; - } - while( pkt.size > 0 ); + } while( pkt.size > 0 ); if( bGotFrame ) { @@ -351,10 +350,11 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) if( bGotFrame ) { -// av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, -// m_cCodecCtx->height, 1 ); - av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, - m_cCodecCtx->height, 1 ); + // av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, + // m_cCodecCtx->pix_fmt, m_cCodecCtx->width, + // m_cCodecCtx->height, 1 ); + av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, + m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); @@ -376,4 +376,3 @@ Bool StreamHandlerLibav::seek( UInt64 iFrameNum ) av_seek_frame( m_cFmtCtx, m_iStreamIdx, iFrameNum, AVSEEK_FLAG_FRAME ); return true; } - diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 4e23c94..6e1934d 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,15 +30,14 @@ #include #ifndef __PRI64_PREFIX -#define __PRI64_PREFIX "l" +#define __PRI64_PREFIX "l" #endif #ifndef PRId64 -#define PRId64 __PRI64_PREFIX "d" +#define PRId64 __PRI64_PREFIX "d" #endif -extern "C" -{ +extern "C" { #include #include #include @@ -55,22 +54,16 @@ struct AVStream; struct AVStream; struct AVPacket; -class StreamHandlerLibav: public PlaYUVerStreamHandlerIf +class StreamHandlerLibav : public PlaYUVerStreamHandlerIf { -REGISTER_STREAM_HANDLER( StreamHandlerLibav ) - -public: + REGISTER_STREAM_HANDLER( StreamHandlerLibav ) + public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); - StreamHandlerLibav() - { - } - ~StreamHandlerLibav() - { - } - + StreamHandlerLibav() {} + ~StreamHandlerLibav() {} Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); @@ -79,15 +72,11 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - UInt getStreamDuration() - { - return m_uiSecs; - } - + UInt getStreamDuration() { return m_uiSecs; } UChar* m_pchFrameBuffer; UInt64 m_uiFrameBufferSize; -private: + private: AVFormatContext* m_cFmtCtx; AVCodecContext* m_cCodecCtx; AVStream* m_cStream; @@ -103,4 +92,4 @@ private: Bool decodeVideoPkt(); }; -#endif // __LIBAVCONTEXTHANDLE_H__ +#endif // __LIBAVCONTEXTHANDLE_H__ diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 126da05..011a6c1 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -40,7 +40,7 @@ using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; -// REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -149,4 +149,3 @@ Bool StreamHandlerOpenCV::write( PlaYUVerFrame* pcFrame ) } return bRet; } - diff --git a/lib/StreamHandlerOpenCV.h b/lib/StreamHandlerOpenCV.h index 022ae8d..616491e 100644 --- a/lib/StreamHandlerOpenCV.h +++ b/lib/StreamHandlerOpenCV.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -25,7 +25,6 @@ #ifndef __STREAMHANDLEROPENCV_H__ #define __STREAMHANDLEROPENCV_H__ - #include "PlaYUVerDefs.h" #include "PlaYUVerStreamHandlerIf.h" @@ -36,20 +35,16 @@ class VideoCapture; class PlaYUVerFrame; -class StreamHandlerOpenCV: public PlaYUVerStreamHandlerIf +class StreamHandlerOpenCV : public PlaYUVerStreamHandlerIf { -REGISTER_STREAM_HANDLER( StreamHandlerOpenCV ) - -public: + REGISTER_STREAM_HANDLER( StreamHandlerOpenCV ) + public: static std::vector supportedReadFormats(); static std::vector supportedWriteFormats(); StreamHandlerOpenCV(); - ~StreamHandlerOpenCV() - { - } - + ~StreamHandlerOpenCV() {} Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); @@ -58,8 +53,8 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); -private: + private: cv::VideoCapture* pcVideoCapture; }; -#endif // __STREAMHANDLEROPENCV_H__ +#endif // __STREAMHANDLEROPENCV_H__ diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index 2e47cf8..c9c8564 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -117,7 +117,7 @@ Bool StreamHandlerPortableMap::seek( UInt64 iFrameNum ) Bool StreamHandlerPortableMap::read( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; pcFrame->frameFromBuffer( m_pStreamBuffer, PLAYUVER_BIG_ENDIAN ); @@ -133,9 +133,8 @@ Bool StreamHandlerPortableMap::write( PlaYUVerFrame* pcFrame ) fprintf( m_pFile, "%d\n", m_iMaxValue ); } pcFrame->frameToBuffer( m_pStreamBuffer, PLAYUVER_BIG_ENDIAN ); - UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; return true; } - diff --git a/lib/StreamHandlerPortableMap.h b/lib/StreamHandlerPortableMap.h index 7434f69..dae1c02 100644 --- a/lib/StreamHandlerPortableMap.h +++ b/lib/StreamHandlerPortableMap.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,18 +30,13 @@ class PlaYUVerFrame; -class StreamHandlerPortableMap: public PlaYUVerStreamHandlerIf +class StreamHandlerPortableMap : public PlaYUVerStreamHandlerIf { -REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) - -public: - StreamHandlerPortableMap() - { - } - ~StreamHandlerPortableMap() - { - } + REGISTER_STREAM_HANDLER( StreamHandlerPortableMap ) + public: + StreamHandlerPortableMap() {} + ~StreamHandlerPortableMap() {} Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); @@ -50,10 +45,10 @@ public: Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); -private: + private: FILE* m_pFile; /**< The input file pointer >*/ Int m_iMagicNumber; Int m_iMaxValue; }; -#endif // __STREAMHANDLERPORTABLEMAP_H__ +#endif // __STREAMHANDLERPORTABLEMAP_H__ diff --git a/lib/StreamHandlerRaw.cpp b/lib/StreamHandlerRaw.cpp index 1128840..bf34390 100644 --- a/lib/StreamHandlerRaw.cpp +++ b/lib/StreamHandlerRaw.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,7 +30,6 @@ #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" - Bool StreamHandlerRaw::openHandler( String strFilename, Bool bInput ) { m_bIsInput = bInput; @@ -78,7 +77,7 @@ Bool StreamHandlerRaw::seek( UInt64 iFrameNum ) Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) { - UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fread( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; pcFrame->frameFromBuffer( m_pStreamBuffer, m_iEndianness ); @@ -88,9 +87,8 @@ Bool StreamHandlerRaw::read( PlaYUVerFrame* pcFrame ) Bool StreamHandlerRaw::write( PlaYUVerFrame* pcFrame ) { pcFrame->frameToBuffer( m_pStreamBuffer, m_iEndianness ); - UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof(Byte), m_uiNBytesPerFrame, m_pFile ); + UInt64 processed_bytes = fwrite( m_pStreamBuffer, sizeof( Byte ), m_uiNBytesPerFrame, m_pFile ); if( processed_bytes != m_uiNBytesPerFrame ) return false; return true; } - diff --git a/lib/StreamHandlerRaw.h b/lib/StreamHandlerRaw.h index f51e1d4..536811d 100644 --- a/lib/StreamHandlerRaw.h +++ b/lib/StreamHandlerRaw.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -32,21 +32,16 @@ * \class StreamHandlerRaw * \brief Class to handle raw video format */ -class StreamHandlerRaw: public PlaYUVerStreamHandlerIf +class StreamHandlerRaw : public PlaYUVerStreamHandlerIf { -REGISTER_STREAM_HANDLER( StreamHandlerRaw ) + REGISTER_STREAM_HANDLER( StreamHandlerRaw ) -private: + private: FILE* m_pFile; /**< The input file pointer >*/ -public: - StreamHandlerRaw() - { - } - ~StreamHandlerRaw() - { - } - + public: + StreamHandlerRaw() {} + ~StreamHandlerRaw() {} Bool openHandler( String strFilename, Bool bInput ); Void closeHandler(); Bool configureBuffer( PlaYUVerFrame* pcFrame ); @@ -54,8 +49,6 @@ public: Bool seek( UInt64 iFrameNum ); Bool read( PlaYUVerFrame* pcFrame ); Bool write( PlaYUVerFrame* pcFrame ); - }; -#endif // __STREAMHANDLERRAW_H__ - +#endif // __STREAMHANDLERRAW_H__ diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 7ccd587..6d676d4 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,22 +24,21 @@ #include "AbsoluteFrameDifference.h" - AbsoluteFrameDifference::AbsoluteFrameDifference() { /* Module Definition */ - m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). - // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. - m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "AbsoluteFrameDifference"; // Name - m_pchModuleTooltip = "Measure the absolute difference " // Description - "between two images (Y plane), e. g., abs( Y1 - Y2 )"; - m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + // See this example for details on the functions prototype + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "AbsoluteFrameDifference"; // Name + m_pchModuleTooltip = + "Measure the absolute difference " // Description + "between two images (Y plane), e. g., abs( Y1 - Y2 )"; + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. m_pcFrameDifference = NULL; - } Bool AbsoluteFrameDifference::create( std::vector apcFrameList ) @@ -47,10 +46,13 @@ Bool AbsoluteFrameDifference::create( std::vector apcFrameList ) _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) return false; - m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcFrameDifference = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); return true; } @@ -79,4 +81,3 @@ Void AbsoluteFrameDifference::destroy() delete m_pcFrameDifference; m_pcFrameDifference = NULL; } - diff --git a/modules/AbsoluteFrameDifference.h b/modules/AbsoluteFrameDifference.h index e13202a..5b8cfbc 100644 --- a/modules/AbsoluteFrameDifference.h +++ b/modules/AbsoluteFrameDifference.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,24 +28,19 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class AbsoluteFrameDifference: public PlaYUVerModuleIf +class AbsoluteFrameDifference : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( AbsoluteFrameDifference ) + REGISTER_CLASS_FACTORY( AbsoluteFrameDifference ) -private: + private: PlaYUVerFrame* m_pcFrameDifference; -public: + public: AbsoluteFrameDifference(); - virtual ~AbsoluteFrameDifference() - { - } + virtual ~AbsoluteFrameDifference() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __FRAMEDIFFERENCE_H__ - +#endif // __FRAMEDIFFERENCE_H__ diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index 3b6f5e0..378382d 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -35,24 +35,24 @@ DisparityStereoBM::DisparityStereoBM() m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [9]" ); + m_cModuleOptions.addOptions() /**/ + ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [9]" ); m_pcDisparityFrame = NULL; m_uiBlockSize = 9; - } Bool DisparityStereoBM::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); if( ( m_uiBlockSize % 2 ) == 0 ) { m_uiBlockSize++; } m_uiNumberOfDisparities = ( ( apcFrameList[0]->getWidth() / 8 ) + 15 ) & -16; -#if( CV_MAJOR_VERSION == 2) +#if( CV_MAJOR_VERSION == 2 ) m_cStereoBM.state->preFilterCap = 31; m_cStereoBM.state->SADWindowSize = 9; m_cStereoBM.state->minDisparity = 0; @@ -89,7 +89,7 @@ PlaYUVerFrame* DisparityStereoBM::process( std::vector apcFrameL } cv::Mat disparityImage, disparityImage8; -#if( CV_MAJOR_VERSION == 2) +#if( CV_MAJOR_VERSION == 2 ) m_cStereoBM( leftImage, rightImage, disparityImage ); #else m_cStereoBM->compute( leftImage, rightImage, disparityImage ); @@ -107,4 +107,3 @@ Void DisparityStereoBM::destroy() delete m_pcDisparityFrame; m_pcDisparityFrame = NULL; } - diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index fd6fb91..d222b1a 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,31 +31,26 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class DisparityStereoBM: public PlaYUVerModuleIf +class DisparityStereoBM : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( DisparityStereoBM ) + REGISTER_CLASS_FACTORY( DisparityStereoBM ) -private: + private: PlaYUVerFrame* m_pcDisparityFrame; Int m_uiNumberOfDisparities; UInt m_uiBlockSize; - #if( CV_MAJOR_VERSION == 2) +#if( CV_MAJOR_VERSION == 2 ) cv::StereoBM m_cStereoBM; #else cv::Ptr m_cStereoBM; - #endif +#endif -public: + public: DisparityStereoBM(); - virtual ~DisparityStereoBM() - { - } - + virtual ~DisparityStereoBM() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); }; -#endif // __DISPARITYSTEREOBM_H__ - +#endif // __DISPARITYSTEREOBM_H__ diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index a6aa542..b4e0dca 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -35,26 +35,27 @@ DisparityStereoSGBM::DisparityStereoSGBM() m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [3]" )( "HHAlgorithm", m_bUseHH, "Use HH algorithm [false]" ); + m_cModuleOptions.addOptions() /**/ + ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [3]" )( "HHAlgorithm", m_bUseHH, + "Use HH algorithm [false]" ); m_pcDisparityFrame = NULL; m_uiBlockSize = 3; m_uiNumberOfDisparities = 0; - } Bool DisparityStereoSGBM::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); if( ( m_uiBlockSize % 2 ) == 0 ) { m_uiBlockSize++; } m_uiNumberOfDisparities = ( ( apcFrameList[0]->getWidth() / 8 ) + 15 ) & -16; Int cn = apcFrameList[0]->getNumberChannels(); -#if( CV_MAJOR_VERSION == 3) +#if( CV_MAJOR_VERSION == 3 ) m_cStereoMatch = cv::StereoSGBM::create( 0, 16, m_uiBlockSize ); m_cStereoMatch->setPreFilterCap( 63 ); @@ -66,7 +67,7 @@ Bool DisparityStereoSGBM::create( std::vector apcFrameList ) m_cStereoMatch->setSpeckleWindowSize( 100 ); m_cStereoMatch->setSpeckleRange( 32 ); m_cStereoMatch->setDisp12MaxDiff( 1 ); - //m_cStereoMatch->setMode( alg == STEREO_HH ? StereoSGBM::MODE_HH : StereoSGBM::MODE_SGBM ); + // m_cStereoMatch->setMode( alg == STEREO_HH ? StereoSGBM::MODE_HH : StereoSGBM::MODE_SGBM ); m_cStereoMatch->setMode( m_bUseHH ? cv::StereoSGBM::MODE_HH : cv::StereoSGBM::MODE_SGBM ); #else m_cStereoMatch.preFilterCap = 63; @@ -94,7 +95,7 @@ PlaYUVerFrame* DisparityStereoSGBM::process( std::vector apcFram return m_pcDisparityFrame; } cv::Mat disparityImage, disparityImage8; -#if( CV_MAJOR_VERSION == 3) +#if( CV_MAJOR_VERSION == 3 ) m_cStereoMatch->compute( leftImage, rightImage, disparityImage ); #else m_cStereoMatch( leftImage, rightImage, disparityImage ); @@ -110,4 +111,3 @@ Void DisparityStereoSGBM::destroy() delete m_pcDisparityFrame; m_pcDisparityFrame = NULL; } - diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index 51cd170..a86b7aa 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -43,32 +43,27 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class DisparityStereoSGBM: public PlaYUVerModuleIf +class DisparityStereoSGBM : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( DisparityStereoSGBM ) + REGISTER_CLASS_FACTORY( DisparityStereoSGBM ) -private: + private: PlaYUVerFrame* m_pcDisparityFrame; Bool m_bUseHH; Int m_uiNumberOfDisparities; UInt m_uiBlockSize; - #if( CV_MAJOR_VERSION == 3) +#if( CV_MAJOR_VERSION == 3 ) cv::Ptr m_cStereoMatch; - #else +#else cv::StereoSGBM m_cStereoMatch; #endif -public: + public: DisparityStereoSGBM(); - virtual ~DisparityStereoSGBM() - { - } - + virtual ~DisparityStereoSGBM() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); }; -#endif // __DISPARITYSTEREOSGBM_H__ - +#endif // __DISPARITYSTEREOSGBM_H__ diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index 15144d5..ff1ea45 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,8 +36,8 @@ DisparityStereoVar::DisparityStereoVar() m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW; m_pcDisparityFrame = NULL; - m_cStereoVar.levels = 3; // ignored with USE_AUTO_PARAMS - m_cStereoVar.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS + m_cStereoVar.levels = 3; // ignored with USE_AUTO_PARAMS + m_cStereoVar.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS m_cStereoVar.nIt = 25; m_cStereoVar.maxDisp = 0; @@ -45,15 +45,17 @@ DisparityStereoVar::DisparityStereoVar() m_cStereoVar.poly_sigma = 0.0; m_cStereoVar.fi = 15.0f; m_cStereoVar.lambda = 0.03f; - m_cStereoVar.penalization = m_cStereoVar.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS - m_cStereoVar.cycle = m_cStereoVar.CYCLE_V; // ignored with USE_AUTO_PARAMS - m_cStereoVar.flags = m_cStereoVar.USE_SMART_ID | m_cStereoVar.USE_AUTO_PARAMS | m_cStereoVar.USE_INITIAL_DISPARITY | m_cStereoVar.USE_MEDIAN_FILTERING; + m_cStereoVar.penalization = m_cStereoVar.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS + m_cStereoVar.cycle = m_cStereoVar.CYCLE_V; // ignored with USE_AUTO_PARAMS + m_cStereoVar.flags = m_cStereoVar.USE_SMART_ID | m_cStereoVar.USE_AUTO_PARAMS | m_cStereoVar.USE_INITIAL_DISPARITY | + m_cStereoVar.USE_MEDIAN_FILTERING; } Bool DisparityStereoVar::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); m_cStereoVar.minDisp = -( ( ( apcFrameList[0]->getWidth() / 8 ) + 15 ) & -16 ); return true; } @@ -79,4 +81,3 @@ Void DisparityStereoVar::destroy() delete m_pcDisparityFrame; m_pcDisparityFrame = NULL; } - diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 0bd9bce..7e80bba 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,24 +31,20 @@ // PlaYUVerLib #include "PlaYUVerModuleIf.h" - -class DisparityStereoVar: public PlaYUVerModuleIf +class DisparityStereoVar : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( DisparityStereoVar ) + REGISTER_CLASS_FACTORY( DisparityStereoVar ) -private: + private: PlaYUVerFrame* m_pcDisparityFrame; cv::StereoVar m_cStereoVar; - public: - DisparityStereoVar(); - virtual ~DisparityStereoVar() - { - } + public: + DisparityStereoVar(); + virtual ~DisparityStereoVar() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); }; -#endif // __DISPARITYSTEREOVAR_H__ - +#endif // __DISPARITYSTEREOVAR_H__ diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index ce6d766..75cfa02 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "EightBitsSampling.h" - EightBitsSampling::EightBitsSampling() { /* Module Definition */ @@ -44,7 +43,8 @@ Bool EightBitsSampling::create( std::vector apcFrameList ) if( apcFrameList[0]->getBitsPel() > 8 ) { m_pcSubSampledFrame = NULL; - m_pcSubSampledFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getPelFormat(), 8 ); + m_pcSubSampledFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + apcFrameList[0]->getPelFormat(), 8 ); return true; } return false; @@ -79,4 +79,3 @@ Void EightBitsSampling::destroy() delete m_pcSubSampledFrame; m_pcSubSampledFrame = NULL; } - diff --git a/modules/EightBitsSampling.h b/modules/EightBitsSampling.h index 4402a1c..79cfc7b 100644 --- a/modules/EightBitsSampling.h +++ b/modules/EightBitsSampling.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,23 +28,19 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class EightBitsSampling: public PlaYUVerModuleIf +class EightBitsSampling : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( EightBitsSampling ) + REGISTER_CLASS_FACTORY( EightBitsSampling ) -private: + private: PlaYUVerFrame* m_pcSubSampledFrame; - public: + + public: EightBitsSampling(); - virtual ~EightBitsSampling() - { - } + virtual ~EightBitsSampling() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __EIGHTBITSSAMPLING_H__ - +#endif // __EIGHTBITSSAMPLING_H__ diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index c0378f5..c4480d5 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -42,7 +42,8 @@ PlaYUVerFrame* FilterComponentModule::filterComponent( PlaYUVerFrame* InputFrame { Pel*** pppOutputPelYUV = m_pcFilteredFrame->getPelBufferYUV(); Pel*** pppInputPelYUV = InputFrame->getPelBufferYUV(); - memcpy( pppOutputPelYUV[LUMA][0], pppInputPelYUV[Component][0], m_pcFilteredFrame->getWidth() * m_pcFilteredFrame->getHeight() * sizeof(Pel) ); + memcpy( pppOutputPelYUV[LUMA][0], pppInputPelYUV[Component][0], + m_pcFilteredFrame->getWidth() * m_pcFilteredFrame->getHeight() * sizeof( Pel ) ); return m_pcFilteredFrame; } @@ -62,9 +63,9 @@ FilterComponentLuma::FilterComponentLuma() m_pchModuleCategory = "FilterComponent"; // Category (sub-menu) m_pchModuleName = "Luma"; // Name m_pchModuleTooltip = "Filter Y matrix of YUV frame"; // Description - m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. } Bool FilterComponentLuma::create( std::vector apcFrameList ) @@ -93,7 +94,8 @@ Bool FilterComponentChromaU::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), + apcFrameList[0]->getBitsPel() ); } return false; } @@ -119,7 +121,8 @@ Bool FilterComponentChromaV::create( std::vector apcFrameList ) { if( apcFrameList[0]->getNumberChannels() > 1 ) { - return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getChromaWidth(), apcFrameList[0]->getChromaHeight(), + apcFrameList[0]->getBitsPel() ); } return false; } @@ -128,4 +131,3 @@ PlaYUVerFrame* FilterComponentChromaV::process( std::vector apcF { return filterComponent( apcFrameList[0], CHROMA_V ); } - diff --git a/modules/FilterComponent.h b/modules/FilterComponent.h index 4744763..c8e7d89 100644 --- a/modules/FilterComponent.h +++ b/modules/FilterComponent.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,16 +28,14 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FilterComponentModule: public PlaYUVerModuleIf +class FilterComponentModule : public PlaYUVerModuleIf { -private: + private: PlaYUVerFrame* m_pcFilteredFrame; - public: + + public: FilterComponentModule(); - virtual ~FilterComponentModule() - { - } + virtual ~FilterComponentModule() {} Bool create( std::vector apcFrameList ) = 0; PlaYUVerFrame* process( std::vector apcFrameList ) = 0; Void destroy(); @@ -46,41 +44,34 @@ private: PlaYUVerFrame* filterComponent( PlaYUVerFrame* InputFrame, Int Component ); }; -class FilterComponentLuma: public FilterComponentModule +class FilterComponentLuma : public FilterComponentModule { -REGISTER_CLASS_FACTORY( FilterComponentLuma ) - public: + REGISTER_CLASS_FACTORY( FilterComponentLuma ) + public: FilterComponentLuma(); - virtual ~FilterComponentLuma() - { - } + virtual ~FilterComponentLuma() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); }; -class FilterComponentChromaU: public FilterComponentModule +class FilterComponentChromaU : public FilterComponentModule { -REGISTER_CLASS_FACTORY( FilterComponentChromaU ) - public: + REGISTER_CLASS_FACTORY( FilterComponentChromaU ) + public: FilterComponentChromaU(); - virtual ~FilterComponentChromaU() - { - } + virtual ~FilterComponentChromaU() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); }; -class FilterComponentChromaV: public FilterComponentModule +class FilterComponentChromaV : public FilterComponentModule { -REGISTER_CLASS_FACTORY( FilterComponentChromaV ) - public: + REGISTER_CLASS_FACTORY( FilterComponentChromaV ) + public: FilterComponentChromaV(); - virtual ~FilterComponentChromaV() - { - } + virtual ~FilterComponentChromaV() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); }; -#endif // __FILTERFRAME_H__ - +#endif // __FILTERFRAME_H__ diff --git a/modules/FrameBinarization.cpp b/modules/FrameBinarization.cpp index fd7f7c5..2adf0cf 100644 --- a/modules/FrameBinarization.cpp +++ b/modules/FrameBinarization.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "FrameBinarization.h" - FrameBinarization::FrameBinarization() { /* Module Definition */ @@ -35,8 +34,8 @@ FrameBinarization::FrameBinarization() m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" ); + m_cModuleOptions.addOptions() /**/ + ( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" ); m_pcBinFrame = NULL; m_uiThreshold = 128; @@ -66,4 +65,3 @@ Void FrameBinarization::destroy() delete m_pcBinFrame; m_pcBinFrame = NULL; } - diff --git a/modules/FrameBinarization.h b/modules/FrameBinarization.h index 2b346c2..54c5502 100644 --- a/modules/FrameBinarization.h +++ b/modules/FrameBinarization.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,24 +28,20 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FrameBinarization: public PlaYUVerModuleIf +class FrameBinarization : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameBinarization ) + REGISTER_CLASS_FACTORY( FrameBinarization ) -private: + private: PlaYUVerFrame* m_pcBinFrame; UInt m_uiThreshold; - public: + + public: FrameBinarization(); - virtual ~FrameBinarization() - { - } + virtual ~FrameBinarization() {} Void create( PlaYUVerFrame* ); PlaYUVerFrame* process( PlaYUVerFrame* ); Void destroy(); - }; -#endif // __FRAMEBINARIZATION_H__ - +#endif // __FRAMEBINARIZATION_H__ diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index e758ef4..a67b35d 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "FrameCrop.h" - FrameCrop::FrameCrop() { /* Module Definition */ @@ -35,11 +34,11 @@ FrameCrop::FrameCrop() m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "xPosition", m_uiXPosition, "X cordinate of the left-top corner of the crop region [0]" )/**/ - ( "yPosition", m_uiYPosition, "Y cordinate of the left-top corner of the crop region [0]" )/**/ - ( "width", m_iXSize, "Width of the crop region [-1]" )/**/ - ( "height", m_iYSize, "Height of the crop region [-1]" ); + m_cModuleOptions.addOptions() /**/ + ( "xPosition", m_uiXPosition, "X cordinate of the left-top corner of the crop region [0]" ) /**/ + ( "yPosition", m_uiYPosition, "Y cordinate of the left-top corner of the crop region [0]" ) /**/ + ( "width", m_iXSize, "Width of the crop region [-1]" ) /**/ + ( "height", m_iYSize, "Height of the crop region [-1]" ); m_pcCropedFrame = NULL; m_uiXPosition = 0; @@ -74,4 +73,3 @@ Void FrameCrop::destroy() delete m_pcCropedFrame; m_pcCropedFrame = NULL; } - diff --git a/modules/FrameCrop.h b/modules/FrameCrop.h index f429bd2..07d1a22 100644 --- a/modules/FrameCrop.h +++ b/modules/FrameCrop.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,27 +28,23 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FrameCrop: public PlaYUVerModuleIf +class FrameCrop : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameCrop ) + REGISTER_CLASS_FACTORY( FrameCrop ) -private: + private: PlaYUVerFrame* m_pcCropedFrame; UInt m_uiXPosition; UInt m_uiYPosition; Int m_iXSize; Int m_iYSize; - public: + + public: FrameCrop(); - virtual ~FrameCrop() - { - } + virtual ~FrameCrop() {} Void create( PlaYUVerFrame* ); PlaYUVerFrame* process( PlaYUVerFrame* ); Void destroy(); - }; -#endif // __FRAMECROP_H__ - +#endif // __FRAMECROP_H__ diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index 0ef9712..eabcd08 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "FrameDifference.h" - FrameDifference::FrameDifference() { /* Module Definition */ @@ -36,8 +35,8 @@ FrameDifference::FrameDifference() m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_cModuleOptions.addOptions()/**/ - ( "Bits per pixel", m_uiBitsPixel, "Bits per pixel (use zero to avoid scaling) [0]" ); + m_cModuleOptions.addOptions() /**/ + ( "Bits per pixel", m_uiBitsPixel, "Bits per pixel (use zero to avoid scaling) [0]" ); m_uiBitsPixel = 0; @@ -51,7 +50,8 @@ Bool FrameDifference::create( std::vector apcFrameList ) UInt uiMaxBitsPixel = 0; for( UInt i = 0; i < apcFrameList.size(); i++ ) { - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], + PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION ) ) return false; if( apcFrameList[i]->getBitsPel() > uiMaxBitsPixel ) { @@ -67,7 +67,8 @@ Bool FrameDifference::create( std::vector apcFrameList ) m_iDiffBitShift = ( uiMaxBitsPixel + 1 ) - m_uiBitsPixel; m_iMaxDiffValue = ( 1 << ( m_uiBitsPixel - 1 ) ); - m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY, m_uiBitsPixel ); + m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY, m_uiBitsPixel ); return true; } @@ -101,4 +102,3 @@ Void FrameDifference::destroy() delete m_pcFrameDifference; m_pcFrameDifference = NULL; } - diff --git a/modules/FrameDifference.h b/modules/FrameDifference.h index 8a388b0..b70d417 100644 --- a/modules/FrameDifference.h +++ b/modules/FrameDifference.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,27 +28,22 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FrameDifference: public PlaYUVerModuleIf +class FrameDifference : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameDifference ) + REGISTER_CLASS_FACTORY( FrameDifference ) -private: + private: UInt m_uiBitsPixel; Int m_iDiffBitShift; Int m_iMaxDiffValue; PlaYUVerFrame* m_pcFrameDifference; -public: + public: FrameDifference(); - virtual ~FrameDifference() - { - } + virtual ~FrameDifference() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __FRAMEDIFFERENCE_H__ - +#endif // __FRAMEDIFFERENCE_H__ diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index 2a92fbd..144cefd 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "FrameMask.h" - FrameMask::FrameMask() { /* Module Definition */ @@ -36,8 +35,8 @@ FrameMask::FrameMask() m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS | MODULE_USES_KEYS; - m_cModuleOptions.addOptions()/**/ - ( "MaskWeigth", m_iWeight, "Influence of the mask [60%]" ); + m_cModuleOptions.addOptions() /**/ + ( "MaskWeigth", m_iWeight, "Influence of the mask [60%]" ); m_iWeight = 6; @@ -51,7 +50,8 @@ Bool FrameMask::create( std::vector apcFrameList ) for( UInt i = 1; i < apcFrameList.size(); i++ ) { if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE_IGNORE_GRAY | - PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) { return false; } @@ -68,18 +68,19 @@ Bool FrameMask::create( std::vector apcFrameList ) } switch( iColorSpace ) { - case PlaYUVerPixel::COLOR_GRAY: - iPelFmt = PlaYUVerFrame::GRAY; - break; - case PlaYUVerPixel::COLOR_YUV: - iPelFmt = PlaYUVerFrame::YUV444p; - break; - case PlaYUVerPixel::COLOR_RGB: - iPelFmt = PlaYUVerFrame::RGB24; - break; + case PlaYUVerPixel::COLOR_GRAY: + iPelFmt = PlaYUVerFrame::GRAY; + break; + case PlaYUVerPixel::COLOR_YUV: + iPelFmt = PlaYUVerFrame::YUV444p; + break; + case PlaYUVerPixel::COLOR_RGB: + iPelFmt = PlaYUVerFrame::RGB24; + break; } - m_pcFrameProcessed = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), iPelFmt, apcFrameList[0]->getBitsPel() ); + m_pcFrameProcessed = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), iPelFmt, + apcFrameList[0]->getBitsPel() ); return true; } @@ -128,4 +129,3 @@ Void FrameMask::destroy() } m_pcFrameProcessed = NULL; } - diff --git a/modules/FrameMask.h b/modules/FrameMask.h index baf2cdf..4eed0a5 100644 --- a/modules/FrameMask.h +++ b/modules/FrameMask.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,26 +28,21 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FrameMask: public PlaYUVerModuleIf +class FrameMask : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameMask ) + REGISTER_CLASS_FACTORY( FrameMask ) -private: + private: Int m_iWeight; PlaYUVerFrame* m_pcFrameProcessed; -public: + public: FrameMask(); - virtual ~FrameMask() - { - } + virtual ~FrameMask() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Bool keyPressed( enum Module_Key_Supported value ); Void destroy(); - }; -#endif // __FRAMEMASK_H__ - +#endif // __FRAMEMASK_H__ diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index 0c098f4..2fcd123 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,6 @@ #include "FrameShift.h" - FrameShift::FrameShift() { /* Module Definition */ @@ -36,9 +35,9 @@ FrameShift::FrameShift() m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS | MODULE_USES_KEYS; - m_cModuleOptions.addOptions()/**/ - ( "ShiftHorizontal", m_iShiftHor, "Amount of pixels to shift in horizontal direction" )/**/ - ( "ShiftVertical", m_iShiftVer, "Amount of pixels to shift in vertical direction" ); + m_cModuleOptions.addOptions() /**/ + ( "ShiftHorizontal", m_iShiftHor, "Amount of pixels to shift in horizontal direction" ) /**/ + ( "ShiftVertical", m_iShiftVer, "Amount of pixels to shift in vertical direction" ); m_pcProcessedFrame = NULL; m_iShiftHor = 0; @@ -84,11 +83,13 @@ PlaYUVerFrame* FrameShift::process( std::vector apcFrameList ) xStartOut = iShiftHorChroma >= 0 ? iShiftHorChroma : 0; xStartIn = iShiftHorChroma >= 0 ? 0 : -iShiftHorChroma; - xEndOut = iShiftHorChroma >= 0 ? m_pcProcessedFrame->getChromaWidth() : m_pcProcessedFrame->getChromaWidth() + iShiftHorChroma; + xEndOut = iShiftHorChroma >= 0 ? m_pcProcessedFrame->getChromaWidth() + : m_pcProcessedFrame->getChromaWidth() + iShiftHorChroma; yStartOut = iShiftVerChroma >= 0 ? iShiftVerChroma : 0; yStartIn = iShiftVerChroma >= 0 ? 0 : -iShiftVerChroma; - yEndOut = iShiftVerChroma >= 0 ? m_pcProcessedFrame->getChromaHeight() : m_pcProcessedFrame->getChromaHeight() + iShiftVerChroma; + yEndOut = iShiftVerChroma >= 0 ? m_pcProcessedFrame->getChromaHeight() + : m_pcProcessedFrame->getChromaHeight() + iShiftVerChroma; for( UInt c = 1; c < m_pcProcessedFrame->getNumberChannels(); c++ ) { @@ -139,4 +140,3 @@ Void FrameShift::destroy() delete m_pcProcessedFrame; m_pcProcessedFrame = NULL; } - diff --git a/modules/FrameShift.h b/modules/FrameShift.h index 78e86a2..43fc5a9 100644 --- a/modules/FrameShift.h +++ b/modules/FrameShift.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,26 +28,22 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class FrameShift: public PlaYUVerModuleIf +class FrameShift : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( FrameShift ) + REGISTER_CLASS_FACTORY( FrameShift ) -private: + private: PlaYUVerFrame* m_pcProcessedFrame; Int m_iShiftHor; Int m_iShiftVer; - public: + + public: FrameShift(); - virtual ~FrameShift() - { - } + virtual ~FrameShift() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Bool keyPressed( enum Module_Key_Supported value ); Void destroy(); - }; -#endif // __FrameShift_H__ - +#endif // __FrameShift_H__ diff --git a/modules/InterFrameVariance.cpp b/modules/InterFrameVariance.cpp index 2abb77c..fb492ba 100644 --- a/modules/InterFrameVariance.cpp +++ b/modules/InterFrameVariance.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,17 +28,17 @@ InterFrameVariance::InterFrameVariance() { /* Module Definition */ - m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. - m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "InterFrameVariance"; // Name + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "InterFrameVariance"; // Name m_pchModuleTooltip = "Measure the variance across several frames"; - m_uiNumberOfFrames = MODULE_REQUIRES_SEVERAL_FRAMES; // Number of Frames required (This module allows a variable number of inputs) - m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). + m_uiNumberOfFrames = + MODULE_REQUIRES_SEVERAL_FRAMES; // Number of Frames required (This module allows a variable number of inputs) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). // Several requirements should be "or" between each others. m_pcFrameVariance = NULL; - } Bool InterFrameVariance::create( std::vector apcFrameList ) @@ -48,10 +48,13 @@ Bool InterFrameVariance::create( std::vector apcFrameList ) _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) return false; - m_pcFrameVariance = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY, 8 ); + m_pcFrameVariance = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY, 8 ); getMem2D( &m_pVariance, apcFrameList[0]->getHeight(), apcFrameList[0]->getWidth() ); return true; @@ -82,19 +85,18 @@ PlaYUVerFrame* InterFrameVariance::process( std::vector apcFrame v = *pInput[i]++; sum += v; m_pVariance[y][x] += v * v; - } - //Final result of the variance for one block + // Final result of the variance for one block m_pVariance[y][x] -= Double( sum * sum ) / Double( numFrames ); - m_pVariance[y][x] /= Double( numFrames ); + m_pVariance[y][x] /= Double( numFrames ); if( m_pVariance[y][x] > maxVariance ) - maxVariance = m_pVariance[y][x]; + maxVariance = m_pVariance[y][x]; } for( UInt y = 0; y < m_pcFrameVariance->getHeight(); y++ ) for( UInt x = 0; x < m_pcFrameVariance->getWidth(); x++ ) { - *pOutputPelYUV++ = m_pVariance[y][x] * 255 / maxVariance; + *pOutputPelYUV++ = m_pVariance[y][x] * 255 / maxVariance; } return m_pcFrameVariance; } @@ -108,4 +110,3 @@ Void InterFrameVariance::destroy() delete m_pcFrameVariance; m_pcFrameVariance = NULL; } - diff --git a/modules/InterFrameVariance.h b/modules/InterFrameVariance.h index 2ae8fab..7f96df4 100644 --- a/modules/InterFrameVariance.h +++ b/modules/InterFrameVariance.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,24 +28,20 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class InterFrameVariance: public PlaYUVerModuleIf +class InterFrameVariance : public PlaYUVerModuleIf { REGISTER_CLASS_FACTORY( InterFrameVariance ) -private: + private: PlaYUVerFrame* m_pcFrameVariance; Double** m_pVariance; -public: + + public: InterFrameVariance(); - virtual ~InterFrameVariance() - { - } + virtual ~InterFrameVariance() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __INTERFRAMEVARIANCE_H__ - +#endif // __INTERFRAMEVARIANCE_H__ diff --git a/modules/LumaAverage.cpp b/modules/LumaAverage.cpp index 5e1d531..d21661c 100644 --- a/modules/LumaAverage.cpp +++ b/modules/LumaAverage.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -24,18 +24,17 @@ #include "LumaAverage.h" - LumaAverage::LumaAverage() { /* Module Definition */ - m_iModuleType = FRAME_MEASUREMENT_MODULE; // Apply module to the frames or to the whole sequence. - // Currently only support for frame - m_pchModuleCategory = "Measurements"; // Category (sub-menu) - m_pchModuleName = "LumaAverage"; // Name - m_pchModuleTooltip = "Measure the average of luma component"; // Description - m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_iModuleType = FRAME_MEASUREMENT_MODULE; // Apply module to the frames or to the whole sequence. + // Currently only support for frame + m_pchModuleCategory = "Measurements"; // Category (sub-menu) + m_pchModuleName = "LumaAverage"; // Name + m_pchModuleTooltip = "Measure the average of luma component"; // Description + m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. } Void LumaAverage::create( PlaYUVerFrame* frame ) @@ -57,6 +56,4 @@ Double LumaAverage::measure( PlaYUVerFrame* frame ) Void LumaAverage::destroy() { - } - diff --git a/modules/LumaAverage.h b/modules/LumaAverage.h index be46dd4..48e9404 100644 --- a/modules/LumaAverage.h +++ b/modules/LumaAverage.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,22 +28,17 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class LumaAverage: public PlaYUVerModuleIf +class LumaAverage : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( LumaAverage ) + REGISTER_CLASS_FACTORY( LumaAverage ) -private: -public: + private: + public: LumaAverage(); - virtual ~LumaAverage() - { - } + virtual ~LumaAverage() {} Void create( PlaYUVerFrame* ); Double measure( PlaYUVerFrame* ); Void destroy(); - }; -#endif // __LUMAAVERAGE_H__ - +#endif // __LUMAAVERAGE_H__ diff --git a/modules/MeasureOpticalFlowDualTVL1.cpp b/modules/MeasureOpticalFlowDualTVL1.cpp index a18b28a..562310a 100644 --- a/modules/MeasureOpticalFlowDualTVL1.cpp +++ b/modules/MeasureOpticalFlowDualTVL1.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -42,12 +42,11 @@ MeasureOpticalFlowDualTVL1::MeasureOpticalFlowDualTVL1() m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + m_cModuleOptions.addOptions() /**/ + ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); m_bShowReconstruction = false; m_pcOutputFrame = NULL; - } Bool MeasureOpticalFlowDualTVL1::create( std::vector apcFrameList ) @@ -55,7 +54,9 @@ Bool MeasureOpticalFlowDualTVL1::create( std::vector apcFrameLis _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) return false; m_iStep = 16; @@ -79,7 +80,6 @@ Void MeasureOpticalFlowDualTVL1::drawFlow() { for( int x = m_iStep / 2; x < m_cvFlow.cols; x += m_iStep ) { - Point2f u( 0, 0 ); Double count = 0; for( int i = ( -m_iStep / 2 ); i < ( m_iStep / 2 ); i++ ) @@ -116,7 +116,7 @@ Void MeasureOpticalFlowDualTVL1::compensateFlow() for( UInt x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) { Point2f u = m_cvFlow( y, x ); - Point p( x + u.x, y + u.y); + Point p( x + u.x, y + u.y ); *pPelOut = pPelPrev[p.y][p.x]; pPelOut++; } @@ -144,11 +144,9 @@ PlaYUVerFrame* MeasureOpticalFlowDualTVL1::process( std::vector return m_pcOutputFrame; } -Void -MeasureOpticalFlowDualTVL1::destroy() +Void MeasureOpticalFlowDualTVL1::destroy() { if( m_pcOutputFrame ) delete m_pcOutputFrame; m_pcOutputFrame = NULL; } - diff --git a/modules/MeasureOpticalFlowDualTVL1.h b/modules/MeasureOpticalFlowDualTVL1.h index 282f3ba..dbd72c9 100644 --- a/modules/MeasureOpticalFlowDualTVL1.h +++ b/modules/MeasureOpticalFlowDualTVL1.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,12 +31,11 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class MeasureOpticalFlowDualTVL1: public PlaYUVerModuleIf +class MeasureOpticalFlowDualTVL1 : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( MeasureOpticalFlowDualTVL1 ) + REGISTER_CLASS_FACTORY( MeasureOpticalFlowDualTVL1 ) -private: + private: Bool m_bShowReconstruction; Int m_iStep; cv::Ptr m_cTvl1; @@ -48,16 +47,12 @@ private: Void drawFlow(); Void compensateFlow(); -public: + public: MeasureOpticalFlowDualTVL1(); - virtual ~MeasureOpticalFlowDualTVL1() - { - } + virtual ~MeasureOpticalFlowDualTVL1() {} Bool create( std::vector apcFrameList ); PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); - }; -#endif // __MeasureOpticalFlowDualTVL1_H__ - +#endif // __MeasureOpticalFlowDualTVL1_H__ diff --git a/modules/OpticalFlow.cpp b/modules/OpticalFlow.cpp index 8d538d2..f89d068 100644 --- a/modules/OpticalFlow.cpp +++ b/modules/OpticalFlow.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -38,7 +38,6 @@ using cv::Ptr; using cv::Point; using cv::Point2f; - OpticalFlowModule::OpticalFlowModule() { /* Module Definition */ @@ -48,12 +47,11 @@ OpticalFlowModule::OpticalFlowModule() m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions()/**/ - ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + m_cModuleOptions.addOptions() /**/ + ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); m_bShowReconstruction = false; m_pcOutputFrame = NULL; - } Bool OpticalFlowModule::commonCreate( std::vector apcFrameList ) @@ -61,7 +59,9 @@ Bool OpticalFlowModule::commonCreate( std::vector apcFrameList ) _BASIC_MODULE_API_2_CHECK_ for( UInt i = 1; i < apcFrameList.size(); i++ ) - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | + PlaYUVerFrame::MATCH_RESOLUTION | + PlaYUVerFrame::MATCH_BITS ) ) return false; m_iStep = 16; @@ -84,7 +84,6 @@ Void OpticalFlowModule::drawFlow() { for( int x = m_iStep / 2; x < m_cvFlow.cols; x += m_iStep ) { - Point2f u( 0, 0 ); Double count = 0; for( int i = ( -m_iStep / 2 ); i < ( m_iStep / 2 ); i++ ) @@ -121,7 +120,7 @@ Void OpticalFlowModule::compensateFlow() for( UInt x = 0; x < m_pcOutputFrame->getWidth( c ); x++ ) { Point2f u = m_cvFlow( y, x ); - Point p( x + u.x, y + u.y); + Point p( x + u.x, y + u.y ); *pPelOut = pPelPrev[p.y][p.x]; pPelOut++; } @@ -154,9 +153,8 @@ Void OpticalFlowModule::destroy() if( m_pcOutputFrame ) delete m_pcOutputFrame; m_pcOutputFrame = NULL; -// if( m_cOpticalFlow ) -// delete m_cOpticalFlow; - + // if( m_cOpticalFlow ) + // delete m_cOpticalFlow; } OpticalFlowDualTVL1::OpticalFlowDualTVL1() @@ -164,7 +162,6 @@ OpticalFlowDualTVL1::OpticalFlowDualTVL1() /* Module Definition */ m_pchModuleName = "OpticalFlowDualTVL1"; m_pchModuleTooltip = "Measure optical flow using DualTVL1 method"; - } Bool OpticalFlowDualTVL1::create( std::vector apcFrameList ) @@ -181,7 +178,6 @@ OpticalFlowSparseToDense::OpticalFlowSparseToDense() /* Module Definition */ m_pchModuleName = "OpticalFlowSparseToDense"; m_pchModuleTooltip = "Measure optical flow using SparseToDense method"; - } Bool OpticalFlowSparseToDense::create( std::vector apcFrameList ) @@ -198,7 +194,6 @@ OpticalFlowFarneback::OpticalFlowFarneback() /* Module Definition */ m_pchModuleName = "OpticalFlowFarneback"; m_pchModuleTooltip = "Measure optical flow using Farneback method"; - } Bool OpticalFlowFarneback::create( std::vector apcFrameList ) @@ -215,7 +210,6 @@ OpticalDeepFlow::OpticalDeepFlow() /* Module Definition */ m_pchModuleName = "OpticalDeepFlow"; m_pchModuleTooltip = "Measure optical flow using Farneback method"; - } Bool OpticalDeepFlow::create( std::vector apcFrameList ) @@ -226,4 +220,3 @@ Bool OpticalDeepFlow::create( std::vector apcFrameList ) m_cOpticalFlow = cv::optflow::createOptFlow_DeepFlow(); return bRet; } - diff --git a/modules/OpticalFlow.h b/modules/OpticalFlow.h index affe3ff..441103d 100644 --- a/modules/OpticalFlow.h +++ b/modules/OpticalFlow.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -32,10 +32,9 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" - -class OpticalFlowModule: public PlaYUVerModuleIf +class OpticalFlowModule : public PlaYUVerModuleIf { -protected: + protected: Bool m_bShowReconstruction; Int m_iStep; cv::Ptr m_cOpticalFlow; @@ -46,61 +45,48 @@ protected: Void drawFlow(); Void compensateFlow(); Bool commonCreate( std::vector apcFrameList ); -public: + + public: OpticalFlowModule(); - virtual ~OpticalFlowModule() - { - } + virtual ~OpticalFlowModule() {} PlaYUVerFrame* process( std::vector apcFrameList ); Void destroy(); }; - -class OpticalFlowDualTVL1: public OpticalFlowModule +class OpticalFlowDualTVL1 : public OpticalFlowModule { REGISTER_CLASS_FACTORY( OpticalFlowDualTVL1 ) -public: + public: OpticalFlowDualTVL1(); - virtual ~OpticalFlowDualTVL1() - { - } + virtual ~OpticalFlowDualTVL1() {} Bool create( std::vector apcFrameList ); }; -class OpticalFlowSparseToDense: public OpticalFlowModule +class OpticalFlowSparseToDense : public OpticalFlowModule { REGISTER_CLASS_FACTORY( OpticalFlowSparseToDense ) -public: + public: OpticalFlowSparseToDense(); - virtual ~OpticalFlowSparseToDense() - { - } + virtual ~OpticalFlowSparseToDense() {} Bool create( std::vector apcFrameList ); }; - -class OpticalFlowFarneback: public OpticalFlowModule +class OpticalFlowFarneback : public OpticalFlowModule { REGISTER_CLASS_FACTORY( OpticalFlowFarneback ) -public: + public: OpticalFlowFarneback(); - virtual ~OpticalFlowFarneback() - { - } + virtual ~OpticalFlowFarneback() {} Bool create( std::vector apcFrameList ); }; -class OpticalDeepFlow: public OpticalFlowModule +class OpticalDeepFlow : public OpticalFlowModule { REGISTER_CLASS_FACTORY( OpticalDeepFlow ) -public: + public: OpticalDeepFlow(); - virtual ~OpticalDeepFlow() - { - } + virtual ~OpticalDeepFlow() {} Bool create( std::vector apcFrameList ); }; - -#endif // __OPTICALFLOW_H__ - +#endif // __OPTICALFLOW_H__ diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index 30ab8f3..b22f4e4 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,7 +34,6 @@ // Generated by cmake #include "ModulesListHeader.h" - PlaYUVerModuleFactory::PlaYUVerModuleFactory() { REGISTER_ALL_MODULES @@ -53,14 +52,13 @@ Void PlaYUVerModuleFactory::Register( const char* moduleName, CreateModuleFn pfn Bool PlaYUVerModuleFactory::RegisterDl( const char* dlName ) { #ifdef USE_DYNLOAD - void *pHndl = dlopen( dlName, RTLD_NOW ); + void* pHndl = dlopen( dlName, RTLD_NOW ); if( pHndl == NULL ) { - std::cerr << dlerror() - << std::endl; + std::cerr << dlerror() << std::endl; return false; } - CreateModuleFn pfnCreate = ( CreateModuleFn )dlsym( pHndl, "Maker" ); + CreateModuleFn pfnCreate = (CreateModuleFn)dlsym( pHndl, "Maker" ); if( pfnCreate == NULL ) { return false; @@ -72,7 +70,7 @@ Bool PlaYUVerModuleFactory::RegisterDl( const char* dlName ) #endif } -PlaYUVerModuleIf *PlaYUVerModuleFactory::CreateModule( const char* moduleName ) +PlaYUVerModuleIf* PlaYUVerModuleFactory::CreateModule( const char* moduleName ) { PlaYUVerModuleFactoryMap& PlaYUVerModuleFactoryMap = PlaYUVerModuleFactory::Get()->getMap(); PlaYUVerModuleFactoryMap::iterator it = PlaYUVerModuleFactoryMap.begin(); @@ -85,4 +83,3 @@ PlaYUVerModuleIf *PlaYUVerModuleFactory::CreateModule( const char* moduleName ) } return NULL; } - diff --git a/modules/PlaYUVerModuleFactory.h b/modules/PlaYUVerModuleFactory.h index daee368..8cf993a 100644 --- a/modules/PlaYUVerModuleFactory.h +++ b/modules/PlaYUVerModuleFactory.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -30,26 +30,23 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -#define REGISTER_MODULE(X) Register( "X", &(X::Create) ); +#define REGISTER_MODULE( X ) Register( "X", &( X::Create ) ); -typedef PlaYUVerModuleIf* (*CreateModuleFn)( void ); -typedef std::map PlaYUVerModuleFactoryMap; +typedef PlaYUVerModuleIf* ( *CreateModuleFn )( void ); +typedef std::map PlaYUVerModuleFactoryMap; // Factory for creating instances of PlaYUVerModuleIf class PlaYUVerModuleFactory { -private: + private: PlaYUVerModuleFactory(); - PlaYUVerModuleFactory &operator=( const PlaYUVerModuleFactory & ) - { - return *this; - } - + PlaYUVerModuleFactory& operator=( const PlaYUVerModuleFactory& ) { return *this; } PlaYUVerModuleFactoryMap m_FactoryMap; - public: + + public: ~PlaYUVerModuleFactory(); - static PlaYUVerModuleFactory *Get() + static PlaYUVerModuleFactory* Get() { static PlaYUVerModuleFactory instance; return &instance; @@ -58,12 +55,8 @@ private: Void Register( const char* moduleName, CreateModuleFn pfnCreate ); Bool RegisterDl( const char* dlName ); - PlaYUVerModuleIf *CreateModule( const char *moduleName ); - PlaYUVerModuleFactoryMap& getMap() - { - return m_FactoryMap; - } + PlaYUVerModuleIf* CreateModule( const char* moduleName ); + PlaYUVerModuleFactoryMap& getMap() { return m_FactoryMap; } }; -#endif // __PLAYUVERMODULESFACTORY_H__ - +#endif // __PLAYUVERMODULESFACTORY_H__ diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index 539bbb6..2189ea9 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -35,13 +35,13 @@ SetChromaHalfScale::SetChromaHalfScale() m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; m_pcProcessedFrame = NULL; - } Void SetChromaHalfScale::create( PlaYUVerFrame* frame ) { m_pcProcessedFrame = NULL; - m_pcProcessedFrame = new PlaYUVerFrame( frame->getWidth(), frame->getHeight(), frame->getPelFormat(), frame->getBitsPel() ); + m_pcProcessedFrame = + new PlaYUVerFrame( frame->getWidth(), frame->getHeight(), frame->getPelFormat(), frame->getBitsPel() ); } PlaYUVerFrame* SetChromaHalfScale::process( PlaYUVerFrame* frame ) @@ -67,4 +67,3 @@ Void SetChromaHalfScale::destroy() delete m_pcProcessedFrame; m_pcProcessedFrame = NULL; } - diff --git a/modules/SetChromaHalfScale.h b/modules/SetChromaHalfScale.h index 9c865c5..34ff622 100644 --- a/modules/SetChromaHalfScale.h +++ b/modules/SetChromaHalfScale.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,22 +28,19 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -class SetChromaHalfScale: public PlaYUVerModuleIf +class SetChromaHalfScale : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( SetChromaHalfScale ) + REGISTER_CLASS_FACTORY( SetChromaHalfScale ) -private: + private: PlaYUVerFrame* m_pcProcessedFrame; - public: + + public: SetChromaHalfScale(); - virtual ~SetChromaHalfScale() - { - } + virtual ~SetChromaHalfScale() {} Void create( PlaYUVerFrame* ); PlaYUVerFrame* process( PlaYUVerFrame* ); Void destroy(); - }; -#endif // _SETCHROMAHALFSCALE_H_ - +#endif // _SETCHROMAHALFSCALE_H_ diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index df8f3e9..70f1aa1 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -36,11 +36,10 @@ WeightedPSNR::WeightedPSNR() m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; m_uiNumberOfFrames = MODULE_REQUIRES_THREE_FRAMES; - m_cModuleOptions.addOptions()/**/ - ( "Component", m_uiComponent, "Select the component to compute quality [0]" ); + m_cModuleOptions.addOptions() /**/ + ( "Component", m_uiComponent, "Select the component to compute quality [0]" ); m_uiComponent = 0; - } Bool WeightedPSNR::create( std::vector apcFrameList ) @@ -113,6 +112,4 @@ Double WeightedPSNR::measure( std::vector apcFrameList ) Void WeightedPSNR::destroy() { - } - diff --git a/modules/WeightedPSNR.h b/modules/WeightedPSNR.h index c420e2b..dd8c149 100644 --- a/modules/WeightedPSNR.h +++ b/modules/WeightedPSNR.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -28,23 +28,19 @@ // PlaYUVerLib #include "lib/PlaYUVerModuleIf.h" -class WeightedPSNR: public PlaYUVerModuleIf +class WeightedPSNR : public PlaYUVerModuleIf { -REGISTER_CLASS_FACTORY( WeightedPSNR ) + REGISTER_CLASS_FACTORY( WeightedPSNR ) -private: + private: UInt m_uiComponent; -public: + public: WeightedPSNR(); - virtual ~WeightedPSNR() - { - } + virtual ~WeightedPSNR() {} Bool create( std::vector apcFrameList ); Double measure( std::vector apcFrameList ); Void destroy(); - }; -#endif // __WEIGHTEDPSNR_H__ - +#endif // __WEIGHTEDPSNR_H__ diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index c0e3e02..844c827 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -57,7 +57,7 @@ PlaYUVerTools::~PlaYUVerTools() } } -#define GET_PARAM( X , i ) X[X.size() > i ? i : X.size() - 1] +#define GET_PARAM( X, i ) X[X.size() > i ? i : X.size() - 1] Int PlaYUVerTools::openInputs() { @@ -90,7 +90,7 @@ Int PlaYUVerTools::openInputs() } if( Opts().hasOpt( "endianness" ) ) { - if( GET_PARAM( m_strEndianness, i )== "big" ) + if( GET_PARAM( m_strEndianness, i ) == "big" ) { uiEndianness = 0; } @@ -109,9 +109,10 @@ Int PlaYUVerTools::openInputs() } m_apcInputStreams.push_back( pcStream ); } - catch( const char *msg ) + catch( const char* msg ) { - log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", inputFileNames[i].c_str(), msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", inputFileNames[i].c_str(), + msg ); return 2; } } @@ -127,13 +128,14 @@ Int PlaYUVerTools::openInputs() for( UInt i = 0; i < m_apcInputStreams.size(); i++ ) { m_uiNumberOfFrames = std::min( m_uiNumberOfFrames, m_apcInputStreams[i]->getFrameNum() ); - m_uiNumberOfComponents = std::min( m_uiNumberOfComponents, m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() ); + m_uiNumberOfComponents = + std::min( m_uiNumberOfComponents, m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() ); } return 0; } -Int PlaYUVerTools::Open( Int argc, Char *argv[] ) +Int PlaYUVerTools::Open( Int argc, Char* argv[] ) { Int iRet = 0; @@ -283,11 +285,13 @@ Int PlaYUVerTools::Open( Int argc, Char *argv[] ) PlaYUVerStream* pcModStream = new PlaYUVerStream; try { - pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ); + pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), + pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ); } - catch( const char *msg ) + catch( const char* msg ) { - log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", outputFileNames[0].c_str(), msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", outputFileNames[0].c_str(), + msg ); delete pcModStream; pcModStream = NULL; return 2; @@ -321,7 +325,7 @@ Int PlaYUVerTools::Process() Int PlaYUVerTools::Close() { -// Finish + // Finish return 0; } @@ -342,7 +346,7 @@ Int PlaYUVerTools::SaveOperation() Int PlaYUVerTools::QualityOperation() { - const char *pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); + const char* pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); PlaYUVerFrame* apcCurrFrame[MAX_NUMBER_INPUTS]; Bool abEOF[MAX_NUMBER_INPUTS]; Double adAverageQuality[MAX_NUMBER_INPUTS - 1][PlaYUVerPixel::MAX_NUMBER_COMPONENTS]; @@ -351,20 +355,20 @@ Int PlaYUVerTools::QualityOperation() String metric_fmt = " "; switch( m_uiQualityMetric ) { - case PlaYUVerFrame::PSNR_METRIC: - //"PSNR_0_0" - metric_fmt += " %6.3f "; - break; - case PlaYUVerFrame::SSIM_METRIC: - //"SSIM_0_0" - metric_fmt += " %6.4f "; - break; - case PlaYUVerFrame::MSE_METRIC: - //"MSE_0_0" - metric_fmt += "%7.2f"; - break; - default: - metric_fmt += " %6.3f "; + case PlaYUVerFrame::PSNR_METRIC: + //"PSNR_0_0" + metric_fmt += " %6.3f "; + break; + case PlaYUVerFrame::SSIM_METRIC: + //"SSIM_0_0" + metric_fmt += " %6.4f "; + break; + case PlaYUVerFrame::MSE_METRIC: + //"MSE_0_0" + metric_fmt += "%7.2f"; + break; + default: + metric_fmt += " %6.3f "; } metric_fmt += " "; @@ -443,7 +447,8 @@ PlaYUVerFrame* PlaYUVerTools::applyFrameModule() Int PlaYUVerTools::ModuleOperation() { std::vector apcFrameList; - log( LOG_INFO, " Applying Module %s/%s ...\n", m_pcCurrModuleIf->m_pchModuleCategory, m_pcCurrModuleIf->m_pchModuleName ); + log( LOG_INFO, " Applying Module %s/%s ...\n", m_pcCurrModuleIf->m_pchModuleCategory, + m_pcCurrModuleIf->m_pchModuleName ); PlaYUVerFrame* pcProcessedFrame = NULL; Double dMeasurementResult = 0.0; @@ -486,7 +491,8 @@ Int PlaYUVerTools::ModuleOperation() } log( LOG_INFO, " %3d", frame ); log( LOG_RESULT, " %8.3f \n", dMeasurementResult ); - dAveragedMeasurementResult = ( dAveragedMeasurementResult * Double( frame ) + dMeasurementResult ) / Double( frame + 1 ); + dAveragedMeasurementResult = + ( dAveragedMeasurementResult * Double( frame ) + dMeasurementResult ) / Double( frame + 1 ); } for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) @@ -506,4 +512,3 @@ Int PlaYUVerTools::ModuleOperation() return 0; } - diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 3795098..0e39134 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -34,20 +34,19 @@ class PlaYUVerFrame; class PlaYUVerStream; class PlaYUVerModuleIf; - #define MAX_NUMBER_INPUTS 10 -class PlaYUVerTools: public PlaYUVerToolsCmdParser +class PlaYUVerTools : public PlaYUVerToolsCmdParser { -public: + public: PlaYUVerTools(); ~PlaYUVerTools(); - Int Open( Int argc, Char *argv[] ); + Int Open( Int argc, Char* argv[] ); Int Process(); Int Close(); -private: + private: Bool m_bVerbose; UInt m_uiOperation; @@ -66,7 +65,7 @@ private: Int openInputs(); - typedef Int (PlaYUVerTools::*FpProcess)(); + typedef Int ( PlaYUVerTools::*FpProcess )(); FpProcess m_fpProcess; Int64 m_iFrameNum; @@ -81,4 +80,4 @@ private: Int ModuleOperation(); }; -#endif // __PLAYUVERTOOLS_H__ +#endif // __PLAYUVERTOOLS_H__ diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 7c1a509..5e3d59f 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -32,7 +32,6 @@ #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" - PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() { m_uiLogLevel = 0; @@ -44,10 +43,9 @@ PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() PlaYUVerToolsCmdParser::~PlaYUVerToolsCmdParser() { - } -Void PlaYUVerToolsCmdParser::log( UInt level, const char *fmt, ... ) +Void PlaYUVerToolsCmdParser::log( UInt level, const char* fmt, ... ) { if( level >= m_uiLogLevel ) { @@ -58,22 +56,21 @@ Void PlaYUVerToolsCmdParser::log( UInt level, const char *fmt, ... ) } } -Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char *argv[] ) +Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char* argv[] ) { Int iRet = 0; - m_cOptions.addOptions()/**/ - ( "quiet,q", m_bQuiet, "disable verbose" ) - ( "input,i", m_apcInputs, "input file" ) /**/ - ( "output,o", m_strOutput, "output file" ) /**/ - ( "size,s", m_strResolution, "size (WxH)" ) /**/ - ( "pel_fmt,p", m_strPelFmt, "pixel format" ) /**/ - ( "bits_pel", m_uiBitsPerPixel, "bits per pixel" ) /**/ - ( "endianness", m_strEndianness, "File endianness (big, little)" ) /**/ - ( "frames,f", m_iFrames, "number of frames to parse" )/**/ - ( "quality", m_strQualityMetric, "select a quality metric" ) /**/ - ( "module", m_strModule, "select a module (use internal name)" ) /**/ - ( "save", "save a specific frame" ); + m_cOptions.addOptions() /**/ + ( "quiet,q", m_bQuiet, "disable verbose" )( "input,i", m_apcInputs, "input file" ) /**/ + ( "output,o", m_strOutput, "output file" ) /**/ + ( "size,s", m_strResolution, "size (WxH)" ) /**/ + ( "pel_fmt,p", m_strPelFmt, "pixel format" ) /**/ + ( "bits_pel", m_uiBitsPerPixel, "bits per pixel" ) /**/ + ( "endianness", m_strEndianness, "File endianness (big, little)" ) /**/ + ( "frames,f", m_iFrames, "number of frames to parse" ) /**/ + ( "quality", m_strQualityMetric, "select a quality metric" ) /**/ + ( "module", m_strModule, "select a module (use internal name)" ) /**/ + ( "save", "save a specific frame" ); if( !m_cOptions.parse( argc, argv ) ) { @@ -120,4 +117,3 @@ Void PlaYUVerToolsCmdParser::listModuleHelp() pcCurrModuleIf->m_cModuleOptions.doHelp( std::cout ); } } - diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 2b2cb77..9b48180 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * Joao Carreira (jfmcarreira@gmail.com) * * This program is free software; you can redistribute it and/or modify @@ -31,15 +31,11 @@ class PlaYUVerToolsCmdParser { -public: + public: PlaYUVerToolsCmdParser(); ~PlaYUVerToolsCmdParser(); - Void setLogLevel( enum LOG_LEVEL level ) - { - m_uiLogLevel = level; - } - + Void setLogLevel( enum LOG_LEVEL level ) { m_uiLogLevel = level; } /** * Send the specified message to the log if the level is higher than or equal * to the current LogLevel. By default, all logging messages are sent to @@ -52,16 +48,12 @@ public: * * @note this function might not be safe in C++ (try to upgrade it) */ - Void log( UInt level, const char *fmt, ... ); + Void log( UInt level, const char* fmt, ... ); - Int parseToolsArgs( Int argc, Char *argv[] ); + Int parseToolsArgs( Int argc, Char* argv[] ); - PlaYUVerOptions& Opts() - { - return m_cOptions; - } - -protected: + PlaYUVerOptions& Opts() { return m_cOptions; } + protected: PlaYUVerOptions m_cOptions; UInt m_uiLogLevel; @@ -89,7 +81,6 @@ protected: Void listModules(); Void listModuleHelp(); - }; -#endif // __PLAYUVERTOOLSCMDPARSER_H__ +#endif // __PLAYUVERTOOLSCMDPARSER_H__ diff --git a/tools/main.cpp b/tools/main.cpp index 97fbaf7..250f930 100644 --- a/tools/main.cpp +++ b/tools/main.cpp @@ -1,5 +1,5 @@ /* This file is a part of plaYUVer project - * Copyright (C) 2014-2016 by Luis Lucas (luisfrlucas@gmail.com) + * Copyright (C) 2014-2017 by Luis Lucas (luisfrlucas@gmail.com) * * Joao Carreira (jfmcarreira@gmail.com) * @@ -25,7 +25,7 @@ #include "PlaYUVerTools.h" -int main( int argc, Char *argv[] ) +int main( int argc, Char* argv[] ) { Int iRet = 0; PlaYUVerTools PlaYUVerToolsApp; @@ -52,5 +52,4 @@ int main( int argc, Char *argv[] ) printf( "Exiting with error \n" ); return 1; } - } From d96167856cba5e2b255da36f96872b9b2b334f40 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 2 Feb 2017 13:50:04 +0000 Subject: [PATCH 115/127] Version bump 0.13.0 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 37ca70e..1dd5758 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ set( PROJECT_NAME "playuver" CACHE INTERNAL "" FORCE ) PROJECT( ${PROJECT_NAME} ) SET( PLAYUVER_VERSION_MAJOR "0" ) -SET( PLAYUVER_VERSION_MINOR "11" ) +SET( PLAYUVER_VERSION_MINOR "13" ) SET( PLAYUVER_VERSION_PATCH "0" ) set( PLAYUVER_VERSION "${PLAYUVER_VERSION_MAJOR}.${PLAYUVER_VERSION_MINOR}.${PLAYUVER_VERSION_PATCH}" CACHE INTERNAL "" FORCE ) From 9c2e6fdbb85b8d7d144055dd02d5a1056dc568e8 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 17 Mar 2017 15:27:47 +0000 Subject: [PATCH 116/127] Add rate reduction operation to PlaYUVerTools --- tools/PlaYUVerTools.cpp | 74 ++++++++++++++++++++++++++++++++ tools/PlaYUVerTools.h | 3 ++ tools/PlaYUVerToolsCmdParser.cpp | 3 +- tools/PlaYUVerToolsCmdParser.h | 1 + 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index 844c827..d122cce 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -183,6 +183,59 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) log( LOG_INFO, "PlaYUVer Save Frame\n" ); } + if( Opts().hasOpt( "rate-reduction" ) ) + { + if( m_apcInputStreams.size() == 0 ) + { + log( LOG_ERROR, "Invalid number of input streams! " ); + return 2; + } + Int64 currFrames = 0; + Int64 numberOfFrames = LONG_MAX; + for( UInt i = 0; i < m_apcInputStreams.size(); i++ ) + { + currFrames = m_apcInputStreams[i]->getFrameNum(); + if( currFrames < numberOfFrames ) + numberOfFrames = currFrames; + } + if( m_iRateReductionFactor <= 0 ) + { + log( LOG_ERROR, "Invalid frame rate reduction value!" ); + return 2; + } + + if( Opts().hasOpt( "output" ) ) + m_pcOutputFileNames.push_back( m_strOutput ); + + PlaYUVerFrame* pcInputFrame = m_apcInputStreams[0]->getCurrFrame(); + PlaYUVerStream* pcOutputStream = new PlaYUVerStream; + try + { + pcOutputStream->open( m_pcOutputFileNames[0], pcInputFrame->getWidth(), pcInputFrame->getHeight(), + pcInputFrame->getPelFormat(), pcInputFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, + false ); + } + catch( const char* msg ) + { + log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", m_pcOutputFileNames[0].c_str(), + msg ); + delete pcOutputStream; + pcOutputStream = NULL; + return 2; + } + m_apcOutputStreams.push_back( pcOutputStream ); + + if( m_apcOutputStreams.size() != m_apcInputStreams.size() ) + { + log( LOG_ERROR, "Invalid number of outputs! Each input must have an output filename. " ); + return 2; + } + + m_uiOperation = RATE_REDUCTION_OPERATION; + m_fpProcess = &PlaYUVerTools::RateReductionOperation; + log( LOG_INFO, "PlaYUVer Frame Rate Reduction\n" ); + } + /** * Check Quality operation */ @@ -344,6 +397,27 @@ Int PlaYUVerTools::SaveOperation() return 0; } +Int PlaYUVerTools::RateReductionOperation() +{ + Bool abEOF; + log( LOG_INFO, "\n Reducing frame rate by a factor of %d ... ", m_iRateReductionFactor ); + for( UInt frame = 0; frame < m_uiNumberOfFrames; frame++ ) + { + log( LOG_INFO, "\n Reading frame %d ... ", frame ); + if( ( frame % m_iRateReductionFactor ) == 0 ) + { + log( LOG_INFO, "Writing", frame ); + m_apcOutputStreams[0]->writeFrame( m_apcInputStreams[0]->getCurrFrame() ); + } + abEOF = m_apcInputStreams[0]->setNextFrame(); + if( !abEOF ) + { + m_apcInputStreams[0]->readFrame(); + } + } + return 0; +} + Int PlaYUVerTools::QualityOperation() { const char* pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); diff --git a/tools/PlaYUVerTools.h b/tools/PlaYUVerTools.h index 0e39134..8bdb859 100644 --- a/tools/PlaYUVerTools.h +++ b/tools/PlaYUVerTools.h @@ -54,6 +54,7 @@ class PlaYUVerTools : public PlaYUVerToolsCmdParser { INVALID_OPERATION, SAVE_OPERATION, + RATE_REDUCTION_OPERATION, QUALITY_OPERATION, MODULE_OPERATION, }; @@ -72,6 +73,8 @@ class PlaYUVerTools : public PlaYUVerToolsCmdParser std::vector m_pcOutputFileNames; Int SaveOperation(); + Int RateReductionOperation(); + Int m_uiQualityMetric; Int QualityOperation(); diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index 5e3d59f..a893787 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -70,7 +70,8 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char* argv[] ) ( "frames,f", m_iFrames, "number of frames to parse" ) /**/ ( "quality", m_strQualityMetric, "select a quality metric" ) /**/ ( "module", m_strModule, "select a module (use internal name)" ) /**/ - ( "save", "save a specific frame" ); + ( "save", "save a specific frame" ) /**/ + ( "rate-reduction", m_iRateReductionFactor, "reduce the frame rate" ); /**/ if( !m_cOptions.parse( argc, argv ) ) { diff --git a/tools/PlaYUVerToolsCmdParser.h b/tools/PlaYUVerToolsCmdParser.h index 9b48180..1b60e16 100644 --- a/tools/PlaYUVerToolsCmdParser.h +++ b/tools/PlaYUVerToolsCmdParser.h @@ -72,6 +72,7 @@ class PlaYUVerToolsCmdParser String m_strOutput; Int64 m_iFrames; + Int m_iRateReductionFactor; String m_strQualityMetric; String m_strModule; From 3d1a771d01f093afee1c34a2dd3561c1cfe99780 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 17 Mar 2017 18:51:30 +0000 Subject: [PATCH 117/127] Update README.md --- README.md | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1164aa6..052e890 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,13 @@ plaYUVer is an open-source video player with the following features: - Constant growing libs for stream and frame processing (PlaYUVerStream PlaYUVerFrame) - Advanced API for frame/video processing algorithms - Frame level quality measurement API based on the PlaYUVerFrame class -- Command-line tool for quality and frame processing algorithms (uses the referred APIs) +- Powefull command-line tool for quality and frame processing algorithms (uses the referred APIs) + +Libs and API +---------------------------------------------------------------- +- PlaYUVerFrame and PlaYUVerStream: Stream and frame handling lib +- PlaYUVerModules: Interface for processing modules (extensions) + Supported Quality Metrics ---------------------------------------------------------------- @@ -27,8 +33,24 @@ Frame Processing Modules - Component filtering - Frame difference, crop, shift, binarization - Sub-sampling operations -- Disparity Computation -- Measuring modules +- Measuring modules +- Modules based on opencv: + * Disparity estimation + * Motion estimation + +Supported Formats +---------------------------------------------------------------- +- Supports for the following pixel formats: + * YUV: 420, 44, 422, 400 + * RGB + * Gray +- Support containers: + * Raw video (yuv,rgb,gray) + * Portable Network Graphics (png) + * Joint Photographic Experts Group (jpeg) + * Windows Bitmap (bmp) + * Tagged Image File Format (tiff) + * Portable Map (ppm,pgm,pbm) Developers ---------------------------------------------------------------- From ca9e78377c59ac890adcab049f6389b9285bc029 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Fri, 17 Mar 2017 18:53:16 +0000 Subject: [PATCH 118/127] Continue update on README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 052e890..b2ce418 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -PlaYUVer - Enhanced raw video player +PlaYUVer - Enhanced Raw Video Player ======== From 18bdd342a5a671e53cacfab341de7cf7d38edaba Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 02:23:32 +0000 Subject: [PATCH 119/127] Increase line size --- .clang-format | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-format b/.clang-format index d8f4194..ad1ad87 100644 --- a/.clang-format +++ b/.clang-format @@ -2,7 +2,7 @@ Language: Cpp # BasedOnStyle: Chromium ColumnLimit: 80 -ColumnLimit: 120 +ColumnLimit: 140 AccessModifierOffset: -1 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false From ebd9fa46fe6c2ab3358cf4e2cb1c3f4b7b8e5175 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 02:23:48 +0000 Subject: [PATCH 120/127] Changes in the libav handle --- lib/StreamHandlerLibav.cpp | 124 +++++++++++++++---------------------- lib/StreamHandlerLibav.h | 4 +- 2 files changed, 53 insertions(+), 75 deletions(-) diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index aa373b3..1da4b03 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -35,12 +35,12 @@ std::vector StreamHandlerLibav::supportedReadFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Tagged Image File Format", "tiff" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -50,49 +50,13 @@ std::vector StreamHandlerLibav::supportedWriteFormats() END_REGIST_PLAYUVER_SUPPORTED_FMT; } -static int open_codec_context( int* stream_idx, AVFormatContext* m_cFmtCtx, enum AVMediaType type ) -{ - int ret; - AVStream* st; - AVCodecContext* dec_ctx = NULL; - AVCodec* dec = NULL; - - ret = av_find_best_stream( m_cFmtCtx, type, -1, -1, NULL, 0 ); - if( ret < 0 ) - { - return ret; - } - else - { - *stream_idx = ret; - st = m_cFmtCtx->streams[*stream_idx]; - - /* find decoder for the stream */ - dec_ctx = st->codec; - dec = avcodec_find_decoder( dec_ctx->codec_id ); - if( !dec ) - { - printf( "Failed to find %s codec\n", av_get_media_type_string( type ) ); - return ret; - } - - if( ( ret = avcodec_open2( dec_ctx, dec, NULL ) ) < 0 ) - { - printf( "Failed to open %s codec\n", av_get_media_type_string( type ) ); - return ret; - } - } - - return 0; -} - Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) { const char* filename = strFilename.c_str(); m_cFmtCtx = NULL; - m_cCodecCtx = NULL; m_cStream = NULL; + // video_dst_data[0] = NULL; // video_dst_data[1] = NULL; // video_dst_data[2] = NULL; @@ -133,28 +97,42 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) return false; } - if( open_codec_context( &m_iStreamIdx, m_cFmtCtx, AVMEDIA_TYPE_VIDEO ) >= 0 ) + AVMediaType mediaType; + + int stream_idx = av_find_best_stream( m_cFmtCtx, mediaType, -1, -1, NULL, 0 ); + if( stream_idx < 0 ) { - m_cStream = m_cFmtCtx->streams[m_iStreamIdx]; - m_cCodecCtx = m_cStream->codec; - - // /* allocate image where the decoded image will be put */ - // ret = av_image_alloc( video_dst_data, video_dst_linesize, m_cCodecCtx->width, m_cCodecCtx->height, - // m_cCodecCtx->pix_fmt, 1 ); - // if( ret < 0 ) - // { - // //qDebug( ) << " Could not allocate raw video buffer !!!" << endl; - // closeAvFormat(); - // return false; - // } - // video_dst_bufsize = ret; - - m_uiFrameBufferSize = av_image_get_buffer_size( m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); - getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); + return false; } + m_iStreamIdx = stream_idx; + + m_cStream = m_cFmtCtx->streams[m_iStreamIdx]; + + /* find decoder for the stream */ + AVCodecParameters* codec_param = m_cStream->codecpar; + + // dec = avcodec_find_decoder( dec_ctx->codec_id ); + AVCodec* dec = avcodec_find_decoder( codec_param->codec_id ); + if( !dec ) + { + printf( "Failed to find %s codec\n", av_get_media_type_string( mediaType ) ); + return false; + } + + m_cCodedCtx = avcodec_alloc_context3( dec ); + + if( avcodec_open2( m_cCodedCtx, dec, NULL ) < 0 ) + { + printf( "Failed to open %s codec\n", av_get_media_type_string( mediaType ) ); + return false; + } + + m_uiFrameBufferSize = av_image_get_buffer_size( AVPixelFormat( codec_param->format ), codec_param->width, codec_param->height, 1 ); + getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); + m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); - const char* name = avcodec_get_name( m_cCodecCtx->codec_id ); + const char* name = avcodec_get_name( m_cStream->codecpar->codec_id ); // sprintf( m_acCodecName, "%s", name ); m_strCodecName = name; @@ -167,12 +145,12 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) #endif else if( m_cStream->time_base.den && m_cStream->time_base.num ) fr = 1 / av_q2d( m_cStream->time_base ); - else if( m_cStream->codec->time_base.den && m_cStream->codec->time_base.num ) - fr = 1 / av_q2d( m_cStream->codec->time_base ); + else if( m_cCodedCtx->time_base.den && m_cCodedCtx->time_base.num ) + fr = 1 / av_q2d( m_cCodedCtx->time_base ); m_dFrameRate = fr; - Int pix_fmt = m_cCodecCtx->pix_fmt; + Int pix_fmt = m_cStream->codecpar->format; // Set bits per pixel to default (8 bits) m_uiBitsPerPixel = 8; @@ -202,8 +180,8 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) pix_fmt = AV_PIX_FMT_GRAY8; } - m_uiWidth = m_cCodecCtx->width; - m_uiHeight = m_cCodecCtx->height; + m_uiWidth = m_cStream->codecpar->width; + m_uiHeight = m_cStream->codecpar->height; m_iPixelFormat = PlaYUVerFrame::NO_FMT; for( Int i = 0; i < PlaYUVerFrame::NUMBER_PEL_FORMATS; i++ ) @@ -254,8 +232,8 @@ Void StreamHandlerLibav::closeHandler() { if( m_bHasStream ) { - if( m_cCodecCtx ) - avcodec_close( m_cCodecCtx ); + if( m_cCodedCtx ) + avcodec_close( m_cCodedCtx ); if( m_cFmtCtx ) avformat_close_input( &m_cFmtCtx ); @@ -302,7 +280,7 @@ Bool StreamHandlerLibav::decodeVideoPkt() Int decResult; if( pkt.stream_index == m_iStreamIdx ) { - decResult = avcodec_decode_video2( m_cCodecCtx, m_cFrame, &got_frame, &pkt ); + decResult = avcodec_decode_video2( m_cCodedCtx, m_cFrame, &got_frame, &pkt ); if( decResult < 0 ) { fprintf( stderr, "Error decoding video frame\n" ); @@ -350,11 +328,9 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) if( bGotFrame ) { - // av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, - // m_cCodecCtx->pix_fmt, m_cCodecCtx->width, - // m_cCodecCtx->height, 1 ); - av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, - m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); + AVCodecParameters* codec_param = m_cStream->codecpar; + av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, AVPixelFormat( codec_param->format ), + codec_param->width, codec_param->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 6e1934d..b94965e 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -78,9 +78,11 @@ class StreamHandlerLibav : public PlaYUVerStreamHandlerIf private: AVFormatContext* m_cFmtCtx; - AVCodecContext* m_cCodecCtx; AVStream* m_cStream; Int m_iStreamIdx; + + AVCodecContext* m_cCodedCtx; + AVFrame* m_cFrame; AVPacket pkt; From a7119c2dc7d1ab71b55b7a0cd33f70b17e571378 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 02:43:39 +0000 Subject: [PATCH 121/127] Fix warnings --- lib/PlaYUVerFrame.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 3d828d9..2c1d7f9 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1316,7 +1316,7 @@ Double PlaYUVerFrame::getMSE( PlaYUVerFrame* Org, Int component ) Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) { - UInt uiMaxValue = ( 1 << Org->getBitsPel() - 1 ); + UInt uiMaxValue = ( 1 << Org->getBitsPel() ) - 1; Double uiMaxValueSquare = uiMaxValue * uiMaxValue; Double dPSNR = 100; Double dMSE = getMSE( Org, component ); From 9f431316cca699c6b1e88c45e66f60d0dfa6cc13 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 02:43:52 +0000 Subject: [PATCH 122/127] Fix bugfix in libav handle --- lib/StreamHandlerLibav.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index 1da4b03..2b4b0b7 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -97,9 +97,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) return false; } - AVMediaType mediaType; - - int stream_idx = av_find_best_stream( m_cFmtCtx, mediaType, -1, -1, NULL, 0 ); + int stream_idx = av_find_best_stream( m_cFmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0 ); if( stream_idx < 0 ) { return false; @@ -116,7 +114,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) AVCodec* dec = avcodec_find_decoder( codec_param->codec_id ); if( !dec ) { - printf( "Failed to find %s codec\n", av_get_media_type_string( mediaType ) ); + printf( "Failed to find %s codec\n", av_get_media_type_string( AVMEDIA_TYPE_VIDEO ) ); return false; } @@ -124,7 +122,7 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) if( avcodec_open2( m_cCodedCtx, dec, NULL ) < 0 ) { - printf( "Failed to open %s codec\n", av_get_media_type_string( mediaType ) ); + printf( "Failed to open %s codec\n", av_get_media_type_string( AVMEDIA_TYPE_VIDEO ) ); return false; } From 2ec2afc33311b18042a62a615a35ebaff21b6269 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 02:43:39 +0000 Subject: [PATCH 123/127] Fix warnings --- lib/PlaYUVerFrame.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 3d828d9..2c1d7f9 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -1316,7 +1316,7 @@ Double PlaYUVerFrame::getMSE( PlaYUVerFrame* Org, Int component ) Double PlaYUVerFrame::getPSNR( PlaYUVerFrame* Org, Int component ) { - UInt uiMaxValue = ( 1 << Org->getBitsPel() - 1 ); + UInt uiMaxValue = ( 1 << Org->getBitsPel() ) - 1; Double uiMaxValueSquare = uiMaxValue * uiMaxValue; Double dPSNR = 100; Double dMSE = getMSE( Org, component ); From ebc10d1b84fd067f2d2c4ee80a54362d62c792dc Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 04:29:34 +0000 Subject: [PATCH 124/127] Re-format code --- .clang-format | 7 +- app/AboutDialog.cpp | 18 +- app/AboutDialog.h | 3 +- app/ConfigureFormatDialog.cpp | 50 +- app/DialogSubWindowSelector.cpp | 16 +- app/DialogSubWindowSelector.h | 2 +- app/FramePropertiesDock.cpp | 32 +- app/FramePropertiesDock.h | 8 +- app/GridManager.cpp | 8 +- app/GridManager.h | 4 +- app/HistogramWidget.cpp | 32 +- app/HistogramWidget.h | 6 +- app/ModuleHandleDock.cpp | 4 +- app/ModuleHandleDock.h | 4 +- app/ModulesHandle.cpp | 122 +- app/ModulesHandle.h | 4 +- app/ModulesHandleOptDialog.cpp | 17 +- app/ModulesHandleOptDialog.h | 2 +- app/PlaYUVerApp.cpp | 94 +- app/PlaYUVerApp.h | 4 +- app/PlaYUVerAppAdaptor.cpp | 5 +- app/PlaYUVerAppAdaptor.h | 5 +- app/PlaYUVerAppModuleIf.cpp | 22 +- app/PlaYUVerAppModuleIf.h | 14 +- app/PlaYUVerMdiSubWindow.cpp | 2 +- app/PlaYUVerMdiSubWindow.h | 2 +- app/PlaYUVerSubWindowHandle.cpp | 82 +- app/PlaYUVerSubWindowHandle.h | 2 +- app/PlotSubWindow.cpp | 29 +- app/PlotSubWindow.h | 6 +- app/ProgressBar.cpp | 6 +- app/ProgressBar.h | 2 +- app/QualityHandle.cpp | 46 +- app/QualityHandle.h | 2 +- app/QualityMeasurementSidebar.cpp | 16 +- app/QualityMeasurementSidebar.h | 8 +- app/SeekStreamDialog.cpp | 9 +- app/SeekStreamDialog.h | 2 +- app/SubWindowAbstract.cpp | 13 +- app/SubWindowAbstract.h | 12 +- app/VideoHandle.cpp | 97 +- app/VideoHandle.h | 6 +- app/VideoSubWindow.cpp | 96 +- app/VideoSubWindow.h | 14 +- app/ViewArea.cpp | 76 +- app/ViewArea.h | 13 +- app/WidgetFrameNumber.h | 2 +- app/external/qcustomplot.cpp | 10029 +++++++++++++++-------- app/external/qcustomplot.h | 627 +- app/main.cpp | 25 +- lib/PlaYUVerDefs.h | 15 +- lib/PlaYUVerFrame.cpp | 89 +- lib/PlaYUVerFramePixelFormats.cpp | 222 +- lib/PlaYUVerFramePixelFormats.h | 5 +- lib/PlaYUVerOptions.cpp | 46 +- lib/PlaYUVerOptions.h | 8 +- lib/PlaYUVerPixel.cpp | 6 +- lib/PlaYUVerPixel.h | 22 +- lib/PlaYUVerStream.cpp | 33 +- lib/StreamHandlerLibav.cpp | 48 +- lib/StreamHandlerLibav.h | 4 +- lib/StreamHandlerOpenCV.cpp | 11 +- lib/StreamHandlerPortableMap.cpp | 9 +- modules/AbsoluteFrameDifference.cpp | 21 +- modules/DisparityStereoBM.cpp | 14 +- modules/DisparityStereoBM.h | 3 +- modules/DisparityStereoSGBM.cpp | 21 +- modules/DisparityStereoSGBM.h | 24 +- modules/DisparityStereoVar.cpp | 15 +- modules/DisparityStereoVar.h | 3 +- modules/EightBitsSampling.cpp | 5 +- modules/FilterComponent.cpp | 16 +- modules/FrameCrop.cpp | 13 +- modules/FrameDifference.cpp | 13 +- modules/FrameMask.cpp | 10 +- modules/FrameShift.cpp | 6 +- modules/InterFrameVariance.cpp | 15 +- modules/LumaAverage.cpp | 13 +- modules/MeasureOpticalFlowDualTVL1.cpp | 9 +- modules/OpticalFlow.cpp | 9 +- modules/PlaYUVerModuleFactory.cpp | 4 +- modules/SetChromaHalfScale.cpp | 4 +- modules/WeightedPSNR.cpp | 3 +- tools/PlaYUVerTools.cpp | 56 +- tools/PlaYUVerToolsCmdParser.cpp | 9 +- 85 files changed, 8092 insertions(+), 4419 deletions(-) diff --git a/.clang-format b/.clang-format index d8f4194..f775df4 100644 --- a/.clang-format +++ b/.clang-format @@ -1,8 +1,7 @@ --- Language: Cpp # BasedOnStyle: Chromium -ColumnLimit: 80 -ColumnLimit: 120 +ColumnLimit: 100 AccessModifierOffset: -1 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false @@ -37,8 +36,10 @@ BraceWrapping: BreakBeforeBinaryOperators: None #BreakBeforeBraces: Attach BreakBeforeBraces: Allman +#BreakBeforeInheritanceComma: true BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializersBeforeComma: true +BreakConstructorInitializersBeforeComma: true BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true CommentPragmas: '^ IWYU pragma:' diff --git a/app/AboutDialog.cpp b/app/AboutDialog.cpp index db81251..475f14d 100644 --- a/app/AboutDialog.cpp +++ b/app/AboutDialog.cpp @@ -20,7 +20,8 @@ /** * \file AboutDialog.cpp * \brief About Dialog - * Based on the work of Glad Deschrijver in KTikZ project + * Based on the work of Glad Deschrijver + * in KTikZ project */ #include @@ -36,14 +37,16 @@ AboutDialog::AboutDialog( QWidget* parent ) : QDialog( parent ) { - QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ).scaled( QSize( 500, 350 ), Qt::KeepAspectRatio ); + QPixmap logo = QPixmap( ":/images/playuver-backgroud-logo.png" ) + .scaled( QSize( 500, 350 ), Qt::KeepAspectRatio ); QLabel* pixmapLabel = new QLabel; pixmapLabel->setPixmap( logo ); - QLabel* label = new QLabel( QString( "

%1 Version %2

%3

" ) - .arg( QApplication::applicationName() ) - .arg( QApplication::applicationVersion() ) - .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) ); + QLabel* label = + new QLabel( QString( "

%1 Version %2

%3

" ) + .arg( QApplication::applicationName() ) + .arg( QApplication::applicationVersion() ) + .arg( tr( "Enhanced open-source Qt-based raw video player" ) ) ); label->setWordWrap( true ); QString featuresList = QStringLiteral( "

Features:

    " ); @@ -61,7 +64,8 @@ AboutDialog::AboutDialog( QWidget* parent ) : QDialog( parent ) QLabel* labelFeatures = new QLabel( featuresList ); - QLabel* labelCopyright = new QLabel( QStringLiteral( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ); + QLabel* labelCopyright = + new QLabel( QStringLiteral( "Copyright © 2014–2015 Luis Lucas and Joao Carreira" ) ); QWidget* topWidget = new QWidget; QVBoxLayout* topLayout = new QVBoxLayout; diff --git a/app/AboutDialog.h b/app/AboutDialog.h index 317ea3c..9d316ed 100644 --- a/app/AboutDialog.h +++ b/app/AboutDialog.h @@ -20,7 +20,8 @@ /** * \file AboutDialog.h * \brief About Dialog - * Based on the work of Glad Deschrijver in KTikZ project + * Based on the work of Glad Deschrijver + * in KTikZ project */ #ifndef __ABOUTDIALOG_H__ diff --git a/app/ConfigureFormatDialog.cpp b/app/ConfigureFormatDialog.cpp index 52831a3..9a9f836 100644 --- a/app/ConfigureFormatDialog.cpp +++ b/app/ConfigureFormatDialog.cpp @@ -23,6 +23,7 @@ */ #include +#include #include #include #include @@ -33,7 +34,6 @@ #include #include #include -#include #include "lib/PlaYUVerFrame.h" @@ -147,17 +147,20 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren Name = QString::fromStdString( aRCustomFileFormats[i].shortName ); uiWidth = aRCustomFileFormats[i].uiWidth; uiHeight = aRCustomFileFormats[i].uiHeight; - standardResolutionNames.append( QString( "%1 (%2x%3)" ).arg( Name ).arg( uiWidth ).arg( uiHeight ) ); + standardResolutionNames.append( + QString( "%1 (%2x%3)" ).arg( Name ).arg( uiWidth ).arg( uiHeight ) ); standardResolutionSizes.append( QSize( uiWidth, uiHeight ) ); } - std::vector listPlaYUVerStdResolution = PlaYUVerStream::stdResolutionSizes(); + std::vector listPlaYUVerStdResolution = + PlaYUVerStream::stdResolutionSizes(); for( UInt i = 0; i < listPlaYUVerStdResolution.size(); i++ ) { Name = QString::fromStdString( listPlaYUVerStdResolution[i].shortName ); uiWidth = listPlaYUVerStdResolution[i].uiWidth; uiHeight = listPlaYUVerStdResolution[i].uiHeight; - standardResolutionNames.append( QString( "%1 (%2x%3)" ).arg( Name ).arg( uiWidth ).arg( uiHeight ) ); + standardResolutionNames.append( + QString( "%1 (%2x%3)" ).arg( Name ).arg( uiWidth ).arg( uiHeight ) ); standardResolutionSizes.append( QSize( uiWidth, uiHeight ) ); } @@ -189,7 +192,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren // dialogTitleLabel->setFont( titleFont ); // dialogTitleLabel->setText( "Configure Resolution" ); // headLayout->addWidget( dialogTitleLabel ); - // headLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + // headLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, + // QSizePolicy::Minimum ) ); // // MainLayout->addLayout( headLayout ); // MainLayout->addItem( new QSpacerItem( 10, 20, QSizePolicy::Minimum ) ); @@ -204,7 +208,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren m_labelFilename = new QLabel(); m_labelFilename->setFont( titleFont ); filenameLayout->addWidget( filenameLabel ); - filenameLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + filenameLayout->addItem( + new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); filenameLayout->addWidget( m_labelFilename ); MainLayout->addLayout( filenameLayout ); @@ -282,16 +287,19 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren for( UInt i = 0; i < PlaYUVerFrame::supportedColorSpacesListNames().size(); i++ ) { - m_comboBoxColorSpace->insertItem( i, PlaYUVerFrame::supportedColorSpacesListNames()[i].c_str() ); + m_comboBoxColorSpace->insertItem( i, + PlaYUVerFrame::supportedColorSpacesListNames()[i].c_str() ); } m_comboBoxColorSpace->setCurrentIndex( 1 ); pixelGridLayout->addWidget( colorSpaceLabel, 0, 0 ); - pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 0, 1 ); + pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), + 0, 1 ); pixelGridLayout->addWidget( m_comboBoxColorSpace, 0, 2 ); pixelGridLayout->addWidget( pixelFormatLabel, 1, 0 ); - pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 1, 1 ); + pixelGridLayout->addItem( new QSpacerItem( 10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), + 1, 1 ); pixelGridLayout->addWidget( m_comboBoxPixelFormat, 1, 2 ); QLabel* bitsPerPelLabel = new QLabel(); @@ -303,7 +311,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren m_spinBoxBits->setRange( 0, 16 ); m_spinBoxBits->setValue( 8 ); pixelGridLayout->addWidget( bitsPerPelLabel, 2, 0 ); - pixelGridLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), 2, 1 ); + pixelGridLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ), + 2, 1 ); pixelGridLayout->addWidget( m_spinBoxBits, 2, 2 ); /* @@ -320,7 +329,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren m_comboBoxEndianness->addItem( QStringLiteral( "Big Endian" ) ); m_comboBoxEndianness->addItem( QStringLiteral( "Little Endian" ) ); endiannessLayout->addWidget( endiannessLabel ); - endiannessLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + endiannessLayout->addItem( + new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); endiannessLayout->addWidget( m_comboBoxEndianness ); m_widgetEndianness = new QWidget(); m_widgetEndianness->setContentsMargins( 0, 0, 0, 0 ); @@ -340,7 +350,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren m_spinBoxFrameRate->setRange( 0, 200 ); m_spinBoxFrameRate->setValue( 30 ); framerateFormatLayout->addWidget( framerateFormatLabel ); - framerateFormatLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + framerateFormatLayout->addItem( + new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); framerateFormatLayout->addWidget( m_spinBoxFrameRate ); QWidget* framerateWidget = new QWidget(); framerateWidget->setContentsMargins( 0, 0, 0, 0 ); @@ -368,7 +379,8 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( paren SLOT( slotStandardResolutionSelected( int ) ) ); connect( m_spinBoxWidth, SIGNAL( valueChanged( int ) ), this, SLOT( slotResolutionChange() ) ); connect( m_spinBoxheight, SIGNAL( valueChanged( int ) ), this, SLOT( slotResolutionChange() ) ); - connect( m_comboBoxColorSpace, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotColorSpaceChange( int ) ) ); + connect( m_comboBoxColorSpace, SIGNAL( currentIndexChanged( int ) ), this, + SLOT( slotColorSpaceChange( int ) ) ); connect( m_spinBoxBits, SIGNAL( valueChanged( int ) ), this, SLOT( slotBitsChange( int ) ) ); connect( dialogButtonOkCancel, SIGNAL( accepted() ), this, SLOT( accept() ) ); @@ -471,9 +483,11 @@ void ConfigureFormatDialog::slotStandardResolutionSelected( Int idx ) if( customResolution.shortName != "" ) { QString name = QString::fromStdString( customResolution.shortName ); - name.append( QString( " (%2x%3)" ).arg( customResolution.uiWidth ).arg( customResolution.uiHeight ) ); + name.append( + QString( " (%2x%3)" ).arg( customResolution.uiWidth ).arg( customResolution.uiHeight ) ); standardResolutionNames.insert( 0, name ); - standardResolutionSizes.insert( 0, QSize( customResolution.uiWidth, customResolution.uiHeight ) ); + standardResolutionSizes.insert( + 0, QSize( customResolution.uiWidth, customResolution.uiHeight ) ); m_comboBoxStandardResolution->blockSignals( true ); m_comboBoxStandardResolution->insertItem( 0, name ); @@ -499,7 +513,8 @@ void ConfigureFormatDialog::slotResolutionChange() Int newIdx = -1; for( Int i = 0; i < standardResolutionSizes.size(); i++ ) { - if( standardResolutionSizes.at( i ) == QSize( m_spinBoxWidth->value(), m_spinBoxheight->value() ) ) + if( standardResolutionSizes.at( i ) == + QSize( m_spinBoxWidth->value(), m_spinBoxheight->value() ) ) { newIdx = i; break; @@ -517,7 +532,8 @@ Void ConfigureFormatDialog::slotColorSpaceChange( Int idx ) m_comboBoxPixelFormat->clear(); for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames( idx ).size(); i++ ) { - m_comboBoxPixelFormat->insertItem( i, PlaYUVerFrame::supportedPixelFormatListNames( idx )[i].c_str() ); + m_comboBoxPixelFormat->insertItem( + i, PlaYUVerFrame::supportedPixelFormatListNames( idx )[i].c_str() ); } m_comboBoxPixelFormat->setCurrentIndex( 0 ); } diff --git a/app/DialogSubWindowSelector.cpp b/app/DialogSubWindowSelector.cpp index 9c51ac3..062aa75 100644 --- a/app/DialogSubWindowSelector.cpp +++ b/app/DialogSubWindowSelector.cpp @@ -22,22 +22,22 @@ * \brief Dialog box to select sub windows */ +#include "DialogSubWindowSelector.h" +#include "PlaYUVerSubWindowHandle.h" +#include "VideoSubWindow.h" #include #include -#include "PlaYUVerSubWindowHandle.h" -#include "DialogSubWindowSelector.h" -#include "VideoSubWindow.h" DialogSubWindowSelector::DialogSubWindowSelector( QWidget* parent, PlaYUVerSubWindowHandle* windowManager, UInt uiCategory, Int minWindowsSelected, Int maxWindowsSelected ) - : QDialog( parent ), - m_uiCategory( uiCategory ), - m_iMinSelectedWindows( minWindowsSelected ), - m_iMaxSlectedWindows( maxWindowsSelected ), - m_pcMainWindowManager( windowManager ) + : QDialog( parent ) + , m_uiCategory( uiCategory ) + , m_iMinSelectedWindows( minWindowsSelected ) + , m_iMaxSlectedWindows( maxWindowsSelected ) + , m_pcMainWindowManager( windowManager ) { QSize windowSize( 350, 80 ); resize( windowSize ); diff --git a/app/DialogSubWindowSelector.h b/app/DialogSubWindowSelector.h index 36df182..3182942 100644 --- a/app/DialogSubWindowSelector.h +++ b/app/DialogSubWindowSelector.h @@ -25,8 +25,8 @@ #ifndef __DIALOGSUBWINDOWSELECTOR_H__ #define __DIALOGSUBWINDOWSELECTOR_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #if( QT_VERSION_PLAYUVER == 5 ) #include #elif( QT_VERSION_PLAYUVER == 4 ) diff --git a/app/FramePropertiesDock.cpp b/app/FramePropertiesDock.cpp index 17f281e..315e0ea 100644 --- a/app/FramePropertiesDock.cpp +++ b/app/FramePropertiesDock.cpp @@ -22,10 +22,10 @@ * \brief Main side bar definition */ -#include -#include -#include #include "FramePropertiesDock.h" +#include +#include +#include FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitch ) : QWidget( parent ), m_pbIsPlaying( pbMainPlaySwitch ) @@ -240,12 +240,17 @@ FramePropertiesDock::FramePropertiesDock( QWidget* parent, Bool* pbMainPlaySwitc setEnabled( false ); connect( channelCB, SIGNAL( activated( int ) ), this, SLOT( slotChannelChanged( int ) ) ); - connect( scaleButtonGroup, SIGNAL( buttonClicked( int ) ), this, SLOT( slotScaleChanged( int ) ) ); + connect( scaleButtonGroup, SIGNAL( buttonClicked( int ) ), this, + SLOT( slotScaleChanged( int ) ) ); connect( colorsCB, SIGNAL( activated( int ) ), this, SLOT( slotColorsChanged( int ) ) ); - connect( renderingButtonGroup, SIGNAL( buttonClicked( int ) ), this, SLOT( slotRenderingChanged( int ) ) ); - connect( histogramWidget, SIGNAL( signalIntervalChanged( int, int ) ), this, SLOT( slotUpdateInterval( int, int ) ) ); - connect( histogramWidget, SIGNAL( signalMaximumValueChanged( int ) ), this, SLOT( slotUpdateIntervRange( int ) ) ); - connect( histogramWidget, SIGNAL( signalHistogramComputationDone( int ) ), this, SLOT( slotRefreshOptions( int ) ) ); + connect( renderingButtonGroup, SIGNAL( buttonClicked( int ) ), this, + SLOT( slotRenderingChanged( int ) ) ); + connect( histogramWidget, SIGNAL( signalIntervalChanged( int, int ) ), this, + SLOT( slotUpdateInterval( int, int ) ) ); + connect( histogramWidget, SIGNAL( signalMaximumValueChanged( int ) ), this, + SLOT( slotUpdateIntervRange( int ) ) ); + connect( histogramWidget, SIGNAL( signalHistogramComputationDone( int ) ), this, + SLOT( slotRefreshOptions( int ) ) ); connect( histogramWidget, SIGNAL( signalHistogramComputationFailed( void ) ), this, SLOT( slotHistogramComputationFailed( void ) ) ); connect( minInterv, SIGNAL( valueChanged( int ) ), this, SLOT( slotMinValueChanged( int ) ) ); @@ -343,7 +348,8 @@ Void FramePropertiesDock::setFrame( PlaYUVerFrame* pcFrame ) colorsCB->setEnabled( false ); colorsCB->setWhatsThis( tr( "

    Select here the main color displayed with Colors Channel mode:" - "

    Luminance: DraupdateDataw the Luminance channel in the foreground.

    " + "

    Luminance: DraupdateDataw the Luminance channel in the " + "foreground.

    " "Chroma U: Draw the Chroma U channel in the foreground.

    " "Chroma V: Draw the Chroma V channel in the foreground.

    " ) ); colorsCB->show(); @@ -386,8 +392,8 @@ Void FramePropertiesDock::setSelection( const QRect& selectionArea ) { delete m_pcSelectedFrame; } - m_pcSelectedFrame = new PlaYUVerFrame( m_pcFrame, selectionArea.x(), selectionArea.y(), selectionArea.width(), - selectionArea.height() ); + m_pcSelectedFrame = new PlaYUVerFrame( m_pcFrame, selectionArea.x(), selectionArea.y(), + selectionArea.width(), selectionArea.height() ); } updateDataHistogram(); selectionImageButton->click(); @@ -454,8 +460,8 @@ Void FramePropertiesDock::updateStatistiques() if( frame ) { - QString rangeText = - "[" + QString::number( frame->getMin( channel ) ) + ":" + QString::number( frame->getMax( channel ) ) + "]"; + QString rangeText = "[" + QString::number( frame->getMin( channel ) ) + ":" + + QString::number( frame->getMax( channel ) ) + "]"; labelRangeValue->setText( rangeText ); double mean = frame->getMean( channel, min, max ); diff --git a/app/FramePropertiesDock.h b/app/FramePropertiesDock.h index fe777bc..1f69deb 100644 --- a/app/FramePropertiesDock.h +++ b/app/FramePropertiesDock.h @@ -25,17 +25,17 @@ #ifndef __FRAMEPROPERTIESDOCK_H__ #define __FRAMEPROPERTIESDOCK_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #if( QT_VERSION_PLAYUVER == 5 ) #include #elif( QT_VERSION_PLAYUVER == 4 ) -#include #include +#include #endif -#include "lib/PlaYUVerStream.h" -#include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" +#include "lib/PlaYUVerFrame.h" +#include "lib/PlaYUVerStream.h" class FramePropertiesDock : public QWidget { diff --git a/app/GridManager.cpp b/app/GridManager.cpp index 68c4ffa..d78e5f6 100644 --- a/app/GridManager.cpp +++ b/app/GridManager.cpp @@ -24,13 +24,13 @@ */ #include +#include +#include #include +#include +#include #include #include -#include -#include -#include -#include #include "GridManager.h" diff --git a/app/GridManager.h b/app/GridManager.h index f68a439..578aab3 100644 --- a/app/GridManager.h +++ b/app/GridManager.h @@ -26,11 +26,11 @@ #ifndef __GRIDMANAGER_H__ #define __GRIDMANAGER_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" -#include +#include "config.h" #include #include +#include class QPoint; class QBitmap; diff --git a/app/HistogramWidget.cpp b/app/HistogramWidget.cpp index c36abf2..6b404d5 100644 --- a/app/HistogramWidget.cpp +++ b/app/HistogramWidget.cpp @@ -25,11 +25,11 @@ // TODO: // - Optimizar paintEvent. Parece haver codigo redundante !! -#include "config.h" -#include -#include -#include #include "HistogramWidget.h" +#include "config.h" +#include +#include +#include class HistogramWorker : public QThread { @@ -177,7 +177,8 @@ HistogramWidget::HistogramWidget( Int width, Int height, QWidget* parent ) : QWi m_colorType = FirstChannelColor; m_renderingType = FullImageHistogram; - setOptions( HistogramWidget::BlinkComputation | HistogramWidget::SelectMode | HistogramWidget::ShowLumaChannel ); + setOptions( HistogramWidget::BlinkComputation | HistogramWidget::SelectMode | + HistogramWidget::ShowLumaChannel ); setMouseTracking( true ); setMinimumSize( width, height ); @@ -439,7 +440,8 @@ Void HistogramWidget::paintEvent( QPaintEvent* ) QPainter p1( this ); p1.fillRect( 0, 0, maxX, maxY, palette().color( QPalette::Disabled, QPalette::Window ) ); - p1.setPen( QPen( palette().color( QPalette::Disabled, QPalette::WindowText ), 1, Qt::SolidLine ) ); + p1.setPen( + QPen( palette().color( QPalette::Disabled, QPalette::WindowText ), 1, Qt::SolidLine ) ); p1.drawRect( 0, 0, maxX, maxY ); return; @@ -461,7 +463,8 @@ Void HistogramWidget::paintEvent( QPaintEvent* ) if( d->clearFlag == HistogramWidgetPrivate::HistogramDataLoading ) p1.drawText( 0, 0, maxX, maxY, Qt::AlignCenter, tr( "Loading image..." ) ); else - p1.drawText( 0, 0, maxX, maxY, Qt::AlignCenter, tr( "Histogram\ncalculation\nin progress..." ) ); + p1.drawText( 0, 0, maxX, maxY, Qt::AlignCenter, + tr( "Histogram\ncalculation\nin progress..." ) ); return; } @@ -526,7 +529,8 @@ Void HistogramWidget::paintEvent( QPaintEvent* ) break; case HistogramWidget::ColorChannelsHistogram: // All color channels. - max = qMax( qMax( frame->getMaximum( LUMA ), frame->getMaximum( CHROMA_U ) ), frame->getMaximum( CHROMA_V ) ); + max = qMax( qMax( frame->getMaximum( LUMA ), frame->getMaximum( CHROMA_U ) ), + frame->getMaximum( CHROMA_V ) ); break; // case HistogramWidget::LumaHistogram: // Luminance. // max = frame->getMaximum( LUMA ); @@ -893,7 +897,8 @@ Void HistogramWidget::paintEvent( QPaintEvent* ) break; // case HistogramWidget::LumaHistogram: - // guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() ), d->colorGuide.blue() ); + // guidePos = qMax( qMax( d->colorGuide.red(), d->colorGuide.green() + // ), d->colorGuide.blue() ); // break; default: // Alpha. @@ -1025,7 +1030,8 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent* e ) if( d->inSelected ) { double max = ( (double)e->pos().x() ) / ( (double)width() ); - // int max = (int)(e->pos().x()*((float)m_imageHistogram->getHistogramSegment()/(float)width())); + // int max = + // (int)(e->pos().x()*((float)m_imageHistogram->getHistogramSegment()/(float)width())); if( max < d->xminOrg ) { @@ -1040,7 +1046,8 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent* e ) } notifyValuesChanged(); - // emit signalMaxValueChanged( d->xmax == 0.0 ? d->range : (int)(d->xmax * d->range) ); + // emit signalMaxValueChanged( d->xmax == 0.0 ? d->range : (int)(d->xmax * + // d->range) ); update(); } @@ -1051,7 +1058,8 @@ Void HistogramWidget::mouseMoveEvent( QMouseEvent* e ) Void HistogramWidget::notifyValuesChanged() { - emit signalIntervalChanged( (int)( d->xmin * d->range ), d->xmax == 0.0 ? d->range : (int)( d->xmax * d->range ) ); + emit signalIntervalChanged( (int)( d->xmin * d->range ), + d->xmax == 0.0 ? d->range : (int)( d->xmax * d->range ) ); } Void HistogramWidget::slotMinValueChanged( int min ) diff --git a/app/HistogramWidget.h b/app/HistogramWidget.h index 23104a5..53ff76d 100644 --- a/app/HistogramWidget.h +++ b/app/HistogramWidget.h @@ -26,11 +26,11 @@ #ifndef __HISTOGRAMWIDGET_H__ #define __HISTOGRAMWIDGET_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" -#include -#include +#include "config.h" #include "lib/PlaYUVerFrame.h" +#include +#include class QEvent; diff --git a/app/ModuleHandleDock.cpp b/app/ModuleHandleDock.cpp index ca2cc6a..f96cda1 100644 --- a/app/ModuleHandleDock.cpp +++ b/app/ModuleHandleDock.cpp @@ -22,10 +22,10 @@ * \brief Module handle dock */ -#include #include "ModuleHandleDock.h" -#include "PlaYUVerAppModuleIf.h" #include "ModulesHandle.h" +#include "PlaYUVerAppModuleIf.h" +#include ModuleHandleDock::ModuleHandleDock( QWidget* parent, PlaYUVerAppModuleIf* moduleIf ) : QWidget( parent ), m_pcCurrModuleIf( moduleIf ) diff --git a/app/ModuleHandleDock.h b/app/ModuleHandleDock.h index f86a7a0..4ae5819 100644 --- a/app/ModuleHandleDock.h +++ b/app/ModuleHandleDock.h @@ -25,13 +25,13 @@ #ifndef __MODULEHANDLEDOCK_H__ #define __MODULEHANDLEDOCK_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #if( QT_VERSION_PLAYUVER == 5 ) #include #elif( QT_VERSION_PLAYUVER == 4 ) -#include #include +#include #endif class PlaYUVerAppModuleIf; diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index f430c9f..6aa9773 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -22,18 +22,23 @@ * \brief PlaYUVer modules handle */ -#include -#include "PlaYUVerApp.h" #include "ModulesHandle.h" -#include "PlaYUVerSubWindowHandle.h" -#include "VideoSubWindow.h" -#include "VideoHandle.h" #include "DialogSubWindowSelector.h" #include "ModulesHandleOptDialog.h" +#include "PlaYUVerApp.h" +#include "PlaYUVerSubWindowHandle.h" +#include "VideoHandle.h" +#include "VideoSubWindow.h" #include "modules/PlaYUVerModuleFactory.h" +#include -ModulesHandle::ModulesHandle( QWidget* parent, PlaYUVerSubWindowHandle* windowManager, VideoHandle* moduleVideo ) - : QWidget( parent ), m_pcParent( parent ), m_pcMainWindowManager( windowManager ), m_appModuleVideo( moduleVideo ) +ModulesHandle::ModulesHandle( QWidget* parent, + PlaYUVerSubWindowHandle* windowManager, + VideoHandle* moduleVideo ) + : QWidget( parent ) + , m_pcParent( parent ) + , m_pcMainWindowManager( windowManager ) + , m_appModuleVideo( moduleVideo ) { setParent( m_pcParent ); } @@ -49,13 +54,16 @@ Void ModulesHandle::createActions() m_pcActionMapper = new QSignalMapper( this ); connect( m_pcActionMapper, SIGNAL( mapped( int ) ), this, SLOT( processOpt( int ) ) ); - // m_arrayActions[FORCE_PLAYING_REFRESH_ACT] = new QAction( "Refresh while playing", parent() ); - // m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setStatusTip( "Force module refreshing while playing" ); + // m_arrayActions[FORCE_PLAYING_REFRESH_ACT] = new QAction( "Refresh while + // playing", parent() ); + // m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setStatusTip( "Force module + // refreshing while playing" ); // m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setCheckable( true ); m_arrayActions[LOAD_EXTERNAL_ACT] = new QAction( "Load external module", parent() ); m_arrayActions[LOAD_EXTERNAL_ACT]->setStatusTip( "Load an externally build module" ); - connect( m_arrayActions[LOAD_EXTERNAL_ACT], SIGNAL( triggered() ), this, SLOT( loadExternalModule() ) ); + connect( m_arrayActions[LOAD_EXTERNAL_ACT], SIGNAL( triggered() ), this, + SLOT( loadExternalModule() ) ); m_arrayActions[APPLY_ALL_ACT] = new QAction( "Apply to All", parent() ); m_arrayActions[APPLY_ALL_ACT]->setStatusTip( "Apply module to all frames and save the result" ); @@ -64,18 +72,22 @@ Void ModulesHandle::createActions() m_arrayActions[SWAP_FRAMES_ACT] = new QAction( "Swap frames", parent() ); m_arrayActions[SWAP_FRAMES_ACT]->setStatusTip( "Swap Sub Window order" ); - connect( m_arrayActions[SWAP_FRAMES_ACT], SIGNAL( triggered() ), m_pcActionMapper, SLOT( map() ) ); + connect( m_arrayActions[SWAP_FRAMES_ACT], SIGNAL( triggered() ), m_pcActionMapper, + SLOT( map() ) ); m_pcActionMapper->setMapping( m_arrayActions[SWAP_FRAMES_ACT], SWAP_FRAMES_ACT ); m_arrayActions[DISABLE_ACT] = new QAction( "Disable Modules", parent() ); - connect( m_arrayActions[DISABLE_ACT], SIGNAL( triggered() ), this, SLOT( destroyWindowModules() ) ); + connect( m_arrayActions[DISABLE_ACT], SIGNAL( triggered() ), this, + SLOT( destroyWindowModules() ) ); m_arrayActions[DISABLE_ALL_ACT] = new QAction( "Disable All Modules", parent() ); - connect( m_arrayActions[DISABLE_ALL_ACT], SIGNAL( triggered() ), this, SLOT( destroyAllModulesIf() ) ); + connect( m_arrayActions[DISABLE_ALL_ACT], SIGNAL( triggered() ), this, + SLOT( destroyAllModulesIf() ) ); m_arrayActions[FORCE_NEW_WINDOW_ACT] = new QAction( "Use New Window", parent() ); m_arrayActions[FORCE_NEW_WINDOW_ACT]->setStatusTip( - "Show module result in a new window. Some modules already force this feature" ); + "Show module result in a new window. Some modules already force this " + "feature" ); m_arrayActions[FORCE_NEW_WINDOW_ACT]->setCheckable( true ); } @@ -113,7 +125,8 @@ Void ModulesHandle::buildMenu() { for( Int j = 0; j < m_pcModulesSubMenuList.size(); j++ ) { - if( m_pcModulesSubMenuList.at( j )->title() == QString( pcCurrModuleIf->m_pchModuleCategory ) ) + if( m_pcModulesSubMenuList.at( j )->title() == + QString( pcCurrModuleIf->m_pchModuleCategory ) ) { currSubMenu = m_pcModulesSubMenuList.at( j ); break; @@ -152,7 +165,8 @@ Void ModulesHandle::buildMenu() Void ModulesHandle::updateMenus() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcSubWindow ? true : false; QAction* currModuleAction; @@ -195,18 +209,21 @@ Void ModulesHandle::updateMenus() Void ModulesHandle::readSettings() { QSettings appSettings; - m_arrayActions[FORCE_NEW_WINDOW_ACT]->setChecked( appSettings.value( "ModulesHandle/UseNewWindow", false ).toBool() ); + m_arrayActions[FORCE_NEW_WINDOW_ACT]->setChecked( + appSettings.value( "ModulesHandle/UseNewWindow", false ).toBool() ); } Void ModulesHandle::writeSettings() { QSettings appSettings; - appSettings.setValue( "ModulesHandle/UseNewWindow", m_arrayActions[FORCE_NEW_WINDOW_ACT]->isChecked() ); + appSettings.setValue( "ModulesHandle/UseNewWindow", + m_arrayActions[FORCE_NEW_WINDOW_ACT]->isChecked() ); } Void ModulesHandle::processOpt( Int index ) { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { PlaYUVerAppModuleIf* pcCurrentModule = pcSubWindow->getDisplayModule(); @@ -239,8 +256,8 @@ Void ModulesHandle::loadExternalModule() formatsList << "Shared Libraries (*.so)"; QStringList filter; filter << supported << formatsList << tr( "All Files (*)" ); - QStringList fileNames = - QFileDialog::getOpenFileNames( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) ); + QStringList fileNames = QFileDialog::getOpenFileNames( m_pcParent, tr( "Open File" ), QString(), + filter.join( ";;" ) ); for( Int i = 0; i < fileNames.size(); i++ ) { @@ -256,13 +273,15 @@ Void ModulesHandle::activateModule() Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers(); Bool bTmpForceNewWindow = false; - VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcVideoSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( !pcVideoSubWindow ) { return; } - if( ( keyModifiers & Qt::ControlModifier ) || pcVideoSubWindow->checkCategory( VideoSubWindow::MODULE_SUBWINDOW ) ) + if( ( keyModifiers & Qt::ControlModifier ) || + pcVideoSubWindow->checkCategory( VideoSubWindow::MODULE_SUBWINDOW ) ) { bTmpForceNewWindow = true; } @@ -270,7 +289,8 @@ Void ModulesHandle::activateModule() QString ModuleIfName = pcAction->data().toString(); PlaYUVerModuleIf* pcCurrModuleIf = PlaYUVerModuleFactory::Get()->CreateModule( ModuleIfName.toLocal8Bit().constData() ); - PlaYUVerAppModuleIf* pcCurrAppModuleIf = new PlaYUVerAppModuleIf( this, pcAction, pcCurrModuleIf ); + PlaYUVerAppModuleIf* pcCurrAppModuleIf = + new PlaYUVerAppModuleIf( this, pcAction, pcCurrModuleIf ); QList videoSubWindowList; Int numberOfFrames = pcCurrAppModuleIf->m_pcModule->m_uiNumberOfFrames; @@ -284,8 +304,10 @@ Void ModulesHandle::activateModule() maxNumFrames = 255; } DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, - SubWindowAbstract::VIDEO_SUBWINDOW, minNumFrames, maxNumFrames ); - QList windowsList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + SubWindowAbstract::VIDEO_SUBWINDOW, + minNumFrames, maxNumFrames ); + QList windowsList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); if( windowsList.size() == minNumFrames && windowsList.size() == maxNumFrames ) { @@ -323,10 +345,12 @@ Void ModulesHandle::activateModule() // Check for same fmt in more than one frame modules for( Int i = 1; i < videoSubWindowList.size(); i++ ) { - if( !videoSubWindowList.at( i )->getCurrFrame()->haveSameFmt( videoSubWindowList.at( 0 )->getCurrFrame() ) ) + if( !videoSubWindowList.at( i )->getCurrFrame()->haveSameFmt( + videoSubWindowList.at( 0 )->getCurrFrame() ) ) { videoSubWindowList.clear(); - qobject_cast( m_pcParent )->printMessage( "Error! Incompatible frames", LOG_ERROR ); + qobject_cast( m_pcParent ) + ->printMessage( "Error! Incompatible frames", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } @@ -356,13 +380,15 @@ Void ModulesHandle::activateModule() ModulesHandleOptDialog moduleOptDialog( m_pcParent, pcCurrAppModuleIf ); if( moduleOptDialog.runConfiguration() == QDialog::Rejected ) { - qobject_cast( m_pcParent )->printMessage( "Module canceled by user!", LOG_WARNINGS ); + qobject_cast( m_pcParent ) + ->printMessage( "Module canceled by user!", LOG_WARNINGS ); destroyModuleIf( pcCurrAppModuleIf ); return; } } - Bool bShowModulesNewWindow = m_arrayActions[FORCE_NEW_WINDOW_ACT]->isChecked() | bTmpForceNewWindow; + Bool bShowModulesNewWindow = + m_arrayActions[FORCE_NEW_WINDOW_ACT]->isChecked() | bTmpForceNewWindow; QString windowName; @@ -376,12 +402,12 @@ Void ModulesHandle::activateModule() windowName.append( QStringLiteral( "Module " ) ); windowName.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); - connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), m_appModuleVideo, - SLOT( updateSelectionArea( QRect ) ) ); - connect( pcModuleSubWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, - SLOT( zoomToFactorAll( double, QPoint ) ) ); - connect( pcModuleSubWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, - SLOT( moveAllScrollBars( const QPoint ) ) ); + connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), + m_appModuleVideo, SLOT( updateSelectionArea( QRect ) ) ); + connect( pcModuleSubWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), + m_appModuleVideo, SLOT( zoomToFactorAll( double, QPoint ) ) ); + connect( pcModuleSubWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), + m_appModuleVideo, SLOT( moveAllScrollBars( const QPoint ) ) ); pcCurrAppModuleIf->m_pcDisplaySubWindow = pcModuleSubWindow; } @@ -394,8 +420,10 @@ Void ModulesHandle::activateModule() titleDockWidget.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); titleDockWidget.append( " Information" ); pcCurrAppModuleIf->m_pcDockWidget = new QDockWidget( titleDockWidget, m_pcParent ); - pcCurrAppModuleIf->m_pcDockWidget->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable ); - pcCurrAppModuleIf->m_pcDockWidget->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); + pcCurrAppModuleIf->m_pcDockWidget->setFeatures( QDockWidget::DockWidgetMovable | + QDockWidget::DockWidgetFloatable ); + pcCurrAppModuleIf->m_pcDockWidget->setAllowedAreas( Qt::LeftDockWidgetArea | + Qt::RightDockWidgetArea ); pcCurrAppModuleIf->m_pcDockWidget->setWidget( pcCurrAppModuleIf->m_pcModuleDock ); qobject_cast( m_pcParent ) ->addDockWidget( Qt::RightDockWidgetArea, pcCurrAppModuleIf->m_pcDockWidget ); @@ -435,7 +463,8 @@ Void ModulesHandle::activateModule() if( !moduleCreated ) { - qobject_cast( m_pcParent )->printMessage( "Error! Module cannot be created", LOG_ERROR ); + qobject_cast( m_pcParent ) + ->printMessage( "Error! Module cannot be created", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } @@ -472,7 +501,8 @@ Void ModulesHandle::destroyModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) Void ModulesHandle::destroyWindowModules() { - VideoSubWindow* pcVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcVideoSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcVideoSubWindow ) { pcVideoSubWindow->disableModule(); @@ -489,7 +519,9 @@ Void ModulesHandle::destroyAllModulesIf() emit changed(); } -Void ModulesHandle::applyModuleIf( QList pcCurrModuleIfList, Bool isPlaying, Bool disableThreads ) +Void ModulesHandle::applyModuleIf( QList pcCurrModuleIfList, + Bool isPlaying, + Bool disableThreads ) { for( Int i = 0; i < pcCurrModuleIfList.size() && !isPlaying; i++ ) { @@ -526,7 +558,8 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) QStringList filter; filter << supported << formatsList << tr( "All Files (*)" ); - QString fileName = QFileDialog::getSaveFileName( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) ); + QString fileName = QFileDialog::getSaveFileName( m_pcParent, tr( "Open File" ), QString(), + filter.join( ";;" ) ); Width = pcCurrModuleIf->m_pcProcessedFrame->getWidth(); Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight(); @@ -535,8 +568,9 @@ Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf* pcCurrModuleIf ) FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate(); pcCurrModuleIf->m_pcModuleStream = new PlaYUVerStream; - if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, - PLAYUVER_LITTLE_ENDIAN, FrameRate, false ) ) + if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, + InputFormat, BitsPixel, PLAYUVER_LITTLE_ENDIAN, + FrameRate, false ) ) { delete pcCurrModuleIf->m_pcModuleStream; pcCurrModuleIf->m_pcModuleStream = NULL; diff --git a/app/ModulesHandle.h b/app/ModulesHandle.h index aebd565..12afbbf 100644 --- a/app/ModulesHandle.h +++ b/app/ModulesHandle.h @@ -26,8 +26,8 @@ #include "config.h" -#include #include +#include #include #if( QT_VERSION_PLAYUVER == 5 ) @@ -35,8 +35,8 @@ #elif( QT_VERSION_PLAYUVER == 4 ) #include #endif -#include "PlaYUVerAppModuleIf.h" #include "PlaYUVerAppDefs.h" +#include "PlaYUVerAppModuleIf.h" #include "lib/PlaYUVerFrame.h" class VideoHandle; diff --git a/app/ModulesHandleOptDialog.cpp b/app/ModulesHandleOptDialog.cpp index fecb4fe..d316897 100644 --- a/app/ModulesHandleOptDialog.cpp +++ b/app/ModulesHandleOptDialog.cpp @@ -24,11 +24,11 @@ #include "ModulesHandleOptDialog.h" -#include -#include -#include -#include #include +#include +#include +#include +#include #include "lib/PlaYUVerOptions.h" @@ -75,17 +75,20 @@ class OpionConfiguration : public QWidget String m_cName; }; -ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget* parent, PlaYUVerAppModuleIf* pcCurrModuleIf ) +ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget* parent, + PlaYUVerAppModuleIf* pcCurrModuleIf ) : QDialog( parent ), m_pcCurrModuleIf( pcCurrModuleIf ) { resize( 400, 10 ); setWindowTitle( "Select module parameters" ); - const PlaYUVerOptions::OptionsList& moduleOptions = m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList(); + const PlaYUVerOptions::OptionsList& moduleOptions = + m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList(); QVBoxLayout* optionsLayout = new QVBoxLayout; OpionConfiguration* pcOption; - for( PlaYUVerOptions::OptionsList::const_iterator it = moduleOptions.begin(); it != moduleOptions.end(); ++it ) + for( PlaYUVerOptions::OptionsList::const_iterator it = moduleOptions.begin(); + it != moduleOptions.end(); ++it ) { pcOption = new OpionConfiguration( ( *it )->opt ); m_apcOptionList.append( pcOption ); diff --git a/app/ModulesHandleOptDialog.h b/app/ModulesHandleOptDialog.h index 48973ca..2451121 100644 --- a/app/ModulesHandleOptDialog.h +++ b/app/ModulesHandleOptDialog.h @@ -25,9 +25,9 @@ #ifndef __MODULEHANDLEOPTDIALOG_H__ #define __MODULEHANDLEOPTDIALOG_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" #include "PlaYUVerAppModuleIf.h" +#include "config.h" #include #include diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 6b018c7..269a8e2 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -22,31 +22,32 @@ * \brief Main definition of the PlaYUVerApp app */ -#include +#include "PlaYUVerApp.h" +#include +#include #include +#include #include #include -#include -#include -#include #include -#include "PlaYUVerApp.h" +#include #ifdef USE_FERVOR #include "fvupdater.h" #endif -#include "lib/PlaYUVerOptions.h" -#include "PlaYUVerSubWindowHandle.h" #include "AboutDialog.h" -#include "SubWindowAbstract.h" -#include "VideoSubWindow.h" -#include "VideoHandle.h" -#include "QualityHandle.h" -#include "ModulesHandle.h" #include "DialogSubWindowSelector.h" +#include "ModulesHandle.h" +#include "PlaYUVerSubWindowHandle.h" +#include "QualityHandle.h" +#include "SubWindowAbstract.h" +#include "VideoHandle.h" +#include "VideoSubWindow.h" +#include "lib/PlaYUVerOptions.h" #define SYNCHRONISED_ZOON 1 -PlaYUVerApp::PlaYUVerApp() : m_pcCurrentSubWindow( NULL ), m_pcCurrentVideoSubWindow( NULL ), m_pcAboutDialog( NULL ) +PlaYUVerApp::PlaYUVerApp() + : m_pcCurrentSubWindow( NULL ), m_pcCurrentVideoSubWindow( NULL ), m_pcAboutDialog( NULL ) { setWindowModality( Qt::ApplicationModal ); setWindowModality( Qt::NonModal ); @@ -118,7 +119,8 @@ Bool PlaYUVerApp::parseArgs( Int argc, Char* argv[] ) } } std::list& argv_unhandled = pcCmdParser.getUnhandledArgs(); - for( std::list::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++ ) + for( std::list::const_iterator it = argv_unhandled.begin(); + it != argv_unhandled.end(); it++ ) { loadFile( QString::fromStdString( *it ) ); } @@ -187,13 +189,15 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) printMessage( "File " + fileName + " do not exist!", LOG_ERROR ); return; } - VideoSubWindow* videoSubWindow = PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); + VideoSubWindow* videoSubWindow = + PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); if( videoSubWindow ) { m_pcWindowHandle->setActiveSubWindow( videoSubWindow ); return; } - videoSubWindow = new VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW ); // createSubWindow(); + videoSubWindow = + new VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW ); // createSubWindow(); SubWindowAbstract* subWindow = videoSubWindow; if( !pStreamInfo ) { @@ -218,8 +222,8 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) connect( subWindow, SIGNAL( aboutToClose( SubWindowAbstract* ) ), m_appModuleVideo, SLOT( closeSubWindow( SubWindowAbstract* ) ) ); - connect( subWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, - SLOT( zoomToFactorAll( double, QPoint ) ) ); + connect( subWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), + m_appModuleVideo, SLOT( zoomToFactorAll( double, QPoint ) ) ); connect( subWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, SLOT( moveAllScrollBars( const QPoint ) ) ); @@ -241,8 +245,8 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) catch( PlaYUVerFailure& e ) { videoSubWindow->close(); - QString warningMsg = - "Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); + QString warningMsg = "Cannot open file " + QFileInfo( fileName ).fileName() + + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); } @@ -272,8 +276,8 @@ Void PlaYUVerApp::open() QStringList filter; filter << supported << formatsList << tr( "All Files (*)" ); - QStringList fileNameList = - QFileDialog::getOpenFileNames( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); + QStringList fileNameList = QFileDialog::getOpenFileNames( this, tr( "Open File" ), + m_cLastOpenPath, filter.join( ";;" ) ); for( Int i = 0; i < fileNameList.size(); i++ ) { @@ -317,7 +321,8 @@ Void PlaYUVerApp::save() QStringList filter; filter << supported << formatsList << tr( "All Files (*)" ); - QString fileName = QFileDialog::getSaveFileName( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) ); + QString fileName = QFileDialog::getSaveFileName( this, tr( "Open File" ), m_cLastOpenPath, + filter.join( ";;" ) ); if( !fileName.isEmpty() ) { @@ -329,8 +334,8 @@ Void PlaYUVerApp::save() catch( PlaYUVerFailure& e ) { QApplication::restoreOverrideCursor(); - QString warningMsg = - "Cannot save file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what(); + QString warningMsg = "Cannot save file " + QFileInfo( fileName ).fileName() + + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); return; @@ -353,7 +358,8 @@ Void PlaYUVerApp::format() } catch( PlaYUVerFailure& e ) { - QString warningMsg = "Cannot change format of " + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + + QString warningMsg = "Cannot change format of " + + QFileInfo( pcVideoSubWindow->getCurrentFileName() ).fileName() + " with the following error: \n" + e.what(); QMessageBox::warning( this, QApplication::applicationName(), warningMsg ); printMessage( warningMsg, LOG_ERROR ); @@ -384,7 +390,8 @@ Void PlaYUVerApp::reloadAll() for( UInt c = 0; c < 3; c++ ) { - QList subWindowList = m_pcWindowHandle->findSubWindow( windowCategoryOrder[c] ); + QList subWindowList = + m_pcWindowHandle->findSubWindow( windowCategoryOrder[c] ); for( Int i = 0; i < subWindowList.size(); i++ ) { subWindowList.at( i )->refreshSubWindow(); @@ -427,7 +434,8 @@ Void PlaYUVerApp::zoomToFit() Void PlaYUVerApp::zoomToFitAll() { VideoSubWindow* videoSubWindow; - QList subWindowList = m_pcWindowHandle->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + QList subWindowList = + m_pcWindowHandle->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { videoSubWindow = qobject_cast( subWindowList.at( i ) ); @@ -494,7 +502,8 @@ VideoSubWindow* PlaYUVerApp::findVideoStreamSubWindow( const PlaYUVerSubWindowHa { QString canonicalFilePath = QFileInfo( fileName ).canonicalFilePath(); VideoSubWindow* pcSubWindow; - QList subWindowList = windowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); + QList subWindowList = + windowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { pcSubWindow = qobject_cast( subWindowList.at( i ) ); @@ -616,7 +625,8 @@ Void PlaYUVerApp::createActions() connect( m_arrayActions[SAVE_ACT], SIGNAL( triggered() ), this, SLOT( save() ) ); m_arrayActions[FORMAT_ACT] = new QAction( tr( "&Format" ), this ); - m_arrayActions[FORMAT_ACT]->setIcon( QIcon::fromTheme( "transform-scale", QIcon( ":/images/configuredialog.png" ) ) ); + m_arrayActions[FORMAT_ACT]->setIcon( + QIcon::fromTheme( "transform-scale", QIcon( ":/images/configuredialog.png" ) ) ); m_arrayActions[FORMAT_ACT]->setShortcut( Qt::CTRL + Qt::Key_F ); m_arrayActions[FORMAT_ACT]->setStatusTip( tr( "Open format dialog" ) ); connect( m_arrayActions[FORMAT_ACT], SIGNAL( triggered() ), this, SLOT( format() ) ); @@ -640,11 +650,13 @@ Void PlaYUVerApp::createActions() m_arrayActions[CLOSE_ACT] = new QAction( tr( "&Close" ), this ); m_arrayActions[CLOSE_ACT]->setIcon( style()->standardIcon( QStyle::SP_DialogCloseButton ) ); m_arrayActions[CLOSE_ACT]->setStatusTip( tr( "Close the active window" ) ); - connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), m_pcWindowHandle, SLOT( removeActiveSubWindow() ) ); + connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), m_pcWindowHandle, + SLOT( removeActiveSubWindow() ) ); m_arrayActions[CLOSEALL_ACT] = new QAction( tr( "Close &All" ), this ); m_arrayActions[CLOSEALL_ACT]->setStatusTip( tr( "Close all the windows" ) ); - connect( m_arrayActions[CLOSEALL_ACT], SIGNAL( triggered() ), m_pcWindowHandle, SLOT( removeAllSubWindow() ) ); + connect( m_arrayActions[CLOSEALL_ACT], SIGNAL( triggered() ), m_pcWindowHandle, + SLOT( removeAllSubWindow() ) ); m_arrayActions[EXIT_ACT] = new QAction( tr( "E&xit" ), this ); m_arrayActions[EXIT_ACT]->setShortcuts( QKeySequence::Quit ); @@ -656,32 +668,37 @@ Void PlaYUVerApp::createActions() connect( mapperZoom, SIGNAL( mapped( int ) ), this, SLOT( scaleFrame( int ) ) ); m_arrayActions[ZOOM_IN_ACT] = new QAction( tr( "Zoom &In (+25%)" ), this ); - m_arrayActions[ZOOM_IN_ACT]->setIcon( QIcon::fromTheme( "zoom-in", QIcon( ":/images/zoomin.png" ) ) ); + m_arrayActions[ZOOM_IN_ACT]->setIcon( + QIcon::fromTheme( "zoom-in", QIcon( ":/images/zoomin.png" ) ) ); m_arrayActions[ZOOM_IN_ACT]->setShortcut( tr( "Ctrl++" ) ); m_arrayActions[ZOOM_IN_ACT]->setStatusTip( tr( "Scale the image up by 25%" ) ); connect( m_arrayActions[ZOOM_IN_ACT], SIGNAL( triggered() ), mapperZoom, SLOT( map() ) ); mapperZoom->setMapping( m_arrayActions[ZOOM_IN_ACT], 125 ); m_arrayActions[ZOOM_OUT_ACT] = new QAction( tr( "Zoom &Out (-25%)" ), this ); - m_arrayActions[ZOOM_OUT_ACT]->setIcon( QIcon::fromTheme( "zoom-out", QIcon( ":/images/zoomout.png" ) ) ); + m_arrayActions[ZOOM_OUT_ACT]->setIcon( + QIcon::fromTheme( "zoom-out", QIcon( ":/images/zoomout.png" ) ) ); m_arrayActions[ZOOM_OUT_ACT]->setShortcut( tr( "Ctrl+-" ) ); m_arrayActions[ZOOM_OUT_ACT]->setStatusTip( tr( "Scale the image down by 25%" ) ); connect( m_arrayActions[ZOOM_OUT_ACT], SIGNAL( triggered() ), mapperZoom, SLOT( map() ) ); mapperZoom->setMapping( m_arrayActions[ZOOM_OUT_ACT], 80 ); m_arrayActions[ZOOM_NORMAL_ACT] = new QAction( tr( "&Normal Size" ), this ); - m_arrayActions[ZOOM_NORMAL_ACT]->setIcon( QIcon::fromTheme( "zoom-original", QIcon( ":/images/zoomtonormal.png" ) ) ); + m_arrayActions[ZOOM_NORMAL_ACT]->setIcon( + QIcon::fromTheme( "zoom-original", QIcon( ":/images/zoomtonormal.png" ) ) ); m_arrayActions[ZOOM_NORMAL_ACT]->setShortcut( tr( "Ctrl+N" ) ); m_arrayActions[ZOOM_NORMAL_ACT]->setStatusTip( tr( "Show the image at its original size" ) ); connect( m_arrayActions[ZOOM_NORMAL_ACT], SIGNAL( triggered() ), this, SLOT( normalSize() ) ); m_arrayActions[ZOOM_FIT_ACT] = new QAction( tr( "Zoom to &Fit" ), this ); - m_arrayActions[ZOOM_FIT_ACT]->setIcon( QIcon::fromTheme( "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) ); + m_arrayActions[ZOOM_FIT_ACT]->setIcon( + QIcon::fromTheme( "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) ); m_arrayActions[ZOOM_FIT_ACT]->setStatusTip( tr( "Zoom in or out to fit on the window." ) ); connect( m_arrayActions[ZOOM_FIT_ACT], SIGNAL( triggered() ), this, SLOT( zoomToFit() ) ); m_arrayActions[ZOOM_FIT_ALL_ACT] = new QAction( tr( "Zoom to Fit All" ), this ); - // m_arrayActions[ZOOM_FIT_ALL_ACT]->setIcon( QIcon::fromTheme( "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) + // m_arrayActions[ZOOM_FIT_ALL_ACT]->setIcon( QIcon::fromTheme( + // "zoom-fit-best", QIcon( ":/images/fittowindow.png" ) ) // ); m_arrayActions[ZOOM_FIT_ALL_ACT]->setStatusTip( tr( "Apply zoom to fit to all windows" ) ); connect( m_arrayActions[ZOOM_FIT_ALL_ACT], SIGNAL( triggered() ), this, SLOT( zoomToFitAll() ) ); @@ -791,7 +808,8 @@ Void PlaYUVerApp::createToolBars() m_pcZoomFactorSBox->setSingleStep( 10.0 ); m_pcZoomFactorSBox->setValue( 100.0 ); m_pcZoomFactorSBox->setSuffix( "%" ); - connect( m_pcZoomFactorSBox, SIGNAL( valueChanged( double ) ), this, SLOT( zoomFromSBox( double ) ) ); + connect( m_pcZoomFactorSBox, SIGNAL( valueChanged( double ) ), this, + SLOT( zoomFromSBox( double ) ) ); m_arrayToolBars[VIEW_TOOLBAR]->addWidget( m_pcZoomFactorSBox ); m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_IN_ACT] ); m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_OUT_ACT] ); diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index 996ea2e..3edfbe6 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -36,11 +36,11 @@ #ifndef __PLAYUVERAPP_H__ #define __PLAYUVERAPP_H__ +#include "PlaYUVerAppDefs.h" #include "config.h" #include -#include #include -#include "PlaYUVerAppDefs.h" +#include #ifdef USE_QTDBUS #include "PlaYUVerAppAdaptor.h" #endif diff --git a/app/PlaYUVerAppAdaptor.cpp b/app/PlaYUVerAppAdaptor.cpp index 806089a..bdddbbb 100644 --- a/app/PlaYUVerAppAdaptor.cpp +++ b/app/PlaYUVerAppAdaptor.cpp @@ -22,11 +22,12 @@ * \brief Define function to manage the interface in DBus */ -#include #include "PlaYUVerAppAdaptor.h" #include "PlaYUVerApp.h" +#include -PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp* app ) : QDBusAbstractAdaptor( app ), m_app( app ) +PlaYUVerAppAdaptor::PlaYUVerAppAdaptor( PlaYUVerApp* app ) + : QDBusAbstractAdaptor( app ), m_app( app ) { // application dbus interface QDBusConnection::sessionBus().registerObject( QStringLiteral( PLAYUVER_DBUS_PATH ), this, diff --git a/app/PlaYUVerAppAdaptor.h b/app/PlaYUVerAppAdaptor.h index 8853485..d57236a 100644 --- a/app/PlaYUVerAppAdaptor.h +++ b/app/PlaYUVerAppAdaptor.h @@ -29,8 +29,8 @@ #include #include #include -#include #include +#include #define PLAYUVER_DBUS_SESSION_NAME "org.pixlra.PlaYUVer.application" #define PLAYUVER_DBUS_PATH "/MainApplication" @@ -68,7 +68,8 @@ class PlaYUVerAppAdaptor : public QDBusAbstractAdaptor Q_SIGNALS: /** * Notify the world that this kate instance is exiting. - * All apps should stop using the dbus interface of this instance after this signal got emitted. + * All apps should stop using the dbus interface of this instance after this + * signal got emitted. */ // void exiting(); // void documentClosed(const QString &token); diff --git a/app/PlaYUVerAppModuleIf.cpp b/app/PlaYUVerAppModuleIf.cpp index 5d334a6..7eed200 100644 --- a/app/PlaYUVerAppModuleIf.cpp +++ b/app/PlaYUVerAppModuleIf.cpp @@ -26,16 +26,18 @@ #include "VideoSubWindow.h" #include "VideoSubWindow.h" -PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, QAction* action, PlaYUVerModuleIf* module ) - : m_bIsRunning( false ), - m_pcModuleAction( action ), - m_pcModule( module ), - m_pcDisplaySubWindow( NULL ), - m_pcDockWidget( NULL ), - m_pcModuleDock( NULL ), - m_pcModuleStream( NULL ), - m_pcProcessedFrame( NULL ), - m_dMeasurementResult( 0 ) +PlaYUVerAppModuleIf::PlaYUVerAppModuleIf( QObject* parent, + QAction* action, + PlaYUVerModuleIf* module ) + : m_bIsRunning( false ) + , m_pcModuleAction( action ) + , m_pcModule( module ) + , m_pcDisplaySubWindow( NULL ) + , m_pcDockWidget( NULL ) + , m_pcModuleDock( NULL ) + , m_pcModuleStream( NULL ) + , m_pcProcessedFrame( NULL ) + , m_dMeasurementResult( 0 ) { setParent( parent ); for( Int i = 0; i < MODULE_REQUIRES_MAX_NUM_FRAMES; i++ ) diff --git a/app/PlaYUVerAppModuleIf.h b/app/PlaYUVerAppModuleIf.h index c5dbc9a..4483e27 100644 --- a/app/PlaYUVerAppModuleIf.h +++ b/app/PlaYUVerAppModuleIf.h @@ -25,15 +25,15 @@ #ifndef __PLAYUVERAPPMODULESIF_H__ #define __PLAYUVERAPPMODULESIF_H__ -#include "config.h" -#include "PlaYUVerAppDefs.h" -#include -#include -#include -#include "lib/PlaYUVerFrame.h" -#include "lib/PlaYUVerStream.h" #include "ModuleHandleDock.h" +#include "PlaYUVerAppDefs.h" +#include "config.h" +#include "lib/PlaYUVerFrame.h" #include "lib/PlaYUVerModuleIf.h" +#include "lib/PlaYUVerStream.h" +#include +#include +#include class QAction; diff --git a/app/PlaYUVerMdiSubWindow.cpp b/app/PlaYUVerMdiSubWindow.cpp index efac05e..230a2bb 100644 --- a/app/PlaYUVerMdiSubWindow.cpp +++ b/app/PlaYUVerMdiSubWindow.cpp @@ -22,9 +22,9 @@ * \brief Re-implementation QMdiSubWindow */ -#include #include "PlaYUVerMdiSubWindow.h" #include "SubWindowAbstract.h" +#include PlaYUVerMdiSubWindow::PlaYUVerMdiSubWindow( QWidget* parent ) : QMdiSubWindow( parent ) { diff --git a/app/PlaYUVerMdiSubWindow.h b/app/PlaYUVerMdiSubWindow.h index 6a74a4a..f622de7 100644 --- a/app/PlaYUVerMdiSubWindow.h +++ b/app/PlaYUVerMdiSubWindow.h @@ -25,8 +25,8 @@ #ifndef __PLAYUVERMDISUBWINDOW_H__ #define __PLAYUVERMDISUBWINDOW_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #include class PlaYUVerMdiSubWindow : public QMdiSubWindow diff --git a/app/PlaYUVerSubWindowHandle.cpp b/app/PlaYUVerSubWindowHandle.cpp index e351e12..8132375 100644 --- a/app/PlaYUVerSubWindowHandle.cpp +++ b/app/PlaYUVerSubWindowHandle.cpp @@ -43,7 +43,8 @@ class PlaYUVerMdiArea : public QMdiArea { public: - PlaYUVerMdiArea( QWidget* parent = 0 ) : QMdiArea( parent ), m_pixmapLogo( ":/images/playuver-backgroud-logo.png" ) + PlaYUVerMdiArea( QWidget* parent = 0 ) + : QMdiArea( parent ), m_pixmapLogo( ":/images/playuver-backgroud-logo.png" ) { setBackgroundRole( QPalette::Background ); } @@ -69,7 +70,8 @@ class PlaYUVerMdiArea : public QMdiArea // for( Int i = 0; i < m_acLogMessages.size(); i++ ) // { - // painter.drawText( 5, height() - 5 - i * 15, m_acLogMessages.at( i ) ); + // painter.drawText( 5, height() - 5 - i * 15, m_acLogMessages.at( i ) + // ); // } // QPoint bottomLeftCorner( 0, viewport()->height() ); } @@ -118,8 +120,8 @@ Void PlaYUVerSubWindowHandle::resetWindowMode() } for( Int i = 0; i < m_apcMdiSubWindowList.size(); i++ ) { - disconnect( m_apcMdiSubWindowList.at( i ), SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), this, - SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); + disconnect( m_apcMdiSubWindowList.at( i ), SIGNAL( aboutToClose( PlaYUVerMdiSubWindow* ) ), + this, SLOT( removeMdiSubWindow( PlaYUVerMdiSubWindow* ) ) ); m_apcMdiSubWindowList.at( i )->close(); } m_apcMdiSubWindowList.clear(); @@ -161,7 +163,8 @@ Void PlaYUVerSubWindowHandle::setWindowMode( Int iWindowMode ) setVisible( true ); m_pcMdiArea = new PlaYUVerMdiArea; m_pcMdiArea->setActivationOrder( QMdiArea::ActivationHistoryOrder ); - connect( m_pcMdiArea, SIGNAL( subWindowActivated( QMdiSubWindow* ) ), this, SLOT( updateActiveSubWindow() ) ); + connect( m_pcMdiArea, SIGNAL( subWindowActivated( QMdiSubWindow* ) ), this, + SLOT( updateActiveSubWindow() ) ); m_pcWindowManagerLayout = new QHBoxLayout( this ); m_pcWindowManagerLayout->addWidget( m_pcMdiArea ); setLayout( m_pcWindowManagerLayout ); @@ -174,7 +177,8 @@ Void PlaYUVerSubWindowHandle::setWindowMode( Int iWindowMode ) // m_pcApp->resize( m_cMdiModeWindowSize ); if( m_pcActiveWindow ) { - m_pcApp->setWindowTitle( QApplication::applicationName() + " :: " + m_pcActiveWindow->getWindowName() ); + m_pcApp->setWindowTitle( QApplication::applicationName() + " :: " + + m_pcActiveWindow->getWindowName() ); } } m_iWindowMode = iWindowMode; @@ -201,7 +205,8 @@ Void PlaYUVerSubWindowHandle::updateActiveSubWindow( SubWindowAbstract* window ) if( mdiSubWindow ) { QWidget* activeWidget = m_pcMdiArea->activeSubWindow()->widget(); - Int windowIdx = m_apcSubWindowList.indexOf( qobject_cast( activeWidget ) ); + Int windowIdx = + m_apcSubWindowList.indexOf( qobject_cast( activeWidget ) ); if( windowIdx >= 0 ) { m_pcActiveWindow = m_apcSubWindowList.at( windowIdx ); @@ -210,7 +215,8 @@ Void PlaYUVerSubWindowHandle::updateActiveSubWindow( SubWindowAbstract* window ) } if( m_pcActiveWindow ) { - m_pcApp->setWindowTitle( QApplication::applicationName() + " :: " + m_pcActiveWindow->getWindowName() ); + m_pcApp->setWindowTitle( QApplication::applicationName() + " :: " + + m_pcActiveWindow->getWindowName() ); } } } @@ -230,7 +236,8 @@ Void PlaYUVerSubWindowHandle::addSubWindow( SubWindowAbstract* window, Qt::Windo { if( window ) { - connect( window, SIGNAL( updateStatusBar( const QString& ) ), m_pcApp, SLOT( printMessage( const QString& ) ) ); + connect( window, SIGNAL( updateStatusBar( const QString& ) ), m_pcApp, + SLOT( printMessage( const QString& ) ) ); connect( window, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_pcApp, SLOT( updateZoomFactorSBox() ) ); if( m_iWindowMode == DETACHEDSUBWINDOWMODE ) @@ -339,7 +346,8 @@ QList PlaYUVerSubWindowHandle::findSubWindow( const QString& return apcSubWindowList; } -SubWindowAbstract* PlaYUVerSubWindowHandle::findSubWindow( const SubWindowAbstract* subWindow ) const +SubWindowAbstract* PlaYUVerSubWindowHandle::findSubWindow( + const SubWindowAbstract* subWindow ) const { QList subWindowList = findSubWindow(); for( Int i = 0; i < subWindowList.size(); i++ ) @@ -418,7 +426,8 @@ Void PlaYUVerSubWindowHandle::tileSubWindows() } QSize totalWindowsSize( screenSize.width(), screenSize.height() - topLeftCornerWindow.y() ); - QSize windowsSize( totalWindowsSize.width() / numberTillingColumns, totalWindowsSize.height() / numberTillingRows ); + QSize windowsSize( totalWindowsSize.width() / numberTillingColumns, + totalWindowsSize.height() / numberTillingRows ); QPoint windowRelativePos; for( Int i = 0; i < m_apcSubWindowList.size(); i++ ) { @@ -445,7 +454,8 @@ Void PlaYUVerSubWindowHandle::cascadeSubWindows() Void PlaYUVerSubWindowHandle::createActions() { m_mapperWindow = new QSignalMapper( this ); - connect( m_mapperWindow, SIGNAL( mapped( QWidget* ) ), this, SLOT( setActiveSubWindow( QWidget* ) ) ); + connect( m_mapperWindow, SIGNAL( mapped( QWidget* ) ), this, + SLOT( setActiveSubWindow( QWidget* ) ) ); m_arrayActions.resize( TOTAL_ACT ); @@ -459,13 +469,16 @@ Void PlaYUVerSubWindowHandle::createActions() m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT] = new QAction( tr( "&Detached SubWindows" ), this ); m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT]->setCheckable( true ); m_actionGroupWindowMode->addAction( m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT] ); - connect( m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT], SIGNAL( triggered() ), m_mapperWindowMode, SLOT( map() ) ); - m_mapperWindowMode->setMapping( m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT], DETACHEDSUBWINDOWMODE ); + connect( m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT], SIGNAL( triggered() ), m_mapperWindowMode, + SLOT( map() ) ); + m_mapperWindowMode->setMapping( m_arrayActions[NORMAL_SUBWINDOW_MODE_ACT], + DETACHEDSUBWINDOWMODE ); m_arrayActions[MDI_SUBWINDOW_MODE_ACT] = new QAction( "&MDI SubWindows", this ); m_arrayActions[MDI_SUBWINDOW_MODE_ACT]->setCheckable( true ); m_actionGroupWindowMode->addAction( m_arrayActions[MDI_SUBWINDOW_MODE_ACT] ); - connect( m_arrayActions[MDI_SUBWINDOW_MODE_ACT], SIGNAL( triggered() ), m_mapperWindowMode, SLOT( map() ) ); + connect( m_arrayActions[MDI_SUBWINDOW_MODE_ACT], SIGNAL( triggered() ), m_mapperWindowMode, + SLOT( map() ) ); m_mapperWindowMode->setMapping( m_arrayActions[MDI_SUBWINDOW_MODE_ACT], MDISUBWINDOWMODE ); m_actionGroupWindowMode->actions().at( m_iWindowMode )->setChecked( true ); @@ -473,40 +486,51 @@ Void PlaYUVerSubWindowHandle::createActions() m_arrayActions[CLOSE_ACT] = new QAction( tr( "&Close" ), this ); m_arrayActions[CLOSE_ACT]->setIcon( style()->standardIcon( QStyle::SP_DialogCloseButton ) ); m_arrayActions[CLOSE_ACT]->setStatusTip( tr( "Close the active window" ) ); - connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, SLOT( removeActiveSubWindow() ) ); + connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, + SLOT( removeActiveSubWindow() ) ); m_arrayActions[CLOSE_ACT] = new QAction( tr( "&Close" ), this ); m_arrayActions[CLOSE_ACT]->setIcon( style()->standardIcon( QStyle::SP_DialogCloseButton ) ); m_arrayActions[CLOSE_ACT]->setStatusTip( tr( "Close the active window" ) ); - connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, SLOT( removeActiveSubWindow() ) ); + connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, + SLOT( removeActiveSubWindow() ) ); m_arrayActions[CLOSE_ALL_ACT] = new QAction( tr( "Close &All" ), this ); m_arrayActions[CLOSE_ALL_ACT]->setStatusTip( tr( "Close all the windows" ) ); - connect( m_arrayActions[CLOSE_ALL_ACT], SIGNAL( triggered() ), this, SLOT( removeAllSubWindow() ) ); + connect( m_arrayActions[CLOSE_ALL_ACT], SIGNAL( triggered() ), this, + SLOT( removeAllSubWindow() ) ); m_arrayActions[TILE_WINDOWS_ACT] = new QAction( tr( "Tile" ), this ); m_arrayActions[TILE_WINDOWS_ACT]->setIcon( QIcon( ":images/windowstile.png" ) ); m_arrayActions[TILE_WINDOWS_ACT]->setStatusTip( tr( "Tile the windows" ) ); m_arrayActions[TILE_WINDOWS_ACT]->setShortcut( tr( "Ctrl+T" ) ); - // connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), mdiArea, SLOT( tileSubWindows() ) ); - connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( tileSubWindows() ) ); + // connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), mdiArea, + // SLOT( tileSubWindows() ) ); + connect( m_arrayActions[TILE_WINDOWS_ACT], SIGNAL( triggered() ), this, + SLOT( tileSubWindows() ) ); m_arrayActions[CASCADE_WINDOWS_ACT] = new QAction( tr( "Cascade" ), this ); m_arrayActions[CASCADE_WINDOWS_ACT]->setIcon( QIcon( ":images/windowscascade.png" ) ); m_arrayActions[CASCADE_WINDOWS_ACT]->setStatusTip( tr( "Cascade the windows" ) ); - connect( m_arrayActions[CASCADE_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( cascadeSubWindows() ) ); + connect( m_arrayActions[CASCADE_WINDOWS_ACT], SIGNAL( triggered() ), this, + SLOT( cascadeSubWindows() ) ); m_arrayActions[NEXT_WINDOWS_ACT] = new QAction( tr( "Ne&xt" ), this ); m_arrayActions[NEXT_WINDOWS_ACT]->setShortcuts( QKeySequence::NextChild ); - m_arrayActions[NEXT_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowRight ) ) ); + m_arrayActions[NEXT_WINDOWS_ACT]->setIcon( + QIcon( style()->standardIcon( QStyle::SP_ArrowRight ) ) ); m_arrayActions[NEXT_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the next window" ) ); - // connect( m_arrayActions[NEXT_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activateNextSubWindow() ) ); + // connect( m_arrayActions[NEXT_WINDOWS_ACT], SIGNAL( triggered() ), this, + // SLOT( activateNextSubWindow() ) ); m_arrayActions[PREVIOUS_WINDOWS_ACT] = new QAction( tr( "Pre&vious" ), this ); m_arrayActions[PREVIOUS_WINDOWS_ACT]->setShortcuts( QKeySequence::PreviousChild ); - m_arrayActions[PREVIOUS_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowLeft ) ) ); - m_arrayActions[PREVIOUS_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the previous window" ) ); - // connect( m_arrayActions[PREVIOUS_WINDOWS_ACT], SIGNAL( triggered() ), this, SLOT( activatePreviousSubWindow() ) ); + m_arrayActions[PREVIOUS_WINDOWS_ACT]->setIcon( + QIcon( style()->standardIcon( QStyle::SP_ArrowLeft ) ) ); + m_arrayActions[PREVIOUS_WINDOWS_ACT]->setStatusTip( + tr( "Move the focus to the previous window" ) ); + // connect( m_arrayActions[PREVIOUS_WINDOWS_ACT], SIGNAL( triggered() ), + // this, SLOT( activatePreviousSubWindow() ) ); m_arrayActions[SEPARATOR_ACT] = new QAction( this ); m_arrayActions[SEPARATOR_ACT]->setSeparator( true ); @@ -574,8 +598,10 @@ Void PlaYUVerSubWindowHandle::updateMenu() Void PlaYUVerSubWindowHandle::readSettings() { QSettings appSettings; - m_cMdiModeWindowPosition = appSettings.value( "SubWindowManager/LastMdiPosition", QPoint( 200, 200 ) ).toPoint(); - m_cMdiModeWindowSize = appSettings.value( "SubWindowManager/LastMdiSize", QSize( 500, 400 ) ).toSize(); + m_cMdiModeWindowPosition = + appSettings.value( "SubWindowManager/LastMdiPosition", QPoint( 200, 200 ) ).toPoint(); + m_cMdiModeWindowSize = + appSettings.value( "SubWindowManager/LastMdiSize", QSize( 500, 400 ) ).toSize(); Int iWindowMode = appSettings.value( "SubWindowManager/SubWindowMode", MDISUBWINDOWMODE ).toInt(); setWindowMode( iWindowMode ); m_actionGroupWindowMode->actions().at( iWindowMode )->setChecked( true ); diff --git a/app/PlaYUVerSubWindowHandle.h b/app/PlaYUVerSubWindowHandle.h index 240f160..5865e02 100644 --- a/app/PlaYUVerSubWindowHandle.h +++ b/app/PlaYUVerSubWindowHandle.h @@ -25,9 +25,9 @@ #ifndef __PLAYUVERSUBWINDOWHANDLE_H__ #define __PLAYUVERSUBWINDOWHANDLE_H__ +#include #include #include -#include #include "PlaYUVerAppDefs.h" diff --git a/app/PlotSubWindow.cpp b/app/PlotSubWindow.cpp index 9cfb771..6d26720 100644 --- a/app/PlotSubWindow.cpp +++ b/app/PlotSubWindow.cpp @@ -92,16 +92,20 @@ PlotSubWindow::PlotSubWindow( const QString& windowTitle, QWidget* parent ) m_cPlotArea->xAxis2->setTickLabels( false ); m_cPlotArea->yAxis2->setVisible( true ); m_cPlotArea->yAxis2->setTickLabels( false ); - // make left and bottom axes always transfer their ranges to right and top axes: - connect( m_cPlotArea->xAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->xAxis2, SLOT( setRange( QCPRange ) ) ); - connect( m_cPlotArea->yAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->yAxis2, SLOT( setRange( QCPRange ) ) ); + // make left and bottom axes always transfer their ranges to right and top + // axes: + connect( m_cPlotArea->xAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->xAxis2, + SLOT( setRange( QCPRange ) ) ); + connect( m_cPlotArea->yAxis, SIGNAL( rangeChanged( QCPRange ) ), m_cPlotArea->yAxis2, + SLOT( setRange( QCPRange ) ) ); QFont legendFont = font(); // start out with MainWindow's font.. legendFont.setPointSize( 9 ); // and make a bit smaller for legend m_cPlotArea->legend->setFont( legendFont ); m_cPlotArea->legend->setBrush( backgroundBrush ); m_cPlotArea->legend->setTextColor( palette().text().color() ); - m_cPlotArea->legend->setBorderPen( QPen( palette().brush( QPalette::Active, QPalette::Shadow ), 1 ) ); + m_cPlotArea->legend->setBorderPen( + QPen( palette().brush( QPalette::Active, QPalette::Shadow ), 1 ) ); m_cPlotArea->legend->setVisible( false ); m_cPlotArea->setInteractions( QCP::iRangeZoom | QCP::iRangeDrag ); // QCP::iSelectPlottables @@ -148,8 +152,10 @@ Void PlotSubWindow::scaleView( Double scale, QPoint center ) // for( UInt dim = 0; dim < 2; dim++ ) // aNewAxisRange[axis][dim] = m_aAxisRange[axis][dim] / m_dScaleFactor; // - // m_cPlotArea->xAxis->setRange( aNewAxisRange[HORIZONTAL][0], aNewAxisRange[HORIZONTAL][1] ); - // m_cPlotArea->yAxis->setRange( aNewAxisRange[VERTICAL][0], aNewAxisRange[VERTICAL][1] ); + // m_cPlotArea->xAxis->setRange( aNewAxisRange[HORIZONTAL][0], + // aNewAxisRange[HORIZONTAL][1] ); + // m_cPlotArea->yAxis->setRange( aNewAxisRange[VERTICAL][0], + // aNewAxisRange[VERTICAL][1] ); m_cPlotArea->xAxis->scaleRange( scale, 0 ); m_cPlotArea->yAxis->scaleRange( scale, 0 ); @@ -188,7 +194,9 @@ Void PlotSubWindow::setAxisRange( const QLine& axisLimits ) setAxisRange( VERTICAL, axisLimits.y1(), axisLimits.y2() ); } -Void PlotSubWindow::setAxisRange( PlotSubWindow::Axis eAxis, const Int& axisStart, const Int& axisEnd ) +Void PlotSubWindow::setAxisRange( PlotSubWindow::Axis eAxis, + const Int& axisStart, + const Int& axisEnd ) { if( eAxis == HORIZONTAL ) { @@ -207,7 +215,9 @@ Void PlotSubWindow::setAxisRange( PlotSubWindow::Axis eAxis, const Int& axisStar m_cPlotArea->replot(); } -Void PlotSubWindow::addPlot( const QVector& arrayX, const QVector& arrayY, const QString& key ) +Void PlotSubWindow::addPlot( const QVector& arrayX, + const QVector& arrayY, + const QString& key ) { QCPGraph* newPlot = m_cPlotArea->addGraph(); QColor plotColor = m_arrayColorList.at( 0 ); @@ -219,7 +229,8 @@ Void PlotSubWindow::addPlot( const QVector& arrayX, const QVectorsetPen( m_cPlotPen ); // line style // pass data points to graphs: newPlot->setData( arrayX, arrayY ); - // let the ranges scale themselves so graph 0 fits perfectly in the visible area: + // let the ranges scale themselves so graph 0 fits perfectly in the visible + // area: newPlot->rescaleAxes( m_iNumberPlots > 1 ? true : false ); if( !key.isEmpty() ) diff --git a/app/PlotSubWindow.h b/app/PlotSubWindow.h index 2f35501..8d5780d 100644 --- a/app/PlotSubWindow.h +++ b/app/PlotSubWindow.h @@ -25,8 +25,8 @@ #ifndef __PLOTWINDOWHANDLE_H__ #define __PLOTWINDOWHANDLE_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #if( QT_VERSION_PLAYUVER == 5 ) #include #elif( QT_VERSION_PLAYUVER == 4 ) @@ -84,7 +84,9 @@ class PlotSubWindow : public SubWindowAbstract Void setKey( const QString& key ); - Void addPlot( const QVector& arrayX, const QVector& arrayY, const QString& key = QString() ); + Void addPlot( const QVector& arrayX, + const QVector& arrayY, + const QString& key = QString() ); }; #endif // __PLOTWINDOWHANDLE_H__ diff --git a/app/ProgressBar.cpp b/app/ProgressBar.cpp index b37c06d..237e7c9 100644 --- a/app/ProgressBar.cpp +++ b/app/ProgressBar.cpp @@ -24,10 +24,10 @@ #include "ProgressBar.h" #include -#include -#include -#include #include +#include +#include +#include ProgressBar::ProgressBar( QWidget* parent, UInt maxValue ) : QWidget( parent ), m_uiTotalProgress( maxValue ), m_uiProgress( 0 ) diff --git a/app/ProgressBar.h b/app/ProgressBar.h index 7a10a21..5a4079a 100644 --- a/app/ProgressBar.h +++ b/app/ProgressBar.h @@ -26,8 +26,8 @@ #define __PROGRESSBAR_H__ #include "PlaYUVerAppDefs.h" -#include #include +#include class QProgressBar; diff --git a/app/QualityHandle.cpp b/app/QualityHandle.cpp index 03f6dbe..976776c 100644 --- a/app/QualityHandle.cpp +++ b/app/QualityHandle.cpp @@ -22,14 +22,14 @@ * \brief Definition of the quality measurement sidebar */ -#include -#include "lib/LibMemory.h" -#include "PlaYUVerSubWindowHandle.h" #include "QualityHandle.h" -#include "VideoSubWindow.h" -#include "PlotSubWindow.h" #include "DialogSubWindowSelector.h" +#include "PlaYUVerSubWindowHandle.h" +#include "PlotSubWindow.h" #include "ProgressBar.h" +#include "VideoSubWindow.h" +#include "lib/LibMemory.h" +#include #if( QT_VERSION_PLAYUVER == 5 ) #include "QtConcurrent/qtconcurrentrun.h" #endif @@ -63,12 +63,15 @@ Void QualityHandle::createActions() m_arrayActions.resize( TOTAL_ACT ); m_arrayActions[SELECT_CURR_REF_ACT] = new QAction( "Mark as Reference", this ); - connect( m_arrayActions[SELECT_CURR_REF_ACT], SIGNAL( triggered() ), this, SLOT( slotSelectCurrentAsReference() ) ); + connect( m_arrayActions[SELECT_CURR_REF_ACT], SIGNAL( triggered() ), this, + SLOT( slotSelectCurrentAsReference() ) ); m_arrayActions[PLOT_QUALITY] = new QAction( "Plot Window's Quality", this ); - connect( m_arrayActions[PLOT_QUALITY], SIGNAL( triggered() ), this, SLOT( slotPlotQualitySingle() ) ); + connect( m_arrayActions[PLOT_QUALITY], SIGNAL( triggered() ), this, + SLOT( slotPlotQualitySingle() ) ); m_arrayActions[PLOT_SEVERAL_QUALITY] = new QAction( "Plot Several Quality", this ); - connect( m_arrayActions[PLOT_SEVERAL_QUALITY], SIGNAL( triggered() ), this, SLOT( slotPlotQualitySeveral() ) ); + connect( m_arrayActions[PLOT_SEVERAL_QUALITY], SIGNAL( triggered() ), this, + SLOT( slotPlotQualitySeveral() ) ); } QMenu* QualityHandle::createMenu() @@ -92,7 +95,8 @@ QDockWidget* QualityHandle::createDock() connect( m_pcQualityHandleSideBar, SIGNAL( signalQualityMetricChanged( int ) ), this, SLOT( slotQualityMetricChanged( int ) ) ); - connect( m_mapperQualityMetric, SIGNAL( mapped( int ) ), this, SLOT( slotQualityMetricChanged( int ) ) ); + connect( m_mapperQualityMetric, SIGNAL( mapped( int ) ), this, + SLOT( slotQualityMetricChanged( int ) ) ); slotQualityMetricChanged( 0 ); @@ -101,7 +105,8 @@ QDockWidget* QualityHandle::createDock() Void QualityHandle::updateMenus() { - VideoSubWindow* pcCurrentVideoSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcCurrentVideoSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcCurrentVideoSubWindow ? true : false; Bool hasReference = false; Bool isReference = false; @@ -196,7 +201,8 @@ Void QualityHandle::measureQuality( QVector apcWindowList ) for( UInt i = 0; i < numberOfWindows; i++ ) { pcCurrFrame = apcWindowList.at( i )->getCurrFrame(); - padQualityValues[i + 1].append( pcCurrFrame->getQuality( m_iQualityMetricIdx, pcReferenceFrame, LUMA ) ); + padQualityValues[i + 1].append( + pcCurrFrame->getQuality( m_iQualityMetricIdx, pcReferenceFrame, LUMA ) ); apcWindowList.at( i )->seekRelativeEvent( true ); } pcReferenceWindow->seekRelativeEvent( true ); @@ -215,7 +221,8 @@ Void QualityHandle::measureQuality( QVector apcWindowList ) } PlotSubWindow* pcPlotWindow = new PlotSubWindow( plotWindowTitle ); pcPlotWindow->setAxisName( - "Frame Number", QString::fromStdString( PlaYUVerFrame::supportedQualityMetricsList()[m_iQualityMetricIdx] ) ); + "Frame Number", + QString::fromStdString( PlaYUVerFrame::supportedQualityMetricsList()[m_iQualityMetricIdx] ) ); if( apcWindowList.size() > 1 ) { @@ -247,7 +254,8 @@ Void QualityHandle::slotQualityMetricChanged( Int idx ) Void QualityHandle::slotSelectCurrentAsReference() { - VideoSubWindow* pcRefSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcRefSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcRefSubWindow ) { VideoSubWindow* pcVideoSubWindow; @@ -267,7 +275,8 @@ Void QualityHandle::slotSelectCurrentAsReference() Void QualityHandle::slotPlotQualitySingle() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { if( pcSubWindow->getRefSubWindow() ) @@ -277,7 +286,8 @@ Void QualityHandle::slotPlotQualitySingle() //#ifndef QT_NO_CONCURRENT // m_cMeasurementResult.waitForFinished(); - // m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); + // m_cMeasurementResult = QtConcurrent::run( this, + // &QualityHandle::measureQuality, apcWindowList ); //#else QApplication::setOverrideCursor( Qt::WaitCursor ); measureQuality( apcWindowList ); @@ -290,7 +300,8 @@ Void QualityHandle::slotPlotQualitySingle() Void QualityHandle::slotPlotQualitySeveral() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); if( pcSubWindow ) { QVector apcWindowList; @@ -317,7 +328,8 @@ Void QualityHandle::slotPlotQualitySeveral() { //#ifndef QT_NO_CONCURRENT // m_cMeasurementResult.waitForFinished(); - // m_cMeasurementResult = QtConcurrent::run( this, &QualityHandle::measureQuality, apcWindowList ); + // m_cMeasurementResult = QtConcurrent::run( this, + // &QualityHandle::measureQuality, apcWindowList ); //#else QApplication::setOverrideCursor( Qt::WaitCursor ); measureQuality( apcWindowList ); diff --git a/app/QualityHandle.h b/app/QualityHandle.h index 9b14912..d36c97b 100644 --- a/app/QualityHandle.h +++ b/app/QualityHandle.h @@ -25,8 +25,8 @@ #ifndef __QUALITYMEASUREMENT_H__ #define __QUALITYMEASUREMENT_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #include #if( QT_VERSION_PLAYUVER == 5 ) #include diff --git a/app/QualityMeasurementSidebar.cpp b/app/QualityMeasurementSidebar.cpp index 2e72f0f..e9a5784 100644 --- a/app/QualityMeasurementSidebar.cpp +++ b/app/QualityMeasurementSidebar.cpp @@ -22,12 +22,13 @@ * \brief Definition of the quality measurement sidebar */ -#include -#include "PlaYUVerSubWindowHandle.h" #include "QualityMeasurementSidebar.h" +#include "PlaYUVerSubWindowHandle.h" #include "VideoSubWindow.h" +#include -QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerSubWindowHandle* windowManager ) +QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, + PlaYUVerSubWindowHandle* windowManager ) : QWidget( parent ), m_pcMainWindowManager( windowManager ), m_pcCurrentVideoSubWindow( NULL ) { // Side bar area ----------------------------------------------------- @@ -98,7 +99,8 @@ QualityMeasurementSidebar::QualityMeasurementSidebar( QWidget* parent, PlaYUVerS setLayout( mainLayout ); connect( m_comboBoxRef, SIGNAL( activated( int ) ), this, SLOT( slotReferenceChanged( int ) ) ); - connect( m_comboBoxMetric, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotQualityMetricChanged( int ) ) ); + connect( m_comboBoxMetric, SIGNAL( currentIndexChanged( int ) ), this, + SLOT( slotQualityMetricChanged( int ) ) ); } QualityMeasurementSidebar::~QualityMeasurementSidebar() @@ -129,7 +131,8 @@ Void QualityMeasurementSidebar::updateSubWindowList() m_pcVideoWindowList.clear(); VideoSubWindow* pcVideoSubWindow; - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { pcVideoSubWindow = qobject_cast( subWindowList.at( i ) ); @@ -139,7 +142,8 @@ Void QualityMeasurementSidebar::updateSubWindowList() } if( m_pcCurrentVideoSubWindow ) { - if( !m_pcCurrentVideoSubWindow->getCurrFrame()->haveSameFmt( pcVideoSubWindow->getCurrFrame() ) ) + if( !m_pcCurrentVideoSubWindow->getCurrFrame()->haveSameFmt( + pcVideoSubWindow->getCurrFrame() ) ) { continue; } diff --git a/app/QualityMeasurementSidebar.h b/app/QualityMeasurementSidebar.h index 9fb4e1b..de41690 100644 --- a/app/QualityMeasurementSidebar.h +++ b/app/QualityMeasurementSidebar.h @@ -25,17 +25,17 @@ #ifndef __QUALITYMEASUREMENTSIDEBAR_H__ #define __QUALITYMEASUREMENTSIDEBAR_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #if( QT_VERSION_PLAYUVER == 5 ) #include #elif( QT_VERSION_PLAYUVER == 4 ) -#include #include +#include #endif -#include "lib/PlaYUVerStream.h" -#include "lib/PlaYUVerFrame.h" #include "HistogramWidget.h" +#include "lib/PlaYUVerFrame.h" +#include "lib/PlaYUVerStream.h" class PlaYUVerSubWindowHandle; class VideoSubWindow; diff --git a/app/SeekStreamDialog.cpp b/app/SeekStreamDialog.cpp index f165cfb..b8c4bbb 100644 --- a/app/SeekStreamDialog.cpp +++ b/app/SeekStreamDialog.cpp @@ -24,11 +24,11 @@ #include "SeekStreamDialog.h" #include "lib/PlaYUVerStream.h" -#include -#include -#include #include +#include #include +#include +#include SeekStreamDialog::SeekStreamDialog( PlaYUVerStream* pcCurrStream, QWidget* parent ) : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint ), m_iSelectedFrameNum() @@ -57,7 +57,8 @@ SeekStreamDialog::SeekStreamDialog( PlaYUVerStream* pcCurrStream, QWidget* paren QVBoxLayout* verticalLayout = new QVBoxLayout; QHBoxLayout* horizontalLayout = new QHBoxLayout; horizontalLayout->addWidget( pcLabel ); - horizontalLayout->addItem( new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); + horizontalLayout->addItem( + new QSpacerItem( 20, 10, QSizePolicy::Expanding, QSizePolicy::Minimum ) ); horizontalLayout->addWidget( m_spinFrameNum ); verticalLayout->addLayout( horizontalLayout ); verticalLayout->addWidget( dialogButtonOkCancel, Qt::AlignRight ); diff --git a/app/SeekStreamDialog.h b/app/SeekStreamDialog.h index b74bb5d..7f4c9b1 100644 --- a/app/SeekStreamDialog.h +++ b/app/SeekStreamDialog.h @@ -25,9 +25,9 @@ #ifndef __SEEKSTREAMDIALOG_H__ #define __SEEKSTREAMDIALOG_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" #include "PlaYUVerAppModuleIf.h" +#include "config.h" #include #include diff --git a/app/SubWindowAbstract.cpp b/app/SubWindowAbstract.cpp index e58b559..429097a 100644 --- a/app/SubWindowAbstract.cpp +++ b/app/SubWindowAbstract.cpp @@ -22,15 +22,16 @@ * \brief Abstract class to handle subwindows */ -#include -#include -#include -#include -#include #include "SubWindowAbstract.h" #include "PlaYUVerMdiSubWindow.h" +#include +#include +#include +#include +#include -SubWindowAbstract::SubWindowAbstract( QWidget* parent, UInt category ) : QWidget( parent ), m_cSubWindow( NULL ) +SubWindowAbstract::SubWindowAbstract( QWidget* parent, UInt category ) + : QWidget( parent ), m_cSubWindow( NULL ) { setParent( parent ); setVisible( false ); diff --git a/app/SubWindowAbstract.h b/app/SubWindowAbstract.h index 04b06cc..a326564 100644 --- a/app/SubWindowAbstract.h +++ b/app/SubWindowAbstract.h @@ -37,12 +37,12 @@ #ifndef __SUBWINDOWABSTRACT_H__ #define __SUBWINDOWABSTRACT_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" -#include -#include +#include "config.h" #include #include +#include +#include class QHBoxLayout; class QFocusEvent; @@ -89,7 +89,8 @@ class SubWindowAbstract : public QWidget */ virtual Void zoomToFit() = 0; /** - * Scale the image (zoomed in or out) to speficied absolute zoom value (1.0 = original size). + * Scale the image (zoomed in or out) to speficied absolute zoom value (1.0 = + * original size). */ virtual Void zoomToFactor( Double factor, QPoint center = QPoint() ) = 0; /** @@ -145,7 +146,8 @@ class SubWindowAbstract : public QWidget */ void zoomFactorChanged_SWindow( const double, const QPoint ); /** - * Notify that scrollbar position was changed by internal event (e.g. by mouse panning ) + * Notify that scrollbar position was changed by internal event (e.g. by mouse + * panning ) */ void scrollBarMoved_SWindow( const QPoint ); /** diff --git a/app/VideoHandle.cpp b/app/VideoHandle.cpp index a7dcd08..2199474 100644 --- a/app/VideoHandle.cpp +++ b/app/VideoHandle.cpp @@ -22,21 +22,21 @@ * \brief Class to handle video playback */ -#include "PlaYUVerApp.h" #include "VideoHandle.h" -#include "VideoSubWindow.h" -#include "PlaYUVerSubWindowHandle.h" #include "DialogSubWindowSelector.h" -#include "SeekStreamDialog.h" #include "FramePropertiesDock.h" +#include "PlaYUVerApp.h" +#include "PlaYUVerSubWindowHandle.h" +#include "SeekStreamDialog.h" +#include "VideoSubWindow.h" #include "WidgetFrameNumber.h" -#include -#include #include +#include +#include #include #include -#include -#include +#include +#include #if( _CONTROL_PLAYING_TIME_ == 1 ) #include #endif @@ -77,16 +77,20 @@ Void VideoHandle::createActions() m_arrayActions[VIDEO_BACKWARD_ACT] = new QAction( "Video Backward", this ); m_arrayActions[VIDEO_BACKWARD_ACT]->setStatusTip( "Seek backward" ); - m_arrayActions[VIDEO_BACKWARD_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_MediaSeekBackward ) ) ); + m_arrayActions[VIDEO_BACKWARD_ACT]->setIcon( + QIcon( style()->standardIcon( QStyle::SP_MediaSeekBackward ) ) ); m_arrayActions[VIDEO_BACKWARD_ACT]->setShortcut( Qt::Key_Left ); - connect( m_arrayActions[VIDEO_BACKWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, SLOT( map() ) ); + connect( m_arrayActions[VIDEO_BACKWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, + SLOT( map() ) ); m_mapperVideoSeek->setMapping( m_arrayActions[VIDEO_BACKWARD_ACT], 0 ); m_arrayActions[VIDEO_FORWARD_ACT] = new QAction( "Video Forward", this ); m_arrayActions[VIDEO_FORWARD_ACT]->setStatusTip( "Seek forward" ); - m_arrayActions[VIDEO_FORWARD_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_MediaSeekForward ) ) ); + m_arrayActions[VIDEO_FORWARD_ACT]->setIcon( + QIcon( style()->standardIcon( QStyle::SP_MediaSeekForward ) ) ); m_arrayActions[VIDEO_FORWARD_ACT]->setShortcut( Qt::Key_Right ); - connect( m_arrayActions[VIDEO_FORWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, SLOT( map() ) ); + connect( m_arrayActions[VIDEO_FORWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, + SLOT( map() ) ); m_mapperVideoSeek->setMapping( m_arrayActions[VIDEO_FORWARD_ACT], 1 ); m_arrayActions[VIDEO_GOTO_ACT] = new QAction( "Go to", this ); @@ -108,13 +112,16 @@ Void VideoHandle::createActions() m_arrayActions[VIDEO_LOCK_SELECTION_ACT] = new QAction( "Sync Play", this ); m_arrayActions[VIDEO_LOCK_SELECTION_ACT]->setStatusTip( - "Select which windows should be played synchronized. Press Ctrl while click to quickly to select all!" ); - connect( m_arrayActions[VIDEO_LOCK_SELECTION_ACT], SIGNAL( triggered() ), this, SLOT( videoSelectionButtonEvent() ) ); + "Select which windows should be played synchronized. Press Ctrl while " + "click to quickly to select all!" ); + connect( m_arrayActions[VIDEO_LOCK_SELECTION_ACT], SIGNAL( triggered() ), this, + SLOT( videoSelectionButtonEvent() ) ); m_pcFrameSlider = new QSlider; m_pcFrameSlider->setOrientation( Qt::Horizontal ); m_pcFrameSlider->setMaximumWidth( 2000 ); - m_pcFrameSlider->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) ); + m_pcFrameSlider->setSizePolicy( + QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) ); m_pcFrameSlider->setEnabled( false ); m_pcFrameSlider->setTracking( false ); connect( m_pcFrameSlider, SIGNAL( valueChanged( int ) ), this, SLOT( seekSliderEvent( int ) ) ); @@ -133,7 +140,8 @@ Void VideoHandle::createActions() m_arrayActions[NAVIGATION_TOOL_ACT]->setChecked( true ); m_arrayActions[NAVIGATION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_1 ); actionGroupTools->addAction( m_arrayActions[NAVIGATION_TOOL_ACT] ); - connect( m_arrayActions[NAVIGATION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) ); + connect( m_arrayActions[NAVIGATION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, + SLOT( map() ) ); m_mapperTools->setMapping( m_arrayActions[NAVIGATION_TOOL_ACT], ViewArea::NavigationView ); m_arrayActions[SELECTION_TOOL_ACT] = new QAction( "Selection Tool", this ); @@ -141,7 +149,8 @@ Void VideoHandle::createActions() m_arrayActions[SELECTION_TOOL_ACT]->setChecked( false ); m_arrayActions[SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_2 ); actionGroupTools->addAction( m_arrayActions[SELECTION_TOOL_ACT] ); - connect( m_arrayActions[SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) ); + connect( m_arrayActions[SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, + SLOT( map() ) ); m_mapperTools->setMapping( m_arrayActions[SELECTION_TOOL_ACT], ViewArea::NormalSelectionView ); m_arrayActions[BLOCK_SELECTION_TOOL_ACT] = new QAction( "Block Selection Tool", this ); @@ -149,13 +158,16 @@ Void VideoHandle::createActions() m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setChecked( false ); m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_3 ); actionGroupTools->addAction( m_arrayActions[BLOCK_SELECTION_TOOL_ACT] ); - connect( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) ); - m_mapperTools->setMapping( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], ViewArea::BlockSelectionView ); + connect( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, + SLOT( map() ) ); + m_mapperTools->setMapping( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], + ViewArea::BlockSelectionView ); m_arrayActions[SHOW_GRID_ACT] = new QAction( "Show grid", this ); m_arrayActions[SHOW_GRID_ACT]->setCheckable( true ); m_arrayActions[SHOW_GRID_ACT]->setChecked( false ); - connect( m_arrayActions[SHOW_GRID_ACT], SIGNAL( toggled( bool ) ), this, SLOT( toggleGrid( bool ) ) ); + connect( m_arrayActions[SHOW_GRID_ACT], SIGNAL( toggled( bool ) ), this, + SLOT( toggleGrid( bool ) ) ); } QMenu* VideoHandle::createVideoMenu() @@ -243,7 +255,8 @@ QWidget* VideoHandle::createStatusBarMessage() Void VideoHandle::updateMenus() { - VideoSubWindow* pcSubWindow = qobject_cast( m_pcMainWindowManager->activeSubWindow() ); + VideoSubWindow* pcSubWindow = + qobject_cast( m_pcMainWindowManager->activeSubWindow() ); Bool hasSubWindow = pcSubWindow ? true : false; m_arrayActions[PLAY_ACT]->setEnabled( hasSubWindow ); @@ -270,8 +283,10 @@ Void VideoHandle::updateMenus() Void VideoHandle::readSettings() { QSettings appSettings; - m_arrayActions[VIDEO_REPEAT_ACT]->setChecked( appSettings.value( "VideoHandle/Repeat", false ).toBool() ); - m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->setChecked( appSettings.value( "VideoHandle/VideoZoomLock", false ).toBool() ); + m_arrayActions[VIDEO_REPEAT_ACT]->setChecked( + appSettings.value( "VideoHandle/Repeat", false ).toBool() ); + m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->setChecked( + appSettings.value( "VideoHandle/VideoZoomLock", false ).toBool() ); if( !appSettings.value( "VideoHandle/FrameProperties", true ).toBool() ) m_pcFramePropertiesDock->close(); @@ -283,7 +298,8 @@ Void VideoHandle::writeSettings() { QSettings appSettings; appSettings.setValue( "VideoHandle/Repeat", m_arrayActions[VIDEO_REPEAT_ACT]->isChecked() ); - appSettings.setValue( "VideoHandle/VideoZoomLock", m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() ); + appSettings.setValue( "VideoHandle/VideoZoomLock", + m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() ); appSettings.setValue( "VideoHandle/FrameProperties", m_pcFramePropertiesSideBar->isVisible() ); appSettings.setValue( "VideoHandle/SelectedTool", m_uiViewTool ); } @@ -303,7 +319,8 @@ Void VideoHandle::update() QString resolution; if( pcFrame ) { - resolution.append( QString( "%1x%2" ).arg( pcFrame->getWidth() ).arg( pcFrame->getHeight() ) ); + resolution.append( + QString( "%1x%2" ).arg( pcFrame->getWidth() ).arg( pcFrame->getHeight() ) ); } if( pcStream ) @@ -376,7 +393,8 @@ Void VideoHandle::updateSelectionArea( QRect area ) Void VideoHandle::openSubWindow( VideoSubWindow* subWindow ) { - connect( subWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), this, SLOT( updateSelectionArea( QRect ) ) ); + connect( subWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), this, + SLOT( updateSelectionArea( QRect ) ) ); subWindow->getViewArea()->setTool( m_uiViewTool ); subWindow->getViewArea()->setGridVisible( m_arrayActions[SHOW_GRID_ACT]->isChecked() ); } @@ -433,7 +451,8 @@ Void VideoHandle::moveAllScrollBars( const QPoint offset ) QScrollBar* scrollBar; scrollBar = m_pcCurrentVideoSubWindow->getScroll()->horizontalScrollBar(); - // Do not move other images, if current image reached maximum or minimum scroll position + // Do not move other images, if current image reached maximum or minimum + // scroll position if( scrollBar->value() == scrollBar->maximum() && offset.x() > 0 ) newOffset.setX( 0 ); if( scrollBar->value() == scrollBar->minimum() && offset.x() < 0 ) @@ -511,7 +530,8 @@ Void VideoHandle::setTimerStatus() #if( _CONTROL_PLAYING_TIME_ == 1 ) if( m_pcPlayControlTimer && m_pcPlayingTimer->interval() > 0 ) { - qDebug() << "Desired Fps: " << 1000 / m_pcPlayingTimer->interval() << "Real Fps: " << 1000 / m_dAverageFps; + qDebug() << "Desired Fps: " << 1000 / m_pcPlayingTimer->interval() + << "Real Fps: " << 1000 / m_dAverageFps; delete m_pcPlayControlTimer; m_pcPlayControlTimer = NULL; @@ -599,8 +619,9 @@ Void VideoHandle::playEvent() { Bool bEndOfSequence = false; #if( _CONTROL_PLAYING_TIME_ == 1 ) - m_dAverageFps = Double( m_dAverageFps * m_uiNumberPlayedFrames + m_pcPlayControlTimer->elapsed() ) / - Double( m_uiNumberPlayedFrames + 1 ); + m_dAverageFps = + Double( m_dAverageFps * m_uiNumberPlayedFrames + m_pcPlayControlTimer->elapsed() ) / + Double( m_uiNumberPlayedFrames + 1 ); m_uiNumberPlayedFrames++; m_pcPlayControlTimer->restart(); #endif @@ -638,7 +659,8 @@ Void VideoHandle::seekEvent( Int direction ) { if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) ) { - if( !( ( UInt )( m_pcCurrentVideoSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= getMaxFrameNumber() && + if( !( ( UInt )( m_pcCurrentVideoSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= + getMaxFrameNumber() && direction > 0 ) ) { for( Int i = 0; i < m_acPlayingSubWindows.size(); i++ ) @@ -662,7 +684,8 @@ Void VideoHandle::seekVideo() { if( m_pcCurrentVideoSubWindow->getInputStream() ) { - SeekStreamDialog* dialogSeekVideo = new SeekStreamDialog( m_pcCurrentVideoSubWindow->getInputStream(), this ); + SeekStreamDialog* dialogSeekVideo = + new SeekStreamDialog( m_pcCurrentVideoSubWindow->getInputStream(), this ); Int newFrameNum = dialogSeekVideo->runDialog(); if( newFrameNum >= 0 ) { @@ -769,7 +792,8 @@ Void VideoHandle::setTool( Int tool ) { m_uiViewTool = tool; actionGroupTools->actions().at( m_uiViewTool )->setChecked( true ); - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { qobject_cast( subWindowList.at( i ) )->getViewArea()->setTool( m_uiViewTool ); @@ -778,9 +802,12 @@ Void VideoHandle::setTool( Int tool ) Void VideoHandle::toggleGrid( Bool checked ) { - QList subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); + QList subWindowList = + m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); for( Int i = 0; i < subWindowList.size(); i++ ) { - qobject_cast( subWindowList.at( i ) )->getViewArea()->setGridVisible( checked ); + qobject_cast( subWindowList.at( i ) ) + ->getViewArea() + ->setGridVisible( checked ); } } diff --git a/app/VideoHandle.h b/app/VideoHandle.h index 9add246..8330a81 100644 --- a/app/VideoHandle.h +++ b/app/VideoHandle.h @@ -25,13 +25,13 @@ #ifndef __VIDEOHANDLE_H__ #define __VIDEOHANDLE_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" -#include #include -#include #include +#include +#include #define _CONTROL_PLAYING_TIME_ 0 diff --git a/app/VideoSubWindow.cpp b/app/VideoSubWindow.cpp index 1fc9474..973105b 100644 --- a/app/VideoSubWindow.cpp +++ b/app/VideoSubWindow.cpp @@ -22,12 +22,12 @@ * \brief Video Sub windows handling */ -#include #include "VideoSubWindow.h" -#include "ModulesHandle.h" #include "ConfigureFormatDialog.h" +#include "ModulesHandle.h" #include "SubWindowAbstract.h" #include +#include #if( QT_VERSION_PLAYUVER == 5 ) #include "QtConcurrent/qtconcurrentrun.h" #endif @@ -43,8 +43,8 @@ QDataStream& operator<<( QDataStream& out, const PlaYUVerStreamInfoVector& array for( Int i = 0; i < array.size(); i++ ) { d = array.at( i ); - out << d.m_cFilename << d.m_uiWidth << d.m_uiHeight << d.m_iPelFormat << d.m_uiBitsPelPixel << d.m_iEndianness - << d.m_uiFrameRate << d.m_uiFileSize; + out << d.m_cFilename << d.m_uiWidth << d.m_uiHeight << d.m_iPelFormat << d.m_uiBitsPelPixel + << d.m_iEndianness << d.m_uiFrameRate << d.m_uiFileSize; } return out; } @@ -124,20 +124,21 @@ class VideoInformation : public QWidget if( m_bBusyWindow ) { painter.setFont( m_cCenterTextFont ); - painter.drawText( rect(), Qt::AlignHCenter | Qt::AlignVCenter, QStringLiteral( "Refreshing..." ) ); + painter.drawText( rect(), Qt::AlignHCenter | Qt::AlignVCenter, + QStringLiteral( "Refreshing..." ) ); painter.fillRect( rect(), QBrush( QColor::fromRgb( 255, 255, 255, 50 ), Qt::SolidPattern ) ); } } }; VideoSubWindow::VideoSubWindow( enum VideoSubWindowCategories category, QWidget* parent ) - : SubWindowAbstract( parent, SubWindowAbstract::VIDEO_SUBWINDOW | category ), - m_bWindowBusy( false ), - m_pCurrStream( NULL ), - m_pcCurrFrame( NULL ), - m_pcCurrentDisplayModule( NULL ), - m_pcReferenceSubWindow( NULL ), - m_bIsPlaying( false ) + : SubWindowAbstract( parent, SubWindowAbstract::VIDEO_SUBWINDOW | category ) + , m_bWindowBusy( false ) + , m_pCurrStream( NULL ) + , m_pcCurrFrame( NULL ) + , m_pcCurrentDisplayModule( NULL ) + , m_pcReferenceSubWindow( NULL ) + , m_bIsPlaying( false ) { // Create a new scroll area inside the sub-window m_pcScrollArea = new QScrollArea; @@ -153,10 +154,13 @@ VideoSubWindow::VideoSubWindow( enum VideoSubWindowCategories category, QWidget* connect( m_cViewArea, SIGNAL( zoomFactorChanged_byWheel( double, QPoint ) ), this, SIGNAL( zoomFactorChanged_SWindow( double, QPoint ) ) ); - connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, SLOT( adjustScrollBarByOffset( QPoint ) ) ); - connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, SIGNAL( scrollBarMoved_SWindow( QPoint ) ) ); + connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, + SLOT( adjustScrollBarByOffset( QPoint ) ) ); + connect( m_cViewArea, SIGNAL( scrollBarMoved( QPoint ) ), this, + SIGNAL( scrollBarMoved_SWindow( QPoint ) ) ); - connect( m_cViewArea, SIGNAL( selectionChanged( QRect ) ), this, SLOT( updateSelectedArea( QRect ) ) ); + connect( m_cViewArea, SIGNAL( selectionChanged( QRect ) ), this, + SLOT( updateSelectedArea( QRect ) ) ); connect( m_cViewArea, SIGNAL( positionChanged( const QPoint& ) ), this, SLOT( updatePixelValueStatusBar( const QPoint& ) ) ); @@ -313,8 +317,9 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) if( guessFormat( cFilename, Width, Height, InputFormat, BitsPel, Endianness ) || bForceDialog ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, - Endianness, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, + InputFormat, BitsPel, Endianness, + FrameRate ) == QDialog::Rejected ) { return false; } @@ -322,16 +327,19 @@ Bool VideoSubWindow::loadFile( QString cFilename, Bool bForceDialog ) try { - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate, true ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, + FrameRate, true ); } catch( ... ) { - if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat, BitsPel, - Endianness, FrameRate ) == QDialog::Rejected ) + if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, + InputFormat, BitsPel, Endianness, + FrameRate ) == QDialog::Rejected ) { return false; } - m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, FrameRate, true ); + m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness, + FrameRate, true ); } m_sStreamInfo.m_cFilename = cFilename; @@ -361,8 +369,9 @@ Bool VideoSubWindow::loadFile( PlaYUVerStreamInfo* streamInfo ) m_pCurrStream = new PlaYUVerStream; } - if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, streamInfo->m_uiHeight, - streamInfo->m_iPelFormat, streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, + if( !m_pCurrStream->open( streamInfo->m_cFilename.toStdString(), streamInfo->m_uiWidth, + streamInfo->m_uiHeight, streamInfo->m_iPelFormat, + streamInfo->m_uiBitsPelPixel, streamInfo->m_iEndianness, streamInfo->m_uiFrameRate, true ) ) { return false; @@ -394,7 +403,8 @@ Void VideoSubWindow::updateVideoWindowInfo() { if( arraySubWindows.at( i )->getWindowName() != getWindowName() ) { - sourceWindowList.append( QString( "Input %1 - " + arraySubWindows.at( i )->getWindowName() ).arg( i + 1 ) ); + sourceWindowList.append( + QString( "Input %1 - " + arraySubWindows.at( i )->getWindowName() ).arg( i + 1 ) ); } } } @@ -440,11 +450,13 @@ Bool VideoSubWindow::guessFormat( QString filename, { return false; } - if( !fileExtension.compare( "yuv" ) || !fileExtension.compare( "rgb" ) || !fileExtension.compare( "gray" ) ) + if( !fileExtension.compare( "yuv" ) || !fileExtension.compare( "rgb" ) || + !fileExtension.compare( "gray" ) ) { bGuessed = false; // Guess pixel format - QVector formats_list = QVector::fromStdVector( PlaYUVerFrame::supportedPixelFormatListNames() ); + QVector formats_list = + QVector::fromStdVector( PlaYUVerFrame::supportedPixelFormatListNames() ); for( Int i = 0; i < formats_list.size(); i++ ) { if( FilenameShort.contains( formats_list.at( i ).c_str(), Qt::CaseInsensitive ) ) @@ -473,7 +485,8 @@ Bool VideoSubWindow::guessFormat( QString filename, #if( QT_VERSION_PLAYUVER == 5 ) // Guess resolution - match %dx%d - QRegularExpressionMatch resolutionMatch = QRegularExpression( "_\\d*x\\d*" ).match( FilenameShort ); + QRegularExpressionMatch resolutionMatch = + QRegularExpression( "_\\d*x\\d*" ).match( FilenameShort ); if( resolutionMatch.hasMatch() ) { QString resolutionString = resolutionMatch.captured( 0 ); @@ -504,8 +517,8 @@ Bool VideoSubWindow::guessFormat( QString filename, Int count = 0, module, frame_bytes, match; for( UInt i = 0; i < stdResList.size(); i++ ) { - frame_bytes = - PlaYUVerFrame::getBytesPerFrame( stdResList[i].uiWidth, stdResList[i].uiHeight, rInputFormat, 8 ); + frame_bytes = PlaYUVerFrame::getBytesPerFrame( stdResList[i].uiWidth, + stdResList[i].uiHeight, rInputFormat, 8 ); module = uiFileSize % frame_bytes; if( module == 0 ) { @@ -683,8 +696,8 @@ Bool VideoSubWindow::save( QString filename ) PlaYUVerFrame* saveFrame = m_pcCurrFrame; if( m_cSelectedArea.isValid() ) { - saveFrame = new PlaYUVerFrame( m_pcCurrFrame, m_cSelectedArea.x(), m_cSelectedArea.y(), m_cSelectedArea.width(), - m_cSelectedArea.height() ); + saveFrame = new PlaYUVerFrame( m_pcCurrFrame, m_cSelectedArea.x(), m_cSelectedArea.y(), + m_cSelectedArea.width(), m_cSelectedArea.height() ); } if( !saveFrame ) { @@ -768,7 +781,8 @@ Void VideoSubWindow::stop() QSize VideoSubWindow::getScrollSize() { - return QSize( m_pcScrollArea->viewport()->size().width() - 5, m_pcScrollArea->viewport()->size().height() - 5 ); + return QSize( m_pcScrollArea->viewport()->size().width() - 5, + m_pcScrollArea->viewport()->size().height() - 5 ); } Void VideoSubWindow::adjustScrollBarByOffset( QPoint Offset ) @@ -809,7 +823,8 @@ Void VideoSubWindow::adjustScrollBarByScale( Double scale, QPoint center ) scrollBarH = m_pcScrollArea->horizontalScrollBar(); if( center.isNull() ) { - m_cCurrScroll.setX( int( scale * cLastScroll.x() + ( ( scale - 1 ) * scrollBarH->pageStep() / 2 ) ) ); + m_cCurrScroll.setX( + int( scale * cLastScroll.x() + ( ( scale - 1 ) * scrollBarH->pageStep() / 2 ) ) ); } else { @@ -825,7 +840,8 @@ Void VideoSubWindow::adjustScrollBarByScale( Double scale, QPoint center ) scrollBarV = m_pcScrollArea->verticalScrollBar(); if( center.isNull() ) { - m_cCurrScroll.setY( int( scale * cLastScroll.y() + ( ( scale - 1 ) * scrollBarV->pageStep() / 2 ) ) ); + m_cCurrScroll.setY( + int( scale * cLastScroll.y() + ( ( scale - 1 ) * scrollBarV->pageStep() / 2 ) ) ); } else { @@ -958,15 +974,19 @@ Void VideoSubWindow::updatePixelValueStatusBar( const QPoint& pos ) if( ColorSpace == PlaYUVerPixel::COLOR_YUV ) { sPixelValue = m_pcCurrFrame->getPixelValue( pos.x(), pos.y() ); - strStatus.append( - QString( "Y: %1 U: %2 V: %3" ).arg( sPixelValue.Y() ).arg( sPixelValue.Cb() ).arg( sPixelValue.Cr() ) ); + strStatus.append( QString( "Y: %1 U: %2 V: %3" ) + .arg( sPixelValue.Y() ) + .arg( sPixelValue.Cb() ) + .arg( sPixelValue.Cr() ) ); } if( ( ColorSpace == PlaYUVerPixel::COLOR_RGB ) ) { sPixelValue = m_pcCurrFrame->getPixelValue( pos.x(), pos.y() ); - strStatus.append( - QString( "R: %1 G: %2 B: %3" ).arg( sPixelValue.R() ).arg( sPixelValue.G() ).arg( sPixelValue.B() ) ); + strStatus.append( QString( "R: %1 G: %2 B: %3" ) + .arg( sPixelValue.R() ) + .arg( sPixelValue.G() ) + .arg( sPixelValue.B() ) ); } emit updateStatusBar( strStatus ); } diff --git a/app/VideoSubWindow.h b/app/VideoSubWindow.h index 78d1f39..ffcb74e 100644 --- a/app/VideoSubWindow.h +++ b/app/VideoSubWindow.h @@ -25,16 +25,16 @@ #ifndef __VIDEOSUBWINDOW_H__ #define __VIDEOSUBWINDOW_H__ -#include "config.h" -#include -#include -#include -#include -#include #include "PlaYUVerAppDefs.h" -#include "lib/PlaYUVerStream.h" #include "SubWindowAbstract.h" #include "ViewArea.h" +#include "config.h" +#include "lib/PlaYUVerStream.h" +#include +#include +#include +#include +#include class QScrollArea; diff --git a/app/ViewArea.cpp b/app/ViewArea.cpp index 397802b..22d4058 100644 --- a/app/ViewArea.cpp +++ b/app/ViewArea.cpp @@ -25,19 +25,19 @@ #include +#include "GridManager.h" +#include "ViewArea.h" +#include #include -#include +#include +#include +#include #include #include -#include -#include -#include -#include #include #include -#include -#include "ViewArea.h" -#include "GridManager.h" +#include +#include static const QColor selectionColor = Qt::cyan; static const QColor imageMaskColor = Qt::green; @@ -72,8 +72,8 @@ Void ViewArea::setImage( PlaYUVerFrame* pcFrame ) m_pcCurrFrame = pcFrame; m_uiPixelHalfScale = 1 << ( m_pcCurrFrame->getBitsPel() - 1 ); m_pcCurrFrame->fillRGBBuffer(); - QImage qimg = QImage( m_pcCurrFrame->getRGBBuffer(), m_pcCurrFrame->getWidth(), m_pcCurrFrame->getHeight(), - QImage::Format_RGB32 ); + QImage qimg = QImage( m_pcCurrFrame->getRGBBuffer(), m_pcCurrFrame->getWidth(), + m_pcCurrFrame->getHeight(), QImage::Format_RGB32 ); setImage( QPixmap::fromImage( qimg ) ); } @@ -432,11 +432,15 @@ Void ViewArea::paintEvent( QPaintEvent* event ) paInter.scale( m_dZoomFactor, m_dZoomFactor ); // This line is for fast paiting. Only visible area of the image is paInted. - // We take the exposed rect from the event (that gives us scroll/expose optimizations for free – no need - // to draw the whole pixmap if your widget is only partially exposed), and reverse map it with the paInter matrix. + // We take the exposed rect from the event (that gives us scroll/expose + // optimizations for free – no need + // to draw the whole pixmap if your widget is only partially exposed), and + // reverse map it with the paInter matrix. // That gives us the part of the pixmap that has actually been exposed. - // See: http://blog.qt.digia.com/blog/2006/05/13/fast-transformed-pixmapimage-drawing/ - QRect exposedRect = paInter.worldTransform().inverted().mapRect( event->rect() ).adjusted( -1, -1, 1, 1 ); + // See: + // http://blog.qt.digia.com/blog/2006/05/13/fast-transformed-pixmapimage-drawing/ + QRect exposedRect = + paInter.worldTransform().inverted().mapRect( event->rect() ).adjusted( -1, -1, 1, 1 ); // Draw the pixmap. paInter.drawPixmap( exposedRect, m_pixmap, exposedRect ); @@ -471,7 +475,8 @@ Void ViewArea::paintEvent( QPaintEvent* event ) /* if( m_xOffset || m_yOffset ) { paInter.setPen( Qt::black ); - paInter.drawRect( m_xOffset - 1, m_yOffset - 1, m_pixmap.width() * m_dZoomFactor + 1, m_pixmap.height() * + paInter.drawRect( m_xOffset - 1, m_yOffset - 1, m_pixmap.width() * + m_dZoomFactor + 1, m_pixmap.height() * m_dZoomFactor + 1 ); }*/ @@ -508,9 +513,10 @@ Void ViewArea::paintEvent( QPaintEvent* event ) else paInter.setPen( QColor( Qt::black ) ); - paInter.drawText( pixelRect, Qt::AlignCenter, "Y: " + QString::number( sPixelValue.Y() ) + "\n" + "U: " + - QString::number( sPixelValue.Cb() ) + "\n" + "V: " + - QString::number( sPixelValue.Cr() ) ); + paInter.drawText( pixelRect, Qt::AlignCenter, + "Y: " + QString::number( sPixelValue.Y() ) + "\n" + "U: " + + QString::number( sPixelValue.Cb() ) + "\n" + "V: " + + QString::number( sPixelValue.Cr() ) ); } if( frFormat == PlaYUVerPixel::COLOR_GRAY ) { @@ -521,7 +527,8 @@ Void ViewArea::paintEvent( QPaintEvent* event ) else paInter.setPen( QColor( Qt::black ) ); - paInter.drawText( pixelRect, Qt::AlignCenter, "Y: " + QString::number( sPixelValue.Y() ) ); + paInter.drawText( pixelRect, Qt::AlignCenter, + "Y: " + QString::number( sPixelValue.Y() ) ); } if( ( frFormat == PlaYUVerPixel::COLOR_RGB ) ) @@ -533,9 +540,10 @@ Void ViewArea::paintEvent( QPaintEvent* event ) else paInter.setPen( QColor( Qt::black ) ); - paInter.drawText( pixelRect, Qt::AlignCenter, "R: " + QString::number( sPixelValue.R() ) + "\n" + "G: " + - QString::number( sPixelValue.G() ) + "\n" + "B: " + - QString::number( sPixelValue.B() ) ); + paInter.drawText( pixelRect, Qt::AlignCenter, + "R: " + QString::number( sPixelValue.R() ) + "\n" + "G: " + + QString::number( sPixelValue.G() ) + "\n" + "B: " + + QString::number( sPixelValue.B() ) ); } } } @@ -1021,8 +1029,10 @@ QRect ViewArea::windowToView( const QRect& rc ) const r.setTopLeft( windowToView( rc.topLeft() ) ); // r.setRight ( (Int)( ceil(( rc.right() - m_xOffset)/m_dZoomFactor ))); // r.setBottom( (Int)( ceil(( rc.bottom()- m_yOffset)/m_dZoomFactor ))); - // r.setRight ( static_cast(( rc.right() - m_xOffset ) / m_dZoomFactor +1)); - // r.setBottom( static_cast(( rc.bottom() - m_xOffset ) / m_dZoomFactor+1)); + // r.setRight ( static_cast(( rc.right() - m_xOffset ) / + // m_dZoomFactor +1)); + // r.setBottom( static_cast(( rc.bottom() - m_xOffset ) / + // m_dZoomFactor+1)); r.setBottomRight( windowToView( rc.bottomRight() ) ); return r; } @@ -1042,13 +1052,19 @@ QRect ViewArea::viewToWindow( const QRect& rc ) const QRect r; r.setTopLeft( viewToWindow( rc.topLeft() ) ); - // r.setRight ( (Int)( ceil(( rc.right() +1+m_xOffset )*m_dZoomFactor ) - 1 )); - // r.setBottom( (Int)( ceil(( rc.bottom()+1+m_yOffset )*m_dZoomFactor ) - 1 )); - // r.setRight ( (Int)( ceil(( rc.right()+0.5)*m_dZoomFactor )+ m_xOffset )-1); - // r.setBottom( (Int)( ceil(( rc.bottom()+0.5)*m_dZoomFactor ) +m_yOffset )-1); + // r.setRight ( (Int)( ceil(( rc.right() +1+m_xOffset )*m_dZoomFactor ) - + // 1 )); + // r.setBottom( (Int)( ceil(( rc.bottom()+1+m_yOffset )*m_dZoomFactor ) - + // 1 )); + // r.setRight ( (Int)( ceil(( rc.right()+0.5)*m_dZoomFactor )+ m_xOffset + // )-1); + // r.setBottom( (Int)( ceil(( rc.bottom()+0.5)*m_dZoomFactor ) +m_yOffset + // )-1); // qDebug()<<"Right = "<< r.right(); - // r.setRight ( static_cast(( rc.right()+1) * m_dZoomFactor + m_xOffset -1) ); - // r.setBottom( static_cast(( rc.bottom()+1) * m_dZoomFactor + m_yOffset -1)); + // r.setRight ( static_cast(( rc.right()+1) * m_dZoomFactor + + // m_xOffset -1) ); + // r.setBottom( static_cast(( rc.bottom()+1) * m_dZoomFactor + + // m_yOffset -1)); r.setBottomRight( viewToWindow( rc.bottomRight() ) ); return r; diff --git a/app/ViewArea.h b/app/ViewArea.h index 1edd931..068d799 100644 --- a/app/ViewArea.h +++ b/app/ViewArea.h @@ -26,15 +26,15 @@ #ifndef __VIEWAREA_H__ #define __VIEWAREA_H__ -#include "config.h" +#include "GridManager.h" #include "PlaYUVerAppDefs.h" -#include -#include +#include "config.h" +#include "lib/PlaYUVerFrame.h" #include #include +#include #include -#include "GridManager.h" -#include "lib/PlaYUVerFrame.h" +#include class PlaYUVerStream; @@ -84,7 +84,8 @@ class ViewArea : public QWidget GridManager gridManager() const { return m_grid; } QColor maskColor() const { return m_maskColor; } Double getZoomFactor() { return m_dZoomFactor; } - // Scale function. Return used scale value (it may change when it touches the min or max zoom value) + // Scale function. Return used scale value (it may change when it touches the + // min or max zoom value) Double scaleZoomFactor( Double scale, QPoint center, QSize minimumSize ); Q_SIGNALS: diff --git a/app/WidgetFrameNumber.h b/app/WidgetFrameNumber.h index 495f0ef..afe3304 100644 --- a/app/WidgetFrameNumber.h +++ b/app/WidgetFrameNumber.h @@ -25,8 +25,8 @@ #ifndef __WIDGETFRAMENUMBER_H__ #define __WIDGETFRAMENUMBER_H__ -#include "config.h" #include "PlaYUVerAppDefs.h" +#include "config.h" #include #if( QT_VERSION_PLAYUVER == 5 ) #include diff --git a/app/external/qcustomplot.cpp b/app/external/qcustomplot.cpp index 41905a8..7efd181 100644 --- a/app/external/qcustomplot.cpp +++ b/app/external/qcustomplot.cpp @@ -32,14 +32,20 @@ /*! \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 + 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). + \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). */ /*! @@ -47,20 +53,27 @@ */ QCPPainter::QCPPainter() : QPainter(), mModes( pmDefault ), mIsAntialiasing( false ) { - // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // 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. + 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. + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt + versions before Qt5. */ -QCPPainter::QCPPainter( QPaintDevice* device ) : QPainter( device ), mModes( pmDefault ), mIsAntialiasing( false ) +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 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 @@ -71,7 +84,8 @@ QCPPainter::~QCPPainter() } /*! - Sets the pen of the painter and applies certain fixes to it, depending on the mode of this + 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. @@ -85,7 +99,8 @@ void QCPPainter::setPen( const QPen& pen ) /*! \overload - Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of + 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. @@ -99,7 +114,8 @@ void QCPPainter::setPen( const QColor& color ) /*! \overload - Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of + 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. @@ -113,8 +129,10 @@ void QCPPainter::setPen( Qt::PenStyle penStyle ) /*! \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 + 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. @@ -128,9 +146,12 @@ void QCPPainter::drawLine( const QLineF& line ) } /*! - 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 + 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 ) @@ -139,7 +160,8 @@ void QCPPainter::setAntialiasing( bool enabled ) if( mIsAntialiasing != enabled ) { mIsAntialiasing = enabled; - if( !mModes.testFlag( pmVectorized ) ) // antialiasing half-pixel shift only needed for rasterized outputs + if( !mModes.testFlag( pmVectorized ) ) // antialiasing half-pixel shift only + // needed for rasterized outputs { if( mIsAntialiasing ) translate( 0.5, 0.5 ); @@ -150,7 +172,8 @@ void QCPPainter::setAntialiasing( bool enabled ) } /*! - Sets the mode of the painter. This controls whether the painter shall adjust its + 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 ) @@ -159,12 +182,16 @@ void QCPPainter::setModes( QCPPainter::PainterModes 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 + 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 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. @@ -172,8 +199,10 @@ void QCPPainter::setModes( QCPPainter::PainterModes modes ) 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 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 @@ -182,7 +211,8 @@ bool QCPPainter::begin( QPaintDevice* device ) /*! \overload - Sets the mode of the painter. This controls whether the painter shall adjust its + 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 ) @@ -194,8 +224,10 @@ void QCPPainter::setMode( QCPPainter::PainterMode mode, bool enabled ) } /*! - 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. + 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. @@ -208,8 +240,10 @@ void QCPPainter::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. + 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. @@ -225,7 +259,8 @@ void QCPPainter::restore() } /*! - Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen + 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() @@ -245,17 +280,22 @@ void QCPPainter::makeNonCosmetic() /*! \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 + 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 + 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: + You can set all these configurations either by calling the respective + functions on an instance: \code QCPScatterStyle myScatter; myScatter.setShape(QCPScatterStyle::ssCircle); @@ -265,41 +305,58 @@ void QCPPainter::makeNonCosmetic() customPlot->graph(0)->setScatterStyle(myScatter); \endcode - Or you can use one of the various constructors that take different parameter combinations, making + 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: \code - customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5)); + customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, + Qt::blue, Qt::white, 5)); \endcode - \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable + \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 + 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: \code customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus); \endcode - 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 + 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. + 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 + 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. + 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. */ @@ -316,9 +373,12 @@ void QCPPainter::makeNonCosmetic() 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 + 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 @@ -327,9 +387,11 @@ void QCPPainter::makeNonCosmetic() /* end documentation of inline functions */ /*! - Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. + 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 + 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() @@ -338,10 +400,12 @@ QCPScatterStyle::QCPScatterStyle() } /*! - Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or + 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 + 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 ) @@ -350,63 +414,111 @@ QCPScatterStyle::QCPScatterStyle( ScatterShape shape, double size ) } /*! - 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. + 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 ) + : 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, + 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 ) +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 + 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 + \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 + 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 + \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 ) +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 + 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 ) + : 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 + 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. + 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( false ) +QCPScatterStyle::QCPScatterStyle( const QPainterPath& customPath, + const QPen& pen, + const QBrush& brush, + double size ) + : mSize( size ) + , mShape( ssCustom ) + , mPen( pen ) + , mBrush( brush ) + , mCustomPath( customPath ) + , mPenDefined( false ) { } @@ -423,7 +535,8 @@ void QCPScatterStyle::setSize( double size ) /*! Sets the shape to \a shape. - Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref + Note that the calls \ref setPixmap and \ref setCustomPath automatically set + the shape to \ref ssPixmap and \ref ssCustom, respectively. \see setSize @@ -436,7 +549,8 @@ void QCPScatterStyle::setShape( QCPScatterStyle::ScatterShape 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 + 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 @@ -448,8 +562,10 @@ void QCPScatterStyle::setPen( const QPen& 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. + 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 */ @@ -483,10 +599,13 @@ void QCPScatterStyle::setCustomPath( const QPainterPath& 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. + 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 + 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 @@ -500,7 +619,8 @@ void QCPScatterStyle::applyTo( QCPPainter* painter, const QPen& defaultPen ) con /*! 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 + 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 @@ -645,42 +765,65 @@ void QCPScatterStyle::drawShape( QCPPainter* painter, double x, double y ) const /*! \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 + 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 + 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. + 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 + 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 + 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 + 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. + 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 + 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. */ @@ -688,13 +831,15 @@ void QCPScatterStyle::drawShape( QCPPainter* painter, double x, double y ) const /*! \fn QList QCPLayer::children() const - Returns a list of all layerables on this layer. The order corresponds to the rendering order: + 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 + 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. @@ -705,17 +850,21 @@ void QCPScatterStyle::drawShape( QCPPainter* painter, double x, double y ) const /*! Creates a new QCPLayer instance. - Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. + 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. + \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 ) + : 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. @@ -723,25 +872,32 @@ QCPLayer::QCPLayer( QCustomPlot* parentPlot, const QString& layerName ) 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.) + // 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 " + 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 + 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 + QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each + layerable takes the visibility of the parent layer into account. */ void QCPLayer::setVisible( bool visible ) @@ -751,10 +907,13 @@ void QCPLayer::setVisible( bool 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. + 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 + 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 @@ -769,14 +928,16 @@ void QCPLayer::addChild( QCPLayerable* layerable, bool prepend ) mChildren.append( layerable ); } else - qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast( layerable ); + 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 + 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 @@ -784,7 +945,8 @@ void QCPLayer::addChild( QCPLayerable* layerable, bool prepend ) void QCPLayer::removeChild( QCPLayerable* layerable ) { if( !mChildren.removeOne( layerable ) ) - qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast( layerable ); + qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" + << reinterpret_cast( layerable ); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -794,10 +956,12 @@ void QCPLayer::removeChild( QCPLayerable* layerable ) /*! \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 + 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 + 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. @@ -807,57 +971,84 @@ void QCPLayer::removeChild( QCPLayerable* layerable ) /*! \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 + 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. + 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 + 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 +/*! \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 + 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 + 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 + 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 + 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 + 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 + 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. */ @@ -866,7 +1057,8 @@ void QCPLayer::removeChild( QCPLayerable* layerable ) /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); - This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to + This signal is emitted when the layer of this layerable changes, i.e. this + layerable is moved to a different layer. \see setLayer @@ -877,35 +1069,44 @@ void QCPLayer::removeChild( QCPLayerable* layerable ) /*! Creates a new QCPLayerable instance. - Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the + 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 + 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 + 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. + 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. */ QCPLayerable::QCPLayerable( QCustomPlot* plot, QString targetLayer, QCPLayerable* parentLayerable ) - : QObject( plot ), - mVisible( true ), - mParentPlot( plot ), - mParentLayerable( parentLayerable ), - mLayer( 0 ), - mAntialiased( true ) + : 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."; + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer + << "failed."; } } @@ -919,8 +1120,10 @@ QCPLayerable::~QCPLayerable() } /*! - 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 + 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 ) @@ -929,7 +1132,8 @@ void QCPLayerable::setVisible( bool on ) } /*! - Sets the \a layer of this layerable object. The object will be placed on top of the other objects + Sets the \a layer of this layerable object. The object will be placed on top + of the other objects already on \a layer. Returns true on success, i.e. if \a layer is a valid layer. @@ -965,7 +1169,8 @@ bool QCPLayerable::setLayer( const QString& layerName ) /*! Sets whether this object will be drawn antialiased or not. - Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and + Note that antialiasing settings may be overridden by + QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased( bool enabled ) @@ -974,16 +1179,22 @@ void QCPLayerable::setAntialiased( bool 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 + 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 + 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 + If this layerable doesn't have a direct layerable parent, returns the state of + this layerable's visibility. */ bool QCPLayerable::realVisibility() const @@ -993,36 +1204,56 @@ bool QCPLayerable::realVisibility() const } /*! - This function is used to decide whether a click hits a layerable object or not. + 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 + \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 item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a - click inside the area returns a constant value greater zero (typically the selectionTolerance of - the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function + If the item is represented not by single lines but by an area like QCPItemRect + or QCPItemText, a + click inside the area returns a constant value greater zero (typically the + selectionTolerance of + the parent QCustomPlot multiplied by 0.99). If the click lies outside the + area, this function returns -1.0. - 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 + 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 + 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. + \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. + You may pass 0 as \a details to indicate that you are not interested in those + selection details. \see selectEvent, deselectEvent, QCustomPlot::setInteractions */ @@ -1036,19 +1267,26 @@ double QCPLayerable::selectTest( const QPointF& pos, bool onlySelectable, QVaria /*! \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 + 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 + 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 + 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 + 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 ) @@ -1068,11 +1306,14 @@ void QCPLayerable::initializeParentPlot( QCustomPlot* parentPlot ) /*! \internal - Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not + 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 + 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 @@ -1084,8 +1325,10 @@ void QCPLayerable::setParentLayerable( QCPLayerable* 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 + 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. @@ -1099,7 +1342,8 @@ bool QCPLayerable::moveToLayer( QCPLayer* layer, bool prepend ) } if( layer && layer->parentPlot() != mParentPlot ) { - qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + qDebug() << Q_FUNC_INFO << "layer" << layer->name() + << "is not in same QCustomPlot as this layerable"; return false; } @@ -1116,9 +1360,12 @@ bool QCPLayerable::moveToLayer( QCPLayer* layer, bool prepend ) /*! \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 + 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, @@ -1135,14 +1382,20 @@ void QCPLayerable::applyAntialiasingHint( QCPPainter* painter, /*! \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 + 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 + 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. @@ -1156,11 +1409,14 @@ void QCPLayerable::parentPlotInitialized( QCustomPlot* 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 + 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 + 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 @@ -1172,11 +1428,14 @@ QCP::Interaction QCPLayerable::selectionCategory() const /*! \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 + 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 + The returned clipping rect is set on the painter before the draw function of + the respective object is called. */ QRect QCPLayerable::clipRect() const @@ -1189,28 +1448,43 @@ QRect QCPLayerable::clipRect() const /*! \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 + 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 + \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 + 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 + 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 + \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 @@ -1228,12 +1502,16 @@ void QCPLayerable::selectEvent( QMouseEvent* event, /*! \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 + 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, + 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 @@ -1249,25 +1527,31 @@ void QCPLayerable::deselectEvent( bool* selectionStateChanged ) /*! \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 + 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, + 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, + 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 + Since the number of planck-volumes in the entire visible universe is only + ~1e183, this should be enough. \see validRange, minRange */ @@ -1305,7 +1589,8 @@ double QCPRange::center() const } /*! - Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values + Makes sure \a lower is numerically smaller than \a upper. If this is not the + case, the values are swapped. */ void QCPRange::normalize() @@ -1315,10 +1600,12 @@ void QCPRange::normalize() } /*! - Expands this range such that \a otherRange is contained in the new range. It is assumed that both + 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. + If \a otherRange is already inside the current range, this function does + nothing. \see expanded */ @@ -1331,7 +1618,8 @@ void QCPRange::expand( const QCPRange& otherRange ) } /*! - Returns an expanded range that contains this and \a otherRange. It is assumed that both this + 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 @@ -1344,15 +1632,22 @@ QCPRange QCPRange::expanded( const QCPRange& otherRange ) const } /*! - 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 + 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 + 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 @@ -1360,8 +1655,10 @@ 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)) + // 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 @@ -1380,7 +1677,8 @@ QCPRange QCPRange::sanitizedForLogScale() const } 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 + // 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 @@ -1398,12 +1696,14 @@ QCPRange QCPRange::sanitizedForLogScale() const sanitizedRange.lower = sanitizedRange.upper * rangeFac; } } - // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper0 && upper<0 should never occur, because + // that implies upper minRange) && (range.upper < -minRange || range.upper > minRange)); */ - return ( range.lower > -maxRange && range.upper < maxRange && qAbs( range.lower - range.upper ) > minRange && + return ( range.lower > -maxRange && range.upper < maxRange && + qAbs( range.lower - range.upper ) > minRange && qAbs( range.lower - range.upper ) < maxRange ); } /*! \page thelayoutsystem The Layout System - The layout system is responsible for positioning and scaling layout elements such as axis rects, + The layout system is responsible for positioning and scaling layout elements + such as axis rects, legends and plot titles in a QCustomPlot. \section layoutsystem-classesandmechanisms Classes and mechanisms - The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that - take part in the layout system derive from this class, either directly or indirectly. + The layout system is based on the abstract base class \ref QCPLayoutElement. + All objects that + take part in the layout system derive from this class, either directly or + indirectly. - Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own - content. However, it is perfectly possible for a layout element to only serve as a structuring + Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element + may draw its own + content. However, it is perfectly possible for a layout element to only serve + as a structuring and/or positioning element, not drawing anything on its own. \subsection layoutsystem-rects Rects of a layout element - A layout element is a rectangular object described by two rects: the inner rect (\ref - QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect - is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward - from the outer rect. The inner rect is meant for main content while the margin area may either be - left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions - the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels + A layout element is a rectangular object described by two rects: the inner + rect (\ref + QCPLayoutElement::rect) and the outer rect (\ref + QCPLayoutElement::setOuterRect). The inner rect + is calculated automatically by applying the margin (\ref + QCPLayoutElement::setMargins) inward + from the outer rect. The inner rect is meant for main content while the margin + area may either be + left blank or serve for displaying peripheral graphics. For example, \ref + QCPAxisRect positions + the four main axes at the sides of the inner rect, so graphs end up inside it + and the axis labels and tick labels are in the margin area. \subsection layoutsystem-margins Margins - Each layout element may provide a mechanism to automatically determine its margins. Internally, - this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref - QCP::MarginSide and returns an integer value which represents the ideal margin for the specified + Each layout element may provide a mechanism to automatically determine its + margins. Internally, + this is realized with the \ref QCPLayoutElement::calculateAutoMargin function + which takes a \ref + QCP::MarginSide and returns an integer value which represents the ideal margin + for the specified side. The automatic margin will be used on the sides specified in \ref - QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic - margin calculation is enabled for all four sides. In this case, a minimum margin may be set with - \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting - margins smaller than desired for a specific situation. If automatic margin calculation is unset - for a specific side, the margin of that side can be controlled directy via \ref + QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll + meaning automatic + margin calculation is enabled for all four sides. In this case, a minimum + margin may be set with + \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin + mechanism from setting + margins smaller than desired for a specific situation. If automatic margin + calculation is unset + for a specific side, the margin of that side can be controlled directy via + \ref QCPLayoutElement::setMargins. - If multiple layout ements are arranged next to or beneath each other, it may be desirable to - align their inner rects on certain sides. Since they all might have different automatic margins, + If multiple layout ements are arranged next to or beneath each other, it may + be desirable to + align their inner rects on certain sides. Since they all might have different + automatic margins, this usually isn't the case. The class \ref QCPMarginGroup and \ref - QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the + QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple + margins. See the documentation there for details. \subsection layoutsystem-layout Layouts - As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in - princple can have the only purpose to manage/arrange those child elements. This is what the - subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual - representation. It defines an interface to add, remove and manage child layout elements. - QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive - from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset + As mentioned, a QCPLayoutElement may have an arbitrary number of child layout + elements and in + princple can have the only purpose to manage/arrange those child elements. + This is what the + subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but + has no visual + representation. It defines an interface to add, remove and manage child layout + elements. + QCPLayout isn't a usable layout though, it's an abstract base class that + concrete layouts derive + from, like \ref QCPLayoutGrid which arranges its child elements in a grid and + \ref QCPLayoutInset which allows placing child elements freely inside its rect. - Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way, + Since a QCPLayout is a layout element itself, it may be placed inside other + layouts. This way, complex hierarchies may be created, offering very flexible arrangements. \image html LayoutsystemSketch.png - Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. - It shows how two child layout elements are placed inside the grid layout next to each other in + Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref + QCustomPlot::plotLayout. + It shows how two child layout elements are placed inside the grid layout next + to each other in cells (0, 0) and (0, 1). \subsection layoutsystem-plotlayout The top level plot layout - Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref - QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout - elements in the QCustomPlot. By default, this top level grid layout contains a single cell which + Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is + accessible via \ref + QCustomPlot::plotLayout and contains (directly or indirectly via other + sub-layouts) all layout + elements in the QCustomPlot. By default, this top level grid layout contains a + single cell which holds the main axis rect. \subsection layoutsystem-examples Examples - Adding a plot title is a typical and simple case to demonstrate basic workings of the layout system. + Adding a plot title is a typical and simple case to demonstrate basic + workings of the layout system. \code // first we create and prepare a plot title layout element: QCPPlotTitle *title = new QCPPlotTitle(customPlot); title->setText("Plot Title Example"); title->setFont(QFont("sans", 12, QFont::Bold)); // then we add it to the main plot layout: - customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect - customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created + customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis + rect + customPlot->plotLayout()->addElement(0, 0, title); // place the title in the + empty cell we've just created \endcode \image html layoutsystem-addingplottitle.png - Arranging multiple axis rects actually is the central purpose of the layout system. + Arranging multiple axis rects actually is the central purpose of the + layout system. \code - customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect + customPlot->plotLayout()->clear(); // let's start from scratch and remove the + default axis rect // add the first axis rect in second row (row index 1): QCPAxisRect *topAxisRect = new QCPAxisRect(customPlot); customPlot->plotLayout()->addElement(1, 0, topAxisRect); @@ -1562,13 +1902,17 @@ bool QCPRange::validRange( const QCPRange& range ) QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot); subLayout->addElement(0, 0, leftAxisRect); subLayout->addElement(0, 1, rightAxisRect); - subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width + subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of + width subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40) - // since we've created the axis rects and axes from scratch, we need to place them on + // since we've created the axis rects and axes from scratch, we need to place + them on // according layers, if we don't want the grid to be drawn above the axes etc. - // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes": + // place the axis on "axes" layer and grids on the "grid" layer, which is + below "axes": QList allAxes; - allAxes << topAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes(); + allAxes << topAxisRect->axes() << leftAxisRect->axes() << + rightAxisRect->axes(); foreach (QCPAxis *axis, allAxes) { axis->setLayer("axes"); @@ -1584,24 +1928,34 @@ bool QCPRange::validRange( const QCPRange& range ) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPMarginGroup - \brief A margin group allows synchronization of margin sides if working with multiple layout elements. + \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. + 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 + 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 + 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 @@ -1615,15 +1969,18 @@ bool QCPRange::validRange( const QCPRange& range ) customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group); customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group); \endcode - Here, we've used the first two axis rects of the plot and synchronized their left margins with + 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 +/*! \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 + Returns a list of all layout elements that have their margin \a side + associated with this margin group. */ @@ -1632,7 +1989,8 @@ bool QCPRange::validRange( const QCPRange& range ) /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ -QCPMarginGroup::QCPMarginGroup( QCustomPlot* parentPlot ) : QObject( parentPlot ), mParentPlot( parentPlot ) +QCPMarginGroup::QCPMarginGroup( QCustomPlot* parentPlot ) + : QObject( parentPlot ), mParentPlot( parentPlot ) { mChildren.insert( QCP::msLeft, QList() ); mChildren.insert( QCP::msRight, QList() ); @@ -1646,12 +2004,13 @@ QCPMarginGroup::~QCPMarginGroup() } /*! - Returns whether this margin group is empty. If this function returns true, no layout elements use + 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 ); + QHashIterator> it( mChildren ); while( it.hasNext() ) { it.next(); @@ -1662,35 +2021,41 @@ bool QCPMarginGroup::isEmpty() const } /*! - Clears this margin group. The synchronization of the margin sides that use this margin group is + 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 ); + 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 + 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 + 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 + 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: + // 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; i < elements.size(); ++i ) @@ -1707,7 +2072,8 @@ int QCPMarginGroup::commonMargin( QCP::MarginSide side ) const /*! \internal - Adds \a element to the internal list of child elements, for the margin \a side. + 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. */ @@ -1722,7 +2088,8 @@ void QCPMarginGroup::addChild( QCP::MarginSide side, QCPLayoutElement* element ) /*! \internal - Removes \a element from the internal list of child elements, for the margin \a side. + 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. */ @@ -1738,28 +2105,45 @@ void QCPMarginGroup::removeChild( QCP::MarginSide side, QCPLayoutElement* elemen //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutElement - \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". + \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. + 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). + 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 + 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 + 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. */ @@ -1772,43 +2156,55 @@ void QCPMarginGroup::removeChild( QCP::MarginSide side, QCPLayoutElement* elemen /*! \fn QRect QCPLayoutElement::rect() const - Returns the inner rect of this layout element. The inner rect is the outer rect (\ref + 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. + 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 + 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. + 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 + 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 + 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 + This event is called, if the mouse wheel is scrolled while the cursor is + inside the rect of this layout element. */ @@ -1818,16 +2214,18 @@ void QCPMarginGroup::removeChild( QCP::MarginSide side, QCPLayoutElement* elemen 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 ) + : 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 ) { } @@ -1835,19 +2233,24 @@ 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 + 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 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 + 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. + The layout element will adapt its inner \ref rect by applying the margins + inward to the outer rect. \see rect */ @@ -1856,17 +2259,22 @@ void QCPLayoutElement::setOuterRect( const QRect& rect ) if( mOuterRect != rect ) { mOuterRect = rect; - mRect = mOuterRect.adjusted( mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom() ); + 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 + 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 + 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 @@ -1876,15 +2284,18 @@ void QCPLayoutElement::setMargins( const QMargins& margins ) if( mMargins != margins ) { mMargins = margins; - mRect = mOuterRect.adjusted( mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom() ); + 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 + 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 + The minimum values are not enforced on margin sides that were set to be under + manual control via \ref setAutoMargins. \see setAutoMargins @@ -1898,12 +2309,17 @@ void QCPLayoutElement::setMinimumMargins( const QMargins& 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. + 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. + 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 */ @@ -1913,12 +2329,17 @@ void QCPLayoutElement::setAutoMargins( QCP::MarginSides 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. + 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 + 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 ) @@ -1941,8 +2362,10 @@ void QCPLayoutElement::setMinimumSize( int width, int 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. + 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 ) { @@ -1966,12 +2389,14 @@ void QCPLayoutElement::setMaximumSize( int width, int height ) /*! Sets the margin \a group of the specified margin \a sides. - Margin groups allow synchronizing specified margins across layout elements, see the documentation + 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 + Note that margin groups only work for margin sides that are set to automatic + (\ref setAutoMargins). */ void QCPLayoutElement::setMarginGroup( QCP::MarginSides sides, QCPMarginGroup* group ) @@ -1995,7 +2420,8 @@ void QCPLayoutElement::setMarginGroup( QCP::MarginSides sides, QCPMarginGroup* g if( oldGroup ) // unregister at old group oldGroup->removeChild( side, this ); - if( !group ) // if setting to 0, remove hash entry. Else set hash entry to new group and register there + if( !group ) // if setting to 0, remove hash entry. Else set hash entry to + // new group and register there { mMarginGroups.remove( side ); } @@ -2009,15 +2435,20 @@ void QCPLayoutElement::setMarginGroup( QCP::MarginSides sides, QCPMarginGroup* g } /*! - 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 + 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 + 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. + 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 ) @@ -2026,25 +2457,29 @@ void QCPLayoutElement::update( UpdatePhase phase ) { if( mAutoMargins != QCP::msNone ) { - // set the margins of this layout element according to automatic margin calculation, either directly or via a + // set the margins of this layout element according to automatic margin + // calculation, either directly or via a // margin group: QMargins newMargins = mMargins; - foreach( QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop - << QCP::msBottom ) + foreach( QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight + << QCP::msTop << QCP::msBottom ) { 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 + 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 + 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 ) ) + if( QCP::getMarginValue( newMargins, side ) < + QCP::getMarginValue( mMinimumMargins, side ) ) QCP::setMarginValue( newMargins, side, QCP::getMarginValue( mMinimumMargins, side ) ); } } @@ -2054,10 +2489,13 @@ void QCPLayoutElement::update( UpdatePhase phase ) } /*! - Returns the minimum size this layout element (the inner \ref rect) may be compressed to. + 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 + 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 @@ -2066,10 +2504,13 @@ QSize QCPLayoutElement::minimumSizeHint() const } /*! - Returns the maximum size this layout element (the inner \ref rect) may be expanded to. + 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 + 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 @@ -2078,10 +2519,12 @@ QSize QCPLayoutElement::maximumSizeHint() const } /*! - Returns a list of all child elements in this layout element. If \a recursive is true, all + 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 + \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 @@ -2091,17 +2534,24 @@ QList QCPLayoutElement::elements( bool recursive ) const } /*! - 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 + 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. + See \ref QCPLayerable::selectTest for a general explanation of this virtual + method. - QCPLayoutElement subclasses may reimplement this method to provide more specific selection test + QCPLayoutElement subclasses may reimplement this method to provide more + specific selection test behaviour. */ -double QCPLayoutElement::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +double QCPLayoutElement::selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details ) const { Q_UNUSED( details ) @@ -2124,7 +2574,8 @@ double QCPLayoutElement::selectTest( const QPointF& pos, bool onlySelectable, QV /*! \internal - propagates the parent plot initialization to all child elements, by calling \ref + propagates the parent plot initialization to all child elements, by calling + \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized( QCustomPlot* parentPlot ) @@ -2138,16 +2589,20 @@ void QCPLayoutElement::parentPlotInitialized( QCustomPlot* 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 + 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 + 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 ) ); + return qMax( QCP::getMarginValue( mMargins, side ), + QCP::getMarginValue( mMinimumMargins, side ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -2157,23 +2612,33 @@ int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) /*! \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 + 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 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 + 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 + 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 + For a general introduction to the layout system, see the dedicated + documentation page \ref thelayoutsystem "The Layout System". */ @@ -2188,10 +2653,13 @@ int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) /*! \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. + 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 + 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 @@ -2203,8 +2671,10 @@ int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) 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. + 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 */ @@ -2215,8 +2685,10 @@ int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) 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. + 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 */ @@ -2224,7 +2696,8 @@ int QCPLayoutElement::calculateAutoMargin( QCP::MarginSide side ) /* end documentation of pure virtual functions */ /*! - Creates an instance of QCPLayout and sets default values. Note that since QCPLayout + 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() @@ -2232,10 +2705,12 @@ QCPLayout::QCPLayout() } /*! - First calls the QCPLayoutElement::update base class implementation to update the margins on this + 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. + Then calls \ref updateLayout which subclasses reimplement to reposition and + resize their cells. Finally, \ref update is called on all child elements. */ @@ -2278,10 +2753,12 @@ QList QCPLayout::elements( bool recursive ) const } /*! - Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the + 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 + Not all layouts need simplification. For example, QCPLayoutInset doesn't use + explicit simplification while QCPLayoutGrid does. */ void QCPLayout::simplify() @@ -2289,10 +2766,12 @@ void QCPLayout::simplify() } /*! - Removes and deletes the element at the provided \a index. Returns true on success. If \a index is + 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 + This function internally uses \ref takeAt to remove the element from the + layout and then deletes the returned element. \see remove, takeAt @@ -2309,10 +2788,12 @@ bool QCPLayout::removeAt( int index ) } /*! - Removes and deletes the provided \a element. Returns true on success. If \a element is not in the + 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 + This function internally uses \ref takeAt to remove the element from the + layout and then deletes the element. \see removeAt, take @@ -2344,11 +2825,15 @@ void QCPLayout::clear() } /*! - Subclasses call this method to report changed (minimum/maximum) size constraints. + 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, + 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 @@ -2361,10 +2846,13 @@ void QCPLayout::sizeConstraintsChanged() const /*! \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. + 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 + 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. @@ -2377,14 +2865,17 @@ void QCPLayout::updateLayout() /*! \internal - Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the + 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 + 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 ) @@ -2403,12 +2894,16 @@ void QCPLayout::adoptElement( QCPLayoutElement* el ) /*! \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 + 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 + 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 ) @@ -2418,7 +2913,8 @@ void QCPLayout::releaseElement( QCPLayoutElement* 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 + // Note: Don't initializeParentPlot(0) here, because layout element will + // stay in same parent plot } else qDebug() << Q_FUNC_INFO << "Null element passed"; @@ -2426,29 +2922,43 @@ void QCPLayout::releaseElement( QCPLayoutElement* el ) /*! \internal - This is a helper function for the implementation of \ref updateLayout in subclasses. + 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. + 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. + 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 + \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 + \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 + \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, + \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. @@ -2460,14 +2970,16 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, { if( maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size() ) { - qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; + 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): + // if provided total size is forced smaller than total minimum size, ignore + // minimum sizes (squeeze sections): int minSizeSum = 0; for( int i = 0; i < sectionCount; ++i ) minSizeSum += minSizes.at( i ); @@ -2489,14 +3001,16 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, int outerIterations = 0; while( !unfinishedSections.isEmpty() && - outerIterations < - sectionCount * 2 ) // the iteration check ist just a failsafe in case something really strange happens + outerIterations < sectionCount * 2 ) // the iteration check ist just a + // failsafe in case something + // really strange happens { ++outerIterations; int innerIterations = 0; while( !unfinishedSections.isEmpty() && - innerIterations < - sectionCount * 2 ) // the iteration check ist just a failsafe in case something really strange happens + innerIterations < sectionCount * 2 ) // the iteration check ist just a + // failsafe in case something + // really strange happens { ++innerIterations; // find section that hits its maximum next: @@ -2505,22 +3019,26 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, for( int i = 0; i < unfinishedSections.size(); ++i ) { int secId = unfinishedSections.at( i ); - double hitsMaxAt = ( maxSizes.at( secId ) - sectionSizes.at( secId ) ) / stretchFactors.at( secId ); + double hitsMaxAt = + ( maxSizes.at( secId ) - sectionSizes.at( secId ) ) / stretchFactors.at( secId ); if( hitsMaxAt < nextMax ) { nextMax = hitsMaxAt; nextId = secId; } } - // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining + // check if that maximum is actually within the bounds of the total size + // (i.e. can we stretch all remaining // sections so far that the found section - // actually hits its maximum, without exceeding the total size when we add up all sections) + // actually hits its maximum, without exceeding the total size when we add + // up all sections) double stretchFactorSum = 0; for( int i = 0; i < unfinishedSections.size(); ++i ) stretchFactorSum += stretchFactors.at( unfinishedSections.at( i ) ); double nextMaxLimit = freeSize / stretchFactorSum; - if( nextMax < - nextMaxLimit ) // next maximum is actually hit, move forward to that point and fix the size of that section + if( nextMax < nextMaxLimit ) // next maximum is actually hit, move forward + // to that point and fix the size of that + // section { for( int i = 0; i < unfinishedSections.size(); ++i ) { @@ -2528,22 +3046,26 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, nextMax * stretchFactors.at( unfinishedSections.at( i ) ); // increment all sections freeSize -= nextMax * stretchFactors.at( unfinishedSections.at( i ) ); } - unfinishedSections.removeOne( nextId ); // exclude the section that is now at maximum from further changes + unfinishedSections.removeOne( nextId ); // exclude the section that is now + // at maximum from further changes } - else // next maximum isn't hit, just distribute rest of free space on remaining sections + else // next maximum isn't hit, just distribute rest of free space on + // remaining sections { for( int i = 0; i < unfinishedSections.size(); ++i ) sectionSizes[unfinishedSections.at( i )] += - nextMaxLimit * stretchFactors.at( unfinishedSections.at( i ) ); // increment all sections + nextMaxLimit * + stretchFactors.at( unfinishedSections.at( i ) ); // increment all sections unfinishedSections.clear(); } } if( innerIterations == sectionCount * 2 ) - qDebug() << Q_FUNC_INFO - << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes - << minSizes << stretchFactors << totalSize; + qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration " + "count, layouting aborted. Input was:" + << maxSizes << minSizes << stretchFactors << totalSize; - // now check whether the resulting section sizes violate minimum restrictions: + // now check whether the resulting section sizes violate minimum + // restrictions: bool foundMinimumViolation = false; for( int i = 0; i < sectionSizes.size(); ++i ) { @@ -2561,22 +3083,25 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, freeSize = totalSize; for( int i = 0; i < sectionCount; ++i ) { - if( !minimumLockedSections.contains( - i ) ) // only put sections that haven't hit their minimum back into the pool + if( !minimumLockedSections.contains( i ) ) // only put sections that + // haven't hit their minimum + // back into the pool unfinishedSections.append( i ); else - freeSize -= - sectionSizes.at( i ); // remove size of minimum locked sections from available space in next round + freeSize -= sectionSizes.at( i ); // remove size of minimum locked + // sections from available space in + // next round } - // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum): + // reset all section sizes to zero that are in unfinished sections (all + // others have been set to their minimum): for( int i = 0; i < unfinishedSections.size(); ++i ) sectionSizes[unfinishedSections.at( i )] = 0; } } if( outerIterations == sectionCount * 2 ) - qDebug() << Q_FUNC_INFO - << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes - << stretchFactors << totalSize; + qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration " + "count, layouting aborted. Input was:" + << maxSizes << minSizes << stretchFactors << totalSize; QVector result( sectionCount ); for( int i = 0; i < sectionCount; ++i ) @@ -2591,17 +3116,25 @@ QVector QCPLayout::getSectionSizes( QVector maxSizes, /*! \class QCPLayoutGrid \brief A layout that arranges child elements in a grid - Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor, - \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing). + Elements are laid out in a grid with configurable stretch factors (\ref + setColumnStretchFactor, + \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref + setRowSpacing). - Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or - column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref - hasElement, that element can be retrieved with \ref element. If rows and columns that only have - empty cells shall be removed, call \ref simplify. Removal of elements is either done by just - adding the element to a different layout or by using the QCPLayout interface \ref take or \ref + Elements can be added to cells via \ref addElement. The grid is expanded if + the specified row or + column doesn't exist yet. Whether a cell contains a valid layout element can + be checked with \ref + hasElement, that element can be retrieved with \ref element. If rows and + columns that only have + empty cells shall be removed, call \ref simplify. Removal of elements is + either done by just + adding the element to a different layout or by using the QCPLayout interface + \ref take or \ref remove. - Row and column insertion can be performed with \ref insertRow and \ref insertColumn. + Row and column insertion can be performed with \ref insertRow and \ref + insertColumn. */ /*! @@ -2613,16 +3146,20 @@ QCPLayoutGrid::QCPLayoutGrid() : mColumnSpacing( 5 ), mRowSpacing( 5 ) QCPLayoutGrid::~QCPLayoutGrid() { - // 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 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 element in the cell in \a row and \a column. - Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug - message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. + Returns 0 if either the row/column is invalid or if the cell is empty. In + those cases, a qDebug + message is printed. To check whether a cell exists and isn't empty, use \ref + hasElement. \see addElement, hasElement */ @@ -2669,11 +3206,14 @@ int QCPLayoutGrid::columnCount() const } /*! - 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 + 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 + 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 @@ -2692,7 +3232,8 @@ bool QCPLayoutGrid::addElement( int row, int column, QCPLayoutElement* element ) return true; } else - qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; + 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; @@ -2700,7 +3241,8 @@ bool QCPLayoutGrid::addElement( int row, int column, QCPLayoutElement* element ) } /*! - Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't + Returns whether the cell at \a row and \a column exists and contains a valid + element, i.e. isn't empty. \see element @@ -2716,8 +3258,10 @@ bool QCPLayoutGrid::hasElement( int row, int column ) /*! 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 + 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. @@ -2738,10 +3282,13 @@ void QCPLayoutGrid::setColumnStretchFactor( int column, double factor ) } /*! - Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. + 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 + 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. @@ -2757,7 +3304,8 @@ void QCPLayoutGrid::setColumnStretchFactors( const QList& factors ) { if( mColumnStretchFactors.at( i ) <= 0 ) { - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at( i ); + qDebug() << Q_FUNC_INFO + << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at( i ); mColumnStretchFactors[i] = 1; } } @@ -2769,8 +3317,10 @@ void QCPLayoutGrid::setColumnStretchFactors( const QList& factors ) /*! Sets the stretch \a factor of \a row. - 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 + 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. @@ -2791,10 +3341,13 @@ void QCPLayoutGrid::setRowStretchFactor( int row, double factor ) } /*! - Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. + 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 + 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. @@ -2810,7 +3363,8 @@ void QCPLayoutGrid::setRowStretchFactors( const QList& factors ) { if( mRowStretchFactors.at( i ) <= 0 ) { - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at( i ); + qDebug() << Q_FUNC_INFO + << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at( i ); mRowStretchFactors[i] = 1; } } @@ -2840,15 +3394,19 @@ void QCPLayoutGrid::setRowSpacing( int pixels ) } /*! - Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid - row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1. + Expands the layout to have \a newRowCount rows and \a newColumnCount columns. + So the last valid + row index will be \a newRowCount-1, the last valid column index will be \a + newColumnCount-1. - If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount, + If the current column/row count is already larger or equal to \a + newColumnCount/\a newRowCount, this function does nothing in that dimension. Newly created cells are empty, new rows and columns have the stretch factor 1. - Note that upon a call to \ref addElement, the layout is expanded automatically to contain the + Note that upon a call to \ref addElement, the layout is expanded automatically + to contain the specified row and column, using this function. \see simplify @@ -2873,14 +3431,17 @@ void QCPLayoutGrid::expandTo( int newRowCount, int newColumnCount ) } /*! - Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex - range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom). + Inserts a new row with empty cells at the row index \a newIndex. Valid values + for \a newIndex + range from 0 (inserts a row at the top) to \a rowCount (appends a row at the + bottom). \see insertColumn */ void QCPLayoutGrid::insertRow( int newIndex ) { - if( mElements.isEmpty() || mElements.first().isEmpty() ) // if grid is completely empty, add first cell + if( mElements.isEmpty() || + mElements.first().isEmpty() ) // if grid is completely empty, add first cell { expandTo( 1, 1 ); return; @@ -2899,14 +3460,17 @@ void QCPLayoutGrid::insertRow( int newIndex ) } /*! - Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a - newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right). + Inserts a new column with empty cells at the column index \a newIndex. Valid + values for \a + newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a + row at the right). \see insertRow */ void QCPLayoutGrid::insertColumn( int newIndex ) { - if( mElements.isEmpty() || mElements.first().isEmpty() ) // if grid is completely empty, add first cell + if( mElements.isEmpty() || + mElements.first().isEmpty() ) // if grid is completely empty, add first cell { expandTo( 1, 1 ); return; @@ -2932,9 +3496,11 @@ void QCPLayoutGrid::updateLayout() int totalRowSpacing = ( rowCount() - 1 ) * mRowSpacing; int totalColSpacing = ( columnCount() - 1 ) * mColumnSpacing; QVector colWidths = - getSectionSizes( maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width() - totalColSpacing ); + getSectionSizes( maxColWidths, minColWidths, mColumnStretchFactors.toVector(), + mRect.width() - totalColSpacing ); QVector rowHeights = - getSectionSizes( maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height() - totalRowSpacing ); + getSectionSizes( maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), + mRect.height() - totalRowSpacing ); // go through cells and set rects accordingly: int yOffset = mRect.top(); @@ -3034,7 +3600,8 @@ QList QCPLayoutGrid::elements( bool recursive ) const } /*! - Simplifies the layout by collapsing rows and columns which only contain empty cells. + Simplifies the layout by collapsing rows and columns which only contain empty + cells. */ void QCPLayoutGrid::simplify() { @@ -3054,7 +3621,8 @@ void QCPLayoutGrid::simplify() { mRowStretchFactors.removeAt( row ); mElements.removeAt( row ); - if( mElements.isEmpty() ) // removed last element, also remove stretch factor (wouldn't happen below because also + if( mElements.isEmpty() ) // removed last element, also remove stretch + // factor (wouldn't happen below because also // columnCount changed to 0 now) mColumnStretchFactors.clear(); } @@ -3091,7 +3659,8 @@ QSize QCPLayoutGrid::minimumSizeHint() const result.rwidth() += minColWidths.at( i ); for( int i = 0; i < minRowHeights.size(); ++i ) result.rheight() += minRowHeights.at( i ); - result.rwidth() += qMax( 0, columnCount() - 1 ) * mColumnSpacing + mMargins.left() + mMargins.right(); + result.rwidth() += + qMax( 0, columnCount() - 1 ) * mColumnSpacing + mMargins.left() + mMargins.right(); result.rheight() += qMax( 0, rowCount() - 1 ) * mRowSpacing + mMargins.top() + mMargins.bottom(); return result; } @@ -3107,24 +3676,28 @@ QSize QCPLayoutGrid::maximumSizeHint() const result.setWidth( qMin( result.width() + maxColWidths.at( i ), QWIDGETSIZE_MAX ) ); for( int i = 0; i < maxRowHeights.size(); ++i ) result.setHeight( qMin( result.height() + maxRowHeights.at( i ), QWIDGETSIZE_MAX ) ); - result.rwidth() += qMax( 0, columnCount() - 1 ) * mColumnSpacing + mMargins.left() + mMargins.right(); + result.rwidth() += + qMax( 0, columnCount() - 1 ) * mColumnSpacing + mMargins.left() + mMargins.right(); result.rheight() += qMax( 0, rowCount() - 1 ) * mRowSpacing + mMargins.top() + mMargins.bottom(); return result; } /*! \internal - Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights + Places the minimum column widths and row heights into \a minColWidths and \a + minRowHeights respectively. - The minimum height of a row is the largest minimum height of any element in that row. The minimum + The minimum height of a row is the largest minimum height of any element in + that row. The minimum width of a column is the largest minimum width of any element in that column. This is a helper function for \ref updateLayout. \see getMaximumRowColSizes */ -void QCPLayoutGrid::getMinimumRowColSizes( QVector* minColWidths, QVector* minRowHeights ) const +void QCPLayoutGrid::getMinimumRowColSizes( QVector* minColWidths, + QVector* minRowHeights ) const { *minColWidths = QVector( columnCount(), 0 ); *minRowHeights = QVector( rowCount(), 0 ); @@ -3149,17 +3722,21 @@ void QCPLayoutGrid::getMinimumRowColSizes( QVector* minColWidths, QVector* maxColWidths, QVector* maxRowHeights ) const +void QCPLayoutGrid::getMaximumRowColSizes( QVector* maxColWidths, + QVector* maxRowHeights ) const { *maxColWidths = QVector( columnCount(), QWIDGETSIZE_MAX ); *maxRowHeights = QVector( rowCount(), QWIDGETSIZE_MAX ); @@ -3186,28 +3763,38 @@ void QCPLayoutGrid::getMaximumRowColSizes( QVector* maxColWidths, QVectorminimumSizeHint(); 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() ); + 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() ); @@ -3342,7 +3945,8 @@ void QCPLayoutInset::updateLayout() { 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() ); + 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() ) @@ -3430,15 +4034,22 @@ bool QCPLayoutInset::take( QCPLayoutElement* element ) } /*! - The inset layout is sensitive to events only at areas where its (visible) child elements are - sensitive. If the selectTest method of any of the child elements returns a positive number for \a - pos, this method returns a value corresponding to 0.99 times the parent plot's selection - tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true, + The inset layout is sensitive to events only at areas where its (visible) + child elements are + sensitive. If the selectTest method of any of the child elements returns a + positive number for \a + pos, this method returns a value corresponding to 0.99 times the parent plot's + selection + tolerance. The inset layout is not selectable itself by default. So if \a + onlySelectable is true, -1.0 is returned. - See \ref QCPLayerable::selectTest for a general explanation of this virtual method. + See \ref QCPLayerable::selectTest for a general explanation of this virtual + method. */ -double QCPLayoutInset::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +double QCPLayoutInset::selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details ) const { Q_UNUSED( details ) if( onlySelectable ) @@ -3446,21 +4057,27 @@ double QCPLayoutInset::selectTest( const QPointF& pos, bool onlySelectable, QVar for( int i = 0; i < mElements.size(); ++i ) { - // inset layout shall only return positive selectTest, if actually an inset object is at pos + // inset layout shall only return positive selectTest, if actually an inset + // object is at pos // else it would block the entire underlying QCPAxisRect with its surface. - if( mElements.at( i )->realVisibility() && mElements.at( i )->selectTest( pos, onlySelectable ) >= 0 ) + if( mElements.at( i )->realVisibility() && + 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 + 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 + \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) @@ -3482,12 +4099,16 @@ void QCPLayoutInset::addElement( QCPLayoutElement* element, Qt::Alignment alignm } /*! - 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 + 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 + \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) @@ -3517,18 +4138,27 @@ void QCPLayoutInset::addElement( QCPLayoutElement* element, const QRectF& rect ) \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. + 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 + 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. \code + Note that due to the overloaded QCPLineEnding constructor, you may directly + specify a + QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. + \code myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode */ @@ -3542,7 +4172,10 @@ QCPLineEnding::QCPLineEnding() : mStyle( esNone ), mWidth( 8 ), mLength( 10 ), m /*! Creates a QCPLineEnding instance with the specified values. */ -QCPLineEnding::QCPLineEnding( QCPLineEnding::EndingStyle style, double width, double length, bool inverted ) +QCPLineEnding::QCPLineEnding( QCPLineEnding::EndingStyle style, + double width, + double length, + bool inverted ) : mStyle( style ), mWidth( width ), mLength( length ), mInverted( inverted ) { } @@ -3556,7 +4189,8 @@ void QCPLineEnding::setStyle( QCPLineEnding::EndingStyle style ) } /*! - Sets the width of the ending decoration, if the style supports it. On arrows, for example, the + 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 @@ -3567,7 +4201,8 @@ void QCPLineEnding::setWidth( double width ) } /*! - Sets the length of the ending decoration, if the style supports it. On arrows, for example, the + 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 @@ -3578,12 +4213,16 @@ void QCPLineEnding::setLength( double length ) } /*! - Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point + 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. + 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 ) { @@ -3592,11 +4231,15 @@ void QCPLineEnding::setInverted( bool 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). + 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 + 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 @@ -3623,14 +4266,19 @@ double QCPLineEnding::boundingDistance() const } /*! - Starting from the origin of this line ending (which is style specific), returns the length + 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). + 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 + This function is used for precise, style specific placement of line endings, + for example in QCPAxes. */ double QCPLineEnding::realLength() const @@ -3660,7 +4308,8 @@ double QCPLineEnding::realLength() const /*! \internal - Draws the line ending with the specified \a painter at the position \a pos. The direction of the + 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 @@ -3698,7 +4347,8 @@ void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, const QVect case esSpikeArrow: { QPointF points[4] = {pos.toPointF(), ( pos - lengthVec + widthVec ).toPointF(), - ( pos - lengthVec * 0.8f ).toPointF(), ( pos - lengthVec - widthVec ).toPointF()}; + ( pos - lengthVec * 0.8f ).toPointF(), + ( pos - lengthVec - widthVec ).toPointF()}; painter->setPen( miterPen ); painter->setBrush( brush ); painter->drawConvexPolygon( points, 4 ); @@ -3725,8 +4375,10 @@ void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, const QVect 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()}; + 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 ); @@ -3758,23 +4410,28 @@ void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, const QVect } case esSkewedBar: { - if( qFuzzyIsNull( painter->pen().widthF() ) && !painter->modes().testFlag( QCPPainter::pmNonCosmetic ) ) + 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 + // 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() ); + 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 + // 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() ); + 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; } @@ -3784,7 +4441,8 @@ void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, const QVect /*! \internal \overload - Draws the line ending. The direction is controlled with the \a angle parameter in radians. + 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 { @@ -3798,25 +4456,33 @@ void QCPLineEnding::draw( QCPPainter* painter, const QVector2D& pos, double angl /*! \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. + 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 + 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. + You shouldn't instantiate grids on their own, since every QCPAxis brings its + own QCPGrid. */ QCPGrid::QCPGrid( QCPAxis* parentAxis ) : QCPLayerable( parentAxis->parentPlot(), "", parentAxis ), mParentAxis( parentAxis ) { - // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + // 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 ) ); @@ -3872,8 +4538,10 @@ void QCPGrid::setSubGridPen( const QPen& 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. + 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 ) { @@ -3882,12 +4550,15 @@ void QCPGrid::setZeroLinePen( const QPen& pen ) /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 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 + 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. @@ -3900,8 +4571,10 @@ void QCPGrid::applyDefaultAntialiasingHint( QCPPainter* painter ) const /*! \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). + 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 ) { @@ -3937,7 +4610,8 @@ void QCPGrid::drawGridLines( QCPPainter* painter ) const { // draw zeroline: int zeroLineIndex = -1; - if( mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0 ) + if( mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && + mParentAxis->mRange.upper > 0 ) { applyAntialiasingHint( painter, mAntialiasedZeroLine, QCP::aeZeroLine ); painter->setPen( mZeroLinePen ); @@ -3948,7 +4622,8 @@ void QCPGrid::drawGridLines( QCPPainter* painter ) const { zeroLineIndex = i; t = mParentAxis->coordToPixel( mParentAxis->mTickVector.at( i ) ); // x - painter->drawLine( QLineF( t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top() ) ); + painter->drawLine( + QLineF( t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top() ) ); break; } } @@ -3961,14 +4636,16 @@ void QCPGrid::drawGridLines( QCPPainter* painter ) const 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() ) ); + 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 ) + if( mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && + mParentAxis->mRange.upper > 0 ) { applyAntialiasingHint( painter, mAntialiasedZeroLine, QCP::aeZeroLine ); painter->setPen( mZeroLinePen ); @@ -3979,7 +4656,8 @@ void QCPGrid::drawGridLines( QCPPainter* painter ) const { zeroLineIndex = i; t = mParentAxis->coordToPixel( mParentAxis->mTickVector.at( i ) ); // y - painter->drawLine( QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); + painter->drawLine( + QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); break; } } @@ -3992,7 +4670,8 @@ void QCPGrid::drawGridLines( QCPPainter* painter ) const 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 ) ); + painter->drawLine( + QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); } } } @@ -4019,7 +4698,8 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const for( int i = 0; i < mParentAxis->mSubTickVector.size(); ++i ) { t = mParentAxis->coordToPixel( mParentAxis->mSubTickVector.at( i ) ); // x - painter->drawLine( QLineF( t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top() ) ); + painter->drawLine( + QLineF( t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top() ) ); } } else @@ -4027,7 +4707,8 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const for( int i = 0; i < mParentAxis->mSubTickVector.size(); ++i ) { t = mParentAxis->coordToPixel( mParentAxis->mSubTickVector.at( i ) ); // y - painter->drawLine( QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); + painter->drawLine( + QLineF( mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t ) ); } } } @@ -4039,8 +4720,10 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const /*! \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 + 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. @@ -4049,7 +4732,8 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const \n \image html AxisRectSpacingOverview.png -

    Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line +
    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.
    */ @@ -4058,7 +4742,8 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const /*! \fn Qt::Orientation QCPAxis::orientation() const - Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced + 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) @@ -4066,7 +4751,8 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const /*! \fn QCPGrid *QCPAxis::grid() const - Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the + Returns the \ref QCPGrid instance belonging to this axis. Access it to set + details about the way the grid is displayed. */ @@ -4082,47 +4768,60 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const /*! \fn void QCPAxis::ticksRequest() - This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick + 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 + 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 + 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 + 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. */ -/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) +/*! \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 + 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 + 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 + 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 + This signal is emitted when the selectability changes, by calls to \ref + setSelectableParts */ /* end of documentation of signals */ @@ -4132,64 +4831,72 @@ void QCPGrid::drawSubGridLines( QCPPainter* painter ) const You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis( QCPAxisRect* parent, AxisType type ) - : QCPLayerable( parent->parentPlot(), "", 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( "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 ) + : QCPLayerable( parent->parentPlot(), "", 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( "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 ) { mGrid->setVisible( false ); setAntialiased( false ); - setLayer( mParentPlot->currentLayer() ); // it's actually on that layer already, but we want it in front of the grid, + 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 ) @@ -4294,16 +5001,24 @@ QCPLineEnding QCPAxis::upperEnding() const } /*! - 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 + 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 + 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 ) @@ -4319,10 +5034,13 @@ void QCPAxis::setScaleType( QCPAxis::ScaleType type ) } /*! - 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. + 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 + 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 ) @@ -4340,7 +5058,8 @@ void QCPAxis::setScaleLogBase( double base ) /*! Sets the range of the axis. - This slot may be connected with the \ref rangeChanged signal of another axis so this 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. @@ -4367,11 +5086,14 @@ void QCPAxis::setRange( const QCPRange& range ) } /*! - Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + 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 + 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 @@ -4386,19 +5108,25 @@ void QCPAxis::setSelectableParts( const SelectableParts& selectable ) } /*! - Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part + 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 + 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. + 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. + 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 + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, + setSelectedTickPen, setSelectedSubTickPen, + setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, + setSelectedLabelColor */ void QCPAxis::setSelectedParts( const SelectableParts& selected ) { @@ -4446,10 +5174,14 @@ void QCPAxis::setRange( double lower, double upper ) 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 + 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 ) @@ -4511,12 +5243,16 @@ void QCPAxis::setRangeUpper( double upper ) } /*! - 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 + 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 + 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 ) @@ -4529,16 +5265,23 @@ void QCPAxis::setRangeReversed( bool reversed ) } /*! - 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). + 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 + 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 + 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 @@ -4553,10 +5296,12 @@ void QCPAxis::setAutoTicks( bool on ) } /*! - When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be + 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 + 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. @@ -4578,16 +5323,23 @@ void QCPAxis::setAutoTickCount( int 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. + 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" + 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 + 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 @@ -4602,14 +5354,18 @@ void QCPAxis::setAutoTickLabels( bool on ) } /*! - 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 + 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 + 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. + If \a on is set to false, you may set the tick step manually with \ref + setTickStep. \see setAutoTicks, setAutoSubTicks, setAutoTickCount */ @@ -4623,11 +5379,14 @@ void QCPAxis::setAutoTickStep( bool on ) } /*! - 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 + 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. + When \a on is set to false, you may set the sub tick count with \ref + setSubTickCount manually. \see setAutoTickCount, setAutoTicks, setAutoTickStep */ @@ -4643,7 +5402,8 @@ void QCPAxis::setAutoSubTicks( bool on ) /*! Sets whether tick marks are displayed. - Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve + 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 ) @@ -4656,7 +5416,8 @@ void QCPAxis::setTicks( bool show ) } /*! - Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. + Sets whether tick labels are displayed. Tick labels are the numbers drawn next + to tick marks. */ void QCPAxis::setTickLabels( bool show ) { @@ -4668,7 +5429,8 @@ void QCPAxis::setTickLabels( bool show ) } /*! - Sets the distance between the axis base line (including any outward ticks) and the tick labels. + Sets the distance between the axis base line (including any outward ticks) and + the tick labels. \see setLabelPadding, setPadding */ void QCPAxis::setTickLabelPadding( int padding ) @@ -4683,21 +5445,32 @@ void QCPAxis::setTickLabelPadding( int padding ) /*! 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 ltNumber, the format specifications of \ref + setNumberFormat apply. - If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat 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 + 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. + 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 */ @@ -4739,12 +5512,16 @@ void QCPAxis::setTickLabelColor( const QColor& color ) } /*! - 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 + 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 + 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 ) @@ -4757,8 +5534,10 @@ void QCPAxis::setTickLabelRotation( double degrees ) } /*! - 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(). + 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". @@ -4774,11 +5553,14 @@ void QCPAxis::setDateTimeFormat( const QString& format ) } /*! - Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref + 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 + 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 @@ -4789,39 +5571,60 @@ void QCPAxis::setDateTimeSpec( const Qt::TimeSpec& 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, + 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 + 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 + 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, + \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 + \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 + \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 + \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 + \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 ) @@ -4841,7 +5644,8 @@ void QCPAxis::setNumberFormat( const QString& formatCode ) } else { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + qDebug() << Q_FUNC_INFO + << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if( formatCode.length() < 2 ) @@ -4858,8 +5662,9 @@ void QCPAxis::setNumberFormat( const QString& formatCode ) } else { - qDebug() << Q_FUNC_INFO - << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + 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 ) @@ -4879,20 +5684,27 @@ void QCPAxis::setNumberFormat( const QString& formatCode ) } else { - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + 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 + 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 + 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 ) @@ -4905,7 +5717,8 @@ void QCPAxis::setNumberPrecision( int precision ) } /*! - If \ref setAutoTickStep is set to false, use this function to set the tick step manually. + 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 */ @@ -4919,47 +5732,62 @@ void QCPAxis::setTickStep( double step ) } /*! - 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. + 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. + \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 + // 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 + 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 + \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 + // 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 + 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 @@ -4971,7 +5799,8 @@ void QCPAxis::setTickLength( int inside, int outside ) } /*! - Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach + 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 @@ -4985,9 +5814,12 @@ void QCPAxis::setTickLengthIn( int 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. + 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 */ @@ -5001,14 +5833,18 @@ void QCPAxis::setTickLengthOut( int outside ) } /*! - Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, + 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 + 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, + 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 ) @@ -5017,9 +5853,12 @@ void QCPAxis::setSubTickCount( int 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, + 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 @@ -5031,7 +5870,8 @@ void QCPAxis::setSubTickLength( int inside, int outside ) } /*! - Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside + 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 @@ -5045,8 +5885,10 @@ void QCPAxis::setSubTickLengthIn( int 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 + 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 @@ -5115,7 +5957,8 @@ void QCPAxis::setLabelColor( const QColor& color ) } /*! - Sets the text of the axis label that will be shown below/above or next to the axis, depending on + 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 ) @@ -5144,10 +5987,12 @@ void QCPAxis::setLabelPadding( int padding ) /*! Sets the padding of the axis. - When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, + 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. + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is + disabled. \see setLabelPadding, setTickLabelPadding */ @@ -5163,9 +6008,12 @@ void QCPAxis::setPadding( int padding ) /*! 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 + 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 ) @@ -5176,32 +6024,37 @@ void QCPAxis::setOffset( int offset ) /*! Sets the font that is used for tick labels when they are selected. - \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions + \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 + // 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 + \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 + // 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 + \see setTickLabelColor, setSelectableParts, setSelectedParts, + QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor( const QColor& color ) { @@ -5214,7 +6067,8 @@ void QCPAxis::setSelectedTickLabelColor( const QColor& color ) /*! Sets the color that is used for the axis label when it is selected. - \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions + \see setLabelColor, setSelectableParts, setSelectedParts, + QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor( const QColor& color ) { @@ -5224,7 +6078,8 @@ void QCPAxis::setSelectedLabelColor( const QColor& color ) /*! Sets the pen that is used to draw the axis base line when selected. - \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions + \see setBasePen, setSelectableParts, setSelectedParts, + QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen( const QPen& pen ) { @@ -5234,7 +6089,8 @@ void QCPAxis::setSelectedBasePen( const QPen& pen ) /*! Sets the pen that is used to draw the (major) ticks when selected. - \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions + \see setTickPen, setSelectableParts, setSelectedParts, + QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen( const QPen& pen ) { @@ -5244,7 +6100,8 @@ void QCPAxis::setSelectedTickPen( const QPen& pen ) /*! Sets the pen that is used to draw the subticks when selected. - \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions + \see setSubTickPen, setSelectableParts, setSelectedParts, + QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen( const QPen& pen ) { @@ -5252,11 +6109,14 @@ void QCPAxis::setSelectedSubTickPen( const QPen& pen ) } /*! - Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available + 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 + 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 @@ -5267,11 +6127,14 @@ void QCPAxis::setLowerEnding( const QCPLineEnding& ending ) } /*! - Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available + 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 + 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 @@ -5282,11 +6145,14 @@ void QCPAxis::setUpperEnding( const QCPLineEnding& ending ) } /*! - If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper + 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). + 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 ) { @@ -5307,9 +6173,12 @@ void QCPAxis::moveRange( double diff ) } /*! - 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 + 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 ) @@ -5335,8 +6204,9 @@ void QCPAxis::scaleRange( double factor, double center ) mRange = newRange.sanitizedForLogScale(); } else - qDebug() << Q_FUNC_INFO - << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in " + "same logarithmic sign domain as range:" + << center; } mCachedMarginValid = false; emit rangeChanged( mRange ); @@ -5344,16 +6214,22 @@ void QCPAxis::scaleRange( double factor, double center ) } /*! - Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will + 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 + 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 + 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 ) @@ -5375,7 +6251,8 @@ void QCPAxis::setScaleRatio( const QCPAxis* otherAxis, double ratio ) } /*! - Changes the axis range such that all plottables associated with this axis are fully visible in + Changes the axis range such that all plottables associated with this axis are + fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes @@ -5393,7 +6270,8 @@ void QCPAxis::rescale( bool onlyVisiblePlottables ) bool currentFoundRange; QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; if( mScaleType == stLogarithmic ) - signDomain = ( mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive ); + signDomain = ( mRange.upper < 0 ? QCPAbstractPlottable::sdNegative + : QCPAbstractPlottable::sdPositive ); if( p.at( i )->keyAxis() == this ) plottableRange = p.at( i )->getKeyRange( currentFoundRange, signDomain ); else @@ -5409,12 +6287,15 @@ void QCPAxis::rescale( bool onlyVisiblePlottables ) } 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 + 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 + 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; @@ -5431,7 +6312,8 @@ void QCPAxis::rescale( bool onlyVisiblePlottables ) } /*! - Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. + Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis + coordinates. */ double QCPAxis::pixelToCoord( double value ) const { @@ -5440,17 +6322,21 @@ double QCPAxis::pixelToCoord( double value ) const if( mScaleType == stLinear ) { if( !mRangeReversed ) - return ( value - mAxisRect->left() ) / (double)mAxisRect->width() * mRange.size() + mRange.lower; + return ( value - mAxisRect->left() ) / (double)mAxisRect->width() * mRange.size() + + mRange.lower; else - return -( value - mAxisRect->left() ) / (double)mAxisRect->width() * mRange.size() + mRange.upper; + return -( value - mAxisRect->left() ) / (double)mAxisRect->width() * mRange.size() + + mRange.upper; } else // mScaleType == stLogarithmic { if( !mRangeReversed ) - return pow( mRange.upper / mRange.lower, ( value - mAxisRect->left() ) / (double)mAxisRect->width() ) * + return pow( mRange.upper / mRange.lower, + ( value - mAxisRect->left() ) / (double)mAxisRect->width() ) * mRange.lower; else - return pow( mRange.upper / mRange.lower, ( mAxisRect->left() - value ) / (double)mAxisRect->width() ) * + return pow( mRange.upper / mRange.lower, + ( mAxisRect->left() - value ) / (double)mAxisRect->width() ) * mRange.upper; } } @@ -5459,24 +6345,29 @@ double QCPAxis::pixelToCoord( double value ) const if( mScaleType == stLinear ) { if( !mRangeReversed ) - return ( mAxisRect->bottom() - value ) / (double)mAxisRect->height() * mRange.size() + mRange.lower; + return ( mAxisRect->bottom() - value ) / (double)mAxisRect->height() * mRange.size() + + mRange.lower; else - return -( mAxisRect->bottom() - value ) / (double)mAxisRect->height() * mRange.size() + mRange.upper; + return -( mAxisRect->bottom() - value ) / (double)mAxisRect->height() * mRange.size() + + mRange.upper; } else // mScaleType == stLogarithmic { if( !mRangeReversed ) - return pow( mRange.upper / mRange.lower, ( mAxisRect->bottom() - value ) / (double)mAxisRect->height() ) * + return pow( mRange.upper / mRange.lower, + ( mAxisRect->bottom() - value ) / (double)mAxisRect->height() ) * mRange.lower; else - return pow( mRange.upper / mRange.lower, ( value - mAxisRect->bottom() ) / (double)mAxisRect->height() ) * + return pow( 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. + Transforms \a value, in coordinates of the axis, to pixel coordinates of the + QCustomPlot widget. */ double QCPAxis::coordToPixel( double value ) const { @@ -5491,18 +6382,23 @@ double QCPAxis::coordToPixel( double value ) const } else // mScaleType == stLogarithmic { - if( value >= 0 && mRange.upper < 0 ) // invalid value for logarithmic scale, just draw it outside visible range + 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 + 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() + + 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() + + return baseLog( mRange.upper / value ) / baseLog( mRange.upper / mRange.lower ) * + mAxisRect->width() + mAxisRect->left(); } } @@ -5518,30 +6414,38 @@ double QCPAxis::coordToPixel( double value ) const } else // mScaleType == stLogarithmic { - if( value >= 0 && mRange.upper < 0 ) // invalid value for logarithmic scale, just draw it outside visible range + 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 + 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(); + 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(); + 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 + 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. + If the axis is not visible (\ref setVisible), this function always returns + \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ @@ -5589,7 +6493,8 @@ QList QCPAxis::plottables() const for( int i = 0; i < mParentPlot->mPlottables.size(); ++i ) { - if( mParentPlot->mPlottables.at( i )->keyAxis() == this || mParentPlot->mPlottables.at( i )->valueAxis() == this ) + if( mParentPlot->mPlottables.at( i )->keyAxis() == this || + mParentPlot->mPlottables.at( i )->valueAxis() == this ) result.append( mParentPlot->mPlottables.at( i ) ); } return result; @@ -5608,15 +6513,18 @@ QList QCPAxis::graphs() const for( int i = 0; i < mParentPlot->mGraphs.size(); ++i ) { - if( mParentPlot->mGraphs.at( i )->keyAxis() == this || mParentPlot->mGraphs.at( i )->valueAxis() == this ) + 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. + 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 */ @@ -5642,7 +6550,8 @@ QList QCPAxis::items() const } /*! - Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to + 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 ) @@ -5665,7 +6574,8 @@ QCPAxis::AxisType QCPAxis::marginSideToAxisType( QCP::MarginSide side ) } /*! - Returns the axis type that describes the opposite axis of an axis with the specified \a type. + Returns the axis type that describes the opposite axis of an axis with the + specified \a type. */ QCPAxis::AxisType QCPAxis::opposite( QCPAxis::AxisType type ) { @@ -5692,10 +6602,14 @@ QCPAxis::AxisType QCPAxis::opposite( QCPAxis::AxisType type ) /*! \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. + 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() { @@ -5704,7 +6618,8 @@ void QCPAxis::setupTickVectors() 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 + // fill tick vectors, either by auto generating or by notifying user to fill + // the vectors himself if( mAutoTicks ) { generateAutoTicks(); @@ -5730,10 +6645,12 @@ void QCPAxis::setupTickVectors() int subTickIndex = 0; bool done = false; int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick - 1 : mLowestVisibleTick; - int highTick = mHighestVisibleTick < mTickVector.size() - 1 ? mHighestVisibleTick + 1 : mHighestVisibleTick; + 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 ); + 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; @@ -5761,27 +6678,32 @@ void QCPAxis::setupTickVectors() if( mTickLabelType == ltNumber ) { for( int i = mLowestVisibleTick; i <= mHighestVisibleTick; ++i ) - mTickVectorLabels[i] = - mParentPlot->locale().toString( mTickVector.at( i ), mNumberFormatChar, mNumberPrecision ); + mTickVectorLabels[i] = mParentPlot->locale().toString( + mTickVector.at( i ), mNumberFormatChar, 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") +#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 ); + QDateTime::fromTime_t( mTickVector.at( i ) ).toTimeSpec( mDateTimeSpec ), + mDateTimeFormat ); #else mTickVectorLabels[i] = mParentPlot->locale().toString( - QDateTime::fromMSecsSinceEpoch( mTickVector.at( i ) * 1000 ).toTimeSpec( mDateTimeSpec ), mDateTimeFormat ); + 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 + if( mAutoTicks ) // ticks generated automatically, but not ticklabels, so + // emit ticksRequest here for labels { emit ticksRequest(); } @@ -5793,11 +6715,14 @@ void QCPAxis::setupTickVectors() /*! \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 + 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 + 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() @@ -5807,11 +6732,13 @@ void QCPAxis::generateAutoTicks() 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 + 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. + 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 ) { @@ -5845,8 +6772,10 @@ void QCPAxis::generateAutoTicks() 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 + while( currentMag < mRange.upper && currentMag > 0 ) // currentMag might be + // zero for ranges + // ~1e-300, just + // cancel in that case { currentMag *= mScaleLogBase; mTickVector.append( currentMag ); @@ -5858,41 +6787,54 @@ void QCPAxis::generateAutoTicks() 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 + 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 + 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; + 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 + 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 + 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 + 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. + 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: @@ -5959,7 +6901,8 @@ int QCPAxis::calculateAutoSubTickCount( double tickStep ) const break; // 4.5 -> 1.5 substep case 5: result = 4; - break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) + break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here + // on) case 6: result = 4; break; // 6.5 -> 1.3 substep @@ -5974,14 +6917,18 @@ int QCPAxis::calculateAutoSubTickCount( double tickStep ) const 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 + // 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 ) +void QCPAxis::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { Q_UNUSED( event ) SelectablePart part = details.value(); @@ -6005,12 +6952,15 @@ void QCPAxis::deselectEvent( bool* selectionStateChanged ) /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 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 + 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. @@ -6023,15 +6973,18 @@ void QCPAxis::applyDefaultAntialiasingHint( QCPPainter* painter ) const /*! \internal - Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. + 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 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 ); @@ -6049,19 +7002,23 @@ void QCPAxis::draw( QCPPainter* painter ) if( mSubTickCount > 0 ) { const int subTickCount = mSubTickVector.size(); - for( int i = 0; i < subTickCount; - ++i ) // no need to check bounds because subticks are always only created inside current mRange + for( int i = 0; i < subTickCount; ++i ) // no need to check bounds because + // subticks are always only created + // inside current mRange subTickPositions.append( coordToPixel( mSubTickVector.at( i ) ) ); } } - // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis. - // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + // transfer all properties of this axis to QCPAxisPainterPrivate which it + // needs to draw the axis. + // Note that some axis painter properties are already set by direct + // feed-through with QCPAxis setters mAxisPainter->type = mAxisType; mAxisPainter->basePen = getBasePen(); mAxisPainter->labelFont = getLabelFont(); mAxisPainter->labelColor = getLabelColor(); mAxisPainter->label = mLabel; - mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; + mAxisPainter->substituteExponent = + mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; mAxisPainter->tickPen = getTickPen(); mAxisPainter->subTickPen = getSubTickPen(); mAxisPainter->tickLabelFont = getTickLabelFont(); @@ -6078,19 +7035,28 @@ void QCPAxis::draw( QCPPainter* 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 + 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 + 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. + 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 { @@ -6126,8 +7092,10 @@ void QCPAxis::visibleTickBounds( int& lowIndex, int& highIndex ) const /*! \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. + 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 @@ -6139,7 +7107,8 @@ double QCPAxis::baseLog( double value ) const /*! \internal - A power function with the base mScaleLogBase, used mostly for coordinate transforms in + A power function with the base mScaleLogBase, used mostly for coordinate + transforms in logarithmic scales with arbitrary log base. \see baseLog, setScaleLogBase, setScaleType @@ -6151,7 +7120,8 @@ double QCPAxis::basePow( double value ) const /*! \internal - Returns the pen that is used to draw the axis base line. Depending on the selection state, this + 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 @@ -6161,7 +7131,8 @@ QPen QCPAxis::getBasePen() const /*! \internal - Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this + 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 @@ -6171,7 +7142,8 @@ QPen QCPAxis::getTickPen() const /*! \internal - Returns the pen that is used to draw the subticks. Depending on the selection state, this + 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 @@ -6181,7 +7153,8 @@ QPen QCPAxis::getSubTickPen() const /*! \internal - Returns the font that is used to draw the tick labels. Depending on the selection state, this + 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 @@ -6191,7 +7164,8 @@ QFont QCPAxis::getTickLabelFont() const /*! \internal - Returns the font that is used to draw the axis label. Depending on the selection state, this + 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 @@ -6201,7 +7175,8 @@ QFont QCPAxis::getLabelFont() const /*! \internal - Returns the color that is used to draw the tick labels. Depending on the selection state, this + 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 @@ -6211,7 +7186,8 @@ QColor QCPAxis::getTickLabelColor() const /*! \internal - Returns the color that is used to draw the axis label. Depending on the selection state, this + 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 @@ -6222,31 +7198,40 @@ QColor QCPAxis::getLabelColor() const /*! \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. + 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 + 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. + 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 + 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 + // 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 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 ); @@ -6259,8 +7244,10 @@ int QCPAxis::calculateMargin() 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 + // 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; @@ -6294,36 +7281,39 @@ QCP::Interaction QCPAxis::selectionCategory() const 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 + 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 + 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 ), - 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 + : type( QCPAxis::atLeft ) + , basePen( QPen( Qt::black, 0, Qt::SolidLine, Qt::SquareCap ) ) + , lowerEnding( QCPLineEnding::esNone ) + , upperEnding( QCPLineEnding::esNone ) + , labelPadding( 0 ) + , tickLabelPadding( 0 ) + , tickLabelRotation( 0 ) + , 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 { } @@ -6335,7 +7325,8 @@ QCPAxisPainterPrivate::~QCPAxisPainterPrivate() Draws the axis with the specified \a painter. - The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, + mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) @@ -6364,8 +7355,8 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) break; } - double xCor = 0, - yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + 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: @@ -6383,12 +7374,15 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) QLineF baseLine; painter->setPen( basePen ); if( QCPAxis::orientation( type ) == Qt::Horizontal ) - baseLine.setPoints( origin + QPointF( xCor, yCor ), origin + QPointF( alignmentRect.width() + xCor, yCor ) ); + baseLine.setPoints( origin + QPointF( xCor, yCor ), + origin + QPointF( alignmentRect.width() + xCor, yCor ) ); else - baseLine.setPoints( origin + QPointF( xCor, yCor ), origin + QPointF( xCor, -alignmentRect.height() + yCor ) ); + baseLine.setPoints( origin + QPointF( xCor, yCor ), + origin + QPointF( xCor, -alignmentRect.height() + yCor ) ); if( reversedEndings ) - baseLine = - QLineF( baseLine.p2(), baseLine.p1() ); // won't make a difference for line itself, but for line endings later + baseLine = QLineF( baseLine.p2(), baseLine.p1() ); // won't make a difference + // for line itself, but for + // line endings later painter->drawLine( baseLine ); // draw ticks: @@ -6397,18 +7391,21 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) 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) + : 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; i < tickPositions.size(); ++i ) - painter->drawLine( QLineF( tickPositions.at( i ) + xCor, origin.y() - tickLengthOut * tickDir + yCor, - tickPositions.at( i ) + xCor, origin.y() + tickLengthIn * tickDir + yCor ) ); + painter->drawLine( + QLineF( tickPositions.at( i ) + xCor, origin.y() - tickLengthOut * tickDir + yCor, + tickPositions.at( i ) + xCor, origin.y() + tickLengthIn * tickDir + yCor ) ); } else { for( int i = 0; i < tickPositions.size(); ++i ) - painter->drawLine( QLineF( origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at( i ) + yCor, - origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at( i ) + yCor ) ); + painter->drawLine( + QLineF( origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at( i ) + yCor, + origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at( i ) + yCor ) ); } } @@ -6416,37 +7413,41 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) if( !subTickPositions.isEmpty() ) { painter->setPen( subTickPen ); - // direction of ticks ("inward" is right for left axis and left for right axis) + // 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; i < subTickPositions.size(); ++i ) - painter->drawLine( QLineF( subTickPositions.at( i ) + xCor, origin.y() - subTickLengthOut * tickDir + yCor, - subTickPositions.at( i ) + xCor, origin.y() + subTickLengthIn * tickDir + yCor ) ); + painter->drawLine( QLineF( + subTickPositions.at( i ) + xCor, origin.y() - subTickLengthOut * tickDir + yCor, + subTickPositions.at( i ) + xCor, origin.y() + subTickLengthIn * tickDir + yCor ) ); } else { for( int i = 0; i < subTickPositions.size(); ++i ) - painter->drawLine( QLineF( origin.x() - subTickLengthOut * tickDir + xCor, subTickPositions.at( i ) + yCor, - origin.x() + subTickLengthIn * tickDir + xCor, subTickPositions.at( i ) + yCor ) ); + painter->drawLine( 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->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 ), + 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 ), + upperEnding.draw( painter, QVector2D( baseLine.p2() ) + + baseLineVector.normalized() * upperEnding.realLength() * + ( upperEnding.inverted() ? -1 : 1 ), baseLineVector ); painter->setAntialiasing( antialiasingBackup ); @@ -6479,25 +7480,27 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) QTransform oldTransform = painter->transform(); painter->translate( ( origin.x() - margin - labelBounds.height() ), origin.y() ); painter->rotate( -90 ); - painter->drawText( 0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, - label ); + painter->drawText( 0, 0, alignmentRect.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() - alignmentRect.height() ); + painter->translate( ( origin.x() + margin + labelBounds.height() ), + origin.y() - alignmentRect.height() ); painter->rotate( 90 ); - painter->drawText( 0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, - label ); + painter->drawText( 0, 0, alignmentRect.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(), alignmentRect.width(), - labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label ); - else if( type == QCPAxis::atBottom ) - painter->drawText( origin.x(), origin.y() + margin, alignmentRect.width(), labelBounds.height(), + painter->drawText( origin.x(), origin.y() - margin - labelBounds.height(), + alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label ); + else if( type == QCPAxis::atBottom ) + painter->drawText( origin.x(), origin.y() + margin, alignmentRect.width(), + labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label ); } // set selection boxes: @@ -6509,54 +7512,61 @@ void QCPAxisPainterPrivate::draw( QCPPainter* painter ) int selAxisOutSize = qMax( qMax( tickLengthOut, subTickLengthOut ), selectionTolerance ); int selAxisInSize = selectionTolerance; int selTickLabelSize = - ( QCPAxis::orientation( type ) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width() ); + ( QCPAxis::orientation( type ) == Qt::Horizontal ? tickLabelsSize.height() + : tickLabelsSize.width() ); int selTickLabelOffset = qMax( tickLengthOut, subTickLengthOut ) + tickLabelPadding; int selLabelSize = labelBounds.height(); int selLabelOffset = selTickLabelOffset + selTickLabelSize + labelPadding; if( type == QCPAxis::atLeft ) { - mAxisSelectionBox.setCoords( origin.x() - selAxisOutSize, alignmentRect.top(), origin.x() + selAxisInSize, - alignmentRect.bottom() ); - mTickLabelsSelectionBox.setCoords( origin.x() - selTickLabelOffset - selTickLabelSize, alignmentRect.top(), - origin.x() - selTickLabelOffset, alignmentRect.bottom() ); + mAxisSelectionBox.setCoords( origin.x() - selAxisOutSize, alignmentRect.top(), + origin.x() + selAxisInSize, alignmentRect.bottom() ); + mTickLabelsSelectionBox.setCoords( origin.x() - selTickLabelOffset - selTickLabelSize, + alignmentRect.top(), origin.x() - selTickLabelOffset, + alignmentRect.bottom() ); mLabelSelectionBox.setCoords( origin.x() - selLabelOffset - selLabelSize, alignmentRect.top(), origin.x() - selLabelOffset, alignmentRect.bottom() ); } else if( type == QCPAxis::atRight ) { - mAxisSelectionBox.setCoords( origin.x() - selAxisInSize, alignmentRect.top(), origin.x() + selAxisOutSize, - alignmentRect.bottom() ); - mTickLabelsSelectionBox.setCoords( origin.x() + selTickLabelOffset + selTickLabelSize, alignmentRect.top(), - origin.x() + selTickLabelOffset, alignmentRect.bottom() ); + mAxisSelectionBox.setCoords( origin.x() - selAxisInSize, alignmentRect.top(), + origin.x() + selAxisOutSize, alignmentRect.bottom() ); + mTickLabelsSelectionBox.setCoords( origin.x() + selTickLabelOffset + selTickLabelSize, + alignmentRect.top(), origin.x() + selTickLabelOffset, + alignmentRect.bottom() ); mLabelSelectionBox.setCoords( origin.x() + selLabelOffset + selLabelSize, alignmentRect.top(), origin.x() + selLabelOffset, alignmentRect.bottom() ); } else if( type == QCPAxis::atTop ) { - mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisOutSize, alignmentRect.right(), - origin.y() + selAxisInSize ); - mTickLabelsSelectionBox.setCoords( alignmentRect.left(), origin.y() - selTickLabelOffset - selTickLabelSize, + mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisOutSize, + alignmentRect.right(), origin.y() + selAxisInSize ); + mTickLabelsSelectionBox.setCoords( alignmentRect.left(), + origin.y() - selTickLabelOffset - selTickLabelSize, alignmentRect.right(), origin.y() - selTickLabelOffset ); mLabelSelectionBox.setCoords( alignmentRect.left(), origin.y() - selLabelOffset - selLabelSize, alignmentRect.right(), origin.y() - selLabelOffset ); } else if( type == QCPAxis::atBottom ) { - mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisInSize, alignmentRect.right(), - origin.y() + selAxisOutSize ); - mTickLabelsSelectionBox.setCoords( alignmentRect.left(), origin.y() + selTickLabelOffset + selTickLabelSize, + mAxisSelectionBox.setCoords( alignmentRect.left(), origin.y() - selAxisInSize, + alignmentRect.right(), origin.y() + selAxisOutSize ); + mTickLabelsSelectionBox.setCoords( alignmentRect.left(), + origin.y() + selTickLabelOffset + selTickLabelSize, alignmentRect.right(), origin.y() + selTickLabelOffset ); mLabelSelectionBox.setCoords( alignmentRect.left(), origin.y() + selLabelOffset + selLabelSize, alignmentRect.right(), origin.y() + selLabelOffset ); } // draw hitboxes for debug purposes: // painter->setBrush(Qt::NoBrush); - // painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); + // painter->drawRects(QVector() << mAxisSelectionBox << + // mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal - Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular + to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const @@ -6573,16 +7583,19 @@ int QCPAxisPainterPrivate::size() const { for( int i = 0; i < tickLabels.size(); ++i ) getMaxTickLabelSize( tickLabelFont, tickLabels.at( i ), &tickLabelsSize ); - result += QCPAxis::orientation( type ) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width(); + result += QCPAxis::orientation( type ) == Qt::Horizontal ? tickLabelsSize.height() + : tickLabelsSize.width(); result += tickLabelPadding; } - // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): + // calculate size of axis label (only height needed, because left/right labels + // are rotated by 90 degrees): if( !label.isEmpty() ) { QFontMetrics fontMetrics( labelFont ); QRect bounds; - bounds = fontMetrics.boundingRect( 0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label ); + bounds = fontMetrics.boundingRect( + 0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label ); result += bounds.height() + labelPadding; } @@ -6591,8 +7604,10 @@ int QCPAxisPainterPrivate::size() const /*! \internal - Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This - method is called automatically in \ref draw, if any parameters have changed that invalidate the + Clears the internal label cache. Upon the next \ref draw, all labels will be + created new. This + method is called automatically in \ref draw, if any parameters have changed + that invalidate the cached labels, such as font, color, etc. */ void QCPAxisPainterPrivate::clearCache() @@ -6602,9 +7617,12 @@ void QCPAxisPainterPrivate::clearCache() /*! \internal - Returns a hash that allows uniquely identifying whether the label parameters have changed such - that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the - return value of this method hasn't changed since the last redraw, the respective label parameters + Returns a hash that allows uniquely identifying whether the label parameters + have changed such + that the cached labels must be refreshed (\ref clearCache). It is used in \ref + draw. If the + return value of this method hasn't changed since the last redraw, the + respective label parameters haven't changed and cached labels may be used. */ QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const @@ -6620,21 +7638,32 @@ QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const /*! \internal - Draws a single tick label with the provided \a painter, utilizing the internal label cache to - significantly speed up drawing of labels that were drawn in previous calls. The tick label is - always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in - pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence - for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), + Draws a single tick label with the provided \a painter, utilizing the internal + label cache to + significantly speed up drawing of labels that were drawn in previous calls. + The tick label is + always bound to an axis, the distance to the axis is controllable via \a + distanceToAxis in + pixels. The pixel position in the axis direction is passed in the \a position + parameter. Hence + for the bottom axis, \a position would indicate the horizontal pixel position + (not coordinate), at which the label should be drawn. - In order to later draw the axis label in a place that doesn't overlap with the tick labels, the - largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref - drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a - tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently + In order to later draw the axis label in a place that doesn't overlap with the + tick labels, the + largest tick label size is needed. This is acquired by passing a \a + tickLabelsSize to the \ref + drawTickLabel calls during the process of drawing all tick labels of one axis. + In every call, \a + tickLabelsSize is expanded, if the drawn label exceeds the value \a + tickLabelsSize currently holds. - The label is drawn with the font and pen that are currently set on the \a painter. To draw - superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref + The label is drawn with the font and pen that are currently set on the \a + painter. To draw + superscripted powers, the font is temporarily made smaller by a fixed factor + (see \ref getTickLabelData). */ void QCPAxisPainterPrivate::placeTickLabel( QCPPainter* painter, @@ -6643,7 +7672,8 @@ void QCPAxisPainterPrivate::placeTickLabel( QCPPainter* painter, const QString& text, QSize* tickLabelsSize ) { - // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! + // warning: if you change anything here, also adapt getMaxTickLabelSize() + // accordingly! if( text.isEmpty() ) return; QSize finalSize; @@ -6682,16 +7712,19 @@ void QCPAxisPainterPrivate::placeTickLabel( QCPPainter* painter, } // draw cached label: const CachedLabel* cachedLabel = mLabelCache.object( text ); - // if label would be partly clipped by widget border on sides, don't draw it: + // if label would be partly clipped by widget border on sides, don't draw + // it: if( QCPAxis::orientation( type ) == Qt::Horizontal ) { - if( labelAnchor.x() + cachedLabel->offset.x() + cachedLabel->pixmap.width() > viewportRect.right() || + if( labelAnchor.x() + cachedLabel->offset.x() + cachedLabel->pixmap.width() > + viewportRect.right() || labelAnchor.x() + cachedLabel->offset.x() < viewportRect.left() ) return; } else { - if( labelAnchor.y() + cachedLabel->offset.y() + cachedLabel->pixmap.height() > viewportRect.bottom() || + if( labelAnchor.y() + cachedLabel->offset.y() + cachedLabel->pixmap.height() > + viewportRect.bottom() || labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top() ) return; } @@ -6702,17 +7735,20 @@ void QCPAxisPainterPrivate::placeTickLabel( QCPPainter* painter, { 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: + // if label would be partly clipped by widget border on sides, don't draw + // it: if( QCPAxis::orientation( type ) == Qt::Horizontal ) { - if( finalPosition.x() + ( labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left() ) > + if( finalPosition.x() + + ( labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left() ) > viewportRect.right() || finalPosition.x() + labelData.rotatedTotalBounds.left() < viewportRect.left() ) return; } else { - if( finalPosition.y() + ( labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top() ) > + if( finalPosition.y() + + ( labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top() ) > viewportRect.bottom() || finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top() ) return; @@ -6732,9 +7768,12 @@ void QCPAxisPainterPrivate::placeTickLabel( QCPPainter* painter, 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 + 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, @@ -6757,8 +7796,8 @@ void QCPAxisPainterPrivate::drawTickLabel( QCPPainter* painter, 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 ); + painter->drawText( labelData.baseBounds.width() + 1, 0, labelData.expBounds.width(), + labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart ); } else { @@ -6776,12 +7815,16 @@ void QCPAxisPainterPrivate::drawTickLabel( QCPPainter* painter, 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. + 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 +QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData( + const QFont& font, + const QString& text ) const { TickLabelData result; @@ -6795,26 +7838,33 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData( co useBeautifulPowers = true; } - // calculate text bounding rects and do string preparation for beautiful decimal powers: + // calculate text bounding rects and do string preparation for beautiful + // decimal powers: result.baseFont = font; - if( result.baseFont.pointSizeF() > 0 ) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so - // we check here before possibly setting a negative value in the 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( result.baseFont.pointSizeF() > 0 ) // On some rare systems, this sometimes + // is initialized with -1 (Qt bug?), so + // we check here before possibly setting a negative value in the 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: + // 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: + // in log scaling, we want to turn "1*10^n" into "10^n", else add + // multiplication sign and decimal base: if( abbreviateDecimalPowers && result.basePart == "1" ) result.basePart = "10"; else - result.basePart += ( numberMultiplyCross ? QString( QChar( 215 ) ) : QString( QChar( 183 ) ) ) + "10"; + result.basePart += + ( numberMultiplyCross ? QString( QChar( 215 ) ) : QString( QChar( 183 ) ) ) + "10"; result.expPart = text.mid( ePos + 1 ); // clip "+" and leading zeros off expPart: while( result.expPart.length() > 2 && - result.expPart.at( 1 ) == '0' ) // length > 2 so we leave one zero when numberFormatChar is 'e' + result.expPart.at( 1 ) == + '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 ) == '+' ) result.expPart.remove( 0, 1 ); @@ -6822,20 +7872,25 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData( co result.expFont = font; result.expFont.setPointSize( result.expFont.pointSize() * 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.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 + 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 = + 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 + 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; @@ -6853,27 +7908,37 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData( co This is a \ref placeTickLabel helper function. - Calculates the offset at which the top left corner of the specified tick label shall be drawn. + 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 + 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 + 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. + 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 ) @@ -6889,7 +7954,8 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labe } else { - x = -qCos( -radians ) * labelData.totalBounds.width() - qSin( -radians ) * labelData.totalBounds.height(); + 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; @@ -6908,12 +7974,14 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labe if( tickLabelRotation > 0 ) { x = +qSin( radians ) * labelData.totalBounds.height(); - y = flip ? -labelData.totalBounds.width() / 2.0 : -qCos( radians ) * labelData.totalBounds.height() / 2.0; + 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; + y = flip ? +labelData.totalBounds.width() / 2.0 + : -qCos( -radians ) * labelData.totalBounds.height() / 2.0; } } else @@ -6928,8 +7996,10 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labe { 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(); + 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 { @@ -6954,7 +8024,8 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labe } else { - x = -qCos( -radians ) * labelData.totalBounds.width() - qSin( -radians ) * labelData.totalBounds.height() / 2.0; + x = -qCos( -radians ) * labelData.totalBounds.width() - + qSin( -radians ) * labelData.totalBounds.height() / 2.0; y = +qSin( -radians ) * labelData.totalBounds.width(); } } @@ -6970,14 +8041,20 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset( const TickLabelData& labe /*! \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 + 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 +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. + // 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 @@ -7005,12 +8082,15 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin /*! \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 + 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 is displayed by \ref QCPGraph + \li A normal graph with possibly a line, scatter points and error bars is + displayed by \ref QCPGraph (typically created with \ref QCustomPlot::addGraph). \li A parametric curve can be displayed with \ref QCPCurve. \li A stackable bar chart can be achieved with \ref QCPBars. @@ -7018,7 +8098,8 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin \section plottables-subclassing Creating own plottables - To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure + 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 @@ -7029,44 +8110,57 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin 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 + 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 + QCPAxis::coordToPixel. However, you must then take care about the orientation + of the axis yourself. Here are some important members you inherit from QCPAbstractPlottable: - - - - + - - @@ -7081,42 +8175,60 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin Clears all data in the plottable. */ -/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 +/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const + QRect &rect) const = 0 \internal - called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a + graphical representation of this plottable inside \a rect, next to the plottable name. */ -/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 +/*! \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 + 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 + 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 +/*! \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 + 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 + 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 @@ -7127,7 +8239,8 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) - This signal is emitted when the selection state of this plottable has changed, either by user + 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. */ @@ -7141,30 +8254,36 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize( const QFont& font, const QStrin /* 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. + 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, + 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. + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve + instead. */ QCPAbstractPlottable::QCPAbstractPlottable( QCPAxis* keyAxis, QCPAxis* valueAxis ) - : QCPLayerable( keyAxis->parentPlot(), "", 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 ) + : QCPLayerable( keyAxis->parentPlot(), "", 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."; @@ -7173,7 +8292,8 @@ QCPAbstractPlottable::QCPAbstractPlottable( QCPAxis* keyAxis, QCPAxis* valueAxis } /*! - The name is the textual representation of this plottable as it is displayed in the legend + 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 ) @@ -7184,7 +8304,8 @@ void QCPAbstractPlottable::setName( const QString& name ) /*! Sets whether fills of this plottable is drawn antialiased or not. - Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + Note that this setting may be overridden by \ref + QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedFill( bool enabled ) @@ -7193,9 +8314,11 @@ void QCPAbstractPlottable::setAntialiasedFill( bool enabled ) } /*! - Sets whether the scatter symbols of this plottable are drawn antialiased or not. + 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 + Note that this setting may be overridden by \ref + QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedScatters( bool enabled ) @@ -7206,7 +8329,8 @@ void QCPAbstractPlottable::setAntialiasedScatters( bool 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 + Note that this setting may be overridden by \ref + QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedErrorBars( bool enabled ) @@ -7215,10 +8339,12 @@ void QCPAbstractPlottable::setAntialiasedErrorBars( bool enabled ) } /*! - The pen is used to draw basic lines that make up the plottable representation in the + 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 and scatter points + For example, the \ref QCPGraph subclass draws its graph lines and scatter + points with this pen. \see setBrush @@ -7229,7 +8355,8 @@ void QCPAbstractPlottable::setPen( const QPen& pen ) } /*! - When the plottable is selected, this pen is used to draw basic lines instead of the normal + 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 @@ -7243,7 +8370,8 @@ void QCPAbstractPlottable::setSelectedPen( const QPen& 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 + 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 @@ -7254,7 +8382,8 @@ void QCPAbstractPlottable::setBrush( const QBrush& brush ) } /*! - When the plottable is selected, this brush is used to draw fills instead of the normal + 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 @@ -7265,13 +8394,18 @@ void QCPAbstractPlottable::setSelectedBrush( const QBrush& 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 + 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). + 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 */ @@ -7281,13 +8415,18 @@ void QCPAbstractPlottable::setKeyAxis( QCPAxis* 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 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). + 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 */ @@ -7297,10 +8436,12 @@ void QCPAbstractPlottable::setValueAxis( QCPAxis* axis ) } /*! - Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. + 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, + However, even when \a selectable was set to false, it is possible to set the + selection manually, by calling \ref setSelected directly. \see setSelected @@ -7315,16 +8456,22 @@ void QCPAbstractPlottable::setSelectable( bool selectable ) } /*! - 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. + 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 + 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. + 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. + emits the \ref selectionChanged signal when \a selected is different from the + previous selection state. \see setSelectable, selectTest */ @@ -7338,17 +8485,24 @@ void QCPAbstractPlottable::setSelected( bool selected ) } /*! - 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 + 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 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 + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, + QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes( bool onlyEnlarge ) const { @@ -7380,12 +8534,15 @@ void QCPAbstractPlottable::rescaleKeyAxis( bool onlyEnlarge ) const { 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 + 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 + 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; @@ -7404,7 +8561,8 @@ void QCPAbstractPlottable::rescaleKeyAxis( bool onlyEnlarge ) const /*! 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 + 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. @@ -7428,12 +8586,15 @@ void QCPAbstractPlottable::rescaleValueAxis( bool onlyEnlarge ) const { 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 + 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 + 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; @@ -7450,13 +8611,17 @@ void QCPAbstractPlottable::rescaleValueAxis( bool onlyEnlarge ) const } /*! - Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). + 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 + 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 + 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 @@ -7476,11 +8641,14 @@ bool QCPAbstractPlottable::addToLegend() } /*! - Removes the plottable from the legend of the parent QCustomPlot. This means the - QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable + 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 + 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 @@ -7513,11 +8681,14 @@ QCP::Interaction QCPAbstractPlottable::selectionCategory() const /*! \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 + 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. + \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 */ @@ -7566,11 +8737,14 @@ const QPointF QCPAbstractPlottable::coordsToPixels( double key, double value ) c /*! \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 + 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. + \a x and \a y are transformed to the plot coodinates and are written to \a key + and \a value. \see coordsToPixels, QCPAxis::coordToPixel */ @@ -7601,14 +8775,17 @@ void QCPAbstractPlottable::pixelsToCoords( double x, double y, double& key, doub 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 +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 + 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 @@ -7618,7 +8795,8 @@ QPen QCPAbstractPlottable::mainPen() const /*! \internal - Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the + 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 @@ -7628,16 +8806,20 @@ QBrush QCPAbstractPlottable::mainBrush() const /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 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 + 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 + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, + applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint( QCPPainter* painter ) const { @@ -7646,14 +8828,17 @@ void QCPAbstractPlottable::applyDefaultAntialiasingHint( QCPPainter* painter ) c /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 + 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 + \see setAntialiased, applyDefaultAntialiasingHint, + applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint( QCPPainter* painter ) const { @@ -7662,14 +8847,17 @@ void QCPAbstractPlottable::applyFillAntialiasingHint( QCPPainter* painter ) cons /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 + 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 + \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, + applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint( QCPPainter* painter ) const { @@ -7678,14 +8866,17 @@ void QCPAbstractPlottable::applyScattersAntialiasingHint( QCPPainter* painter ) /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 + 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 + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, + applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyErrorBarsAntialiasingHint( QCPPainter* painter ) const { @@ -7694,15 +8885,19 @@ void QCPAbstractPlottable::applyErrorBarsAntialiasingHint( QCPPainter* painter ) /*! \internal - Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + 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 + 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 +double QCPAbstractPlottable::distSqrToLine( const QPointF& start, + const QPointF& end, + const QPointF& point ) const { QVector2D a( start ); QVector2D b( end ); @@ -7760,21 +8955,30 @@ void QCPAbstractPlottable::deselectEvent( bool* selectionStateChanged ) /*! \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 + 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 + 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 + 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 + To learn how to provide anchors in your own item subclasses, see the + subclassing section of the QCPAbstractItem documentation. */ @@ -7782,22 +8986,30 @@ void QCPAbstractPlottable::deselectEvent( bool* selectionStateChanged ) /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() - Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if + 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 + 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 + 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 ) +QCPItemAnchor::QCPItemAnchor( QCustomPlot* parentPlot, + QCPAbstractItem* parentItem, + const QString name, + int anchorId ) : mName( name ), mParentPlot( parentPlot ), mParentItem( parentItem ), mAnchorId( anchorId ) { } @@ -7807,14 +9019,17 @@ QCPItemAnchor::~QCPItemAnchor() // unregister as parent at children: QList currentChildren( mChildren.toList() ); for( int i = 0; i < currentChildren.size(); ++i ) - currentChildren.at( i )->setParentAnchor( - 0 ); // this acts back on this anchor and child removes itself from mChildren + currentChildren.at( i )->setParentAnchor( 0 ); // this acts back on this anchor + // and child removes itself from + // mChildren } /*! - Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. + Returns the final absolute pixel position of the QCPItemAnchor on the + QCustomPlot surface. - The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the + The pixel information is internally retrieved via + QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPoint() const @@ -7840,7 +9055,8 @@ QPointF QCPItemAnchor::pixelPoint() const /*! \internal - Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to + Adds \a pos to the child list of this anchor. 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. @@ -7872,92 +9088,127 @@ void QCPItemAnchor::removeChild( QCPItemPosition* pos ) /*! \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: + 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 + 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. - Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every - QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other - positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the - coordinates set with \ref setCoords are considered to be absolute values 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, or is + Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref + setParentAnchor. (Note that every + QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as + parent anchor for other + positions.) This way you can tie multiple items together. If the + QCPItemPosition has a parent, the + coordinates set with \ref setCoords are considered to be absolute values 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, or is itself tied to. - 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 + 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. */ /*! - 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 + 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 ), - mPositionType( ptAbsolute ), - mKey( 0 ), - mValue( 0 ), - mParentAnchor( 0 ) +QCPItemPosition::QCPItemPosition( QCustomPlot* parentPlot, + QCPAbstractItem* parentItem, + const QString name ) + : QCPItemAnchor( parentPlot, parentItem, name ) + , mPositionType( ptAbsolute ) + , mKey( 0 ) + , mValue( 0 ) + , mParentAnchor( 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 + // 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 QList currentChildren( mChildren.toList() ); for( int i = 0; i < currentChildren.size(); ++i ) - currentChildren.at( i )->setParentAnchor( - 0 ); // this acts back on this anchor and child removes itself from mChildren + currentChildren.at( i )->setParentAnchor( 0 ); // this acts back on this anchor + // and child removes itself from + // mChildren // unregister as child in parent: if( mParentAnchor ) mParentAnchor->removeChild( this ); } -/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ +/* 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 + 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. + \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. + \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 + 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. + 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. */ void QCPItemPosition::setType( QCPItemPosition::PositionType type ) { if( mPositionType != 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. + // 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 recoverPixelPosition = true; if( ( mPositionType == ptPlotCoords || type == ptPlotCoords ) && ( !mKeyAxis || !mValueAxis ) ) recoverPixelPosition = false; @@ -7976,18 +9227,25 @@ void QCPItemPosition::setType( QCPItemPosition::PositionType type ) } /*! - 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 with (0, 0) being exactly on top of the parent anchor. (Hence the type + 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 with (0, 0) being exactly on top of the parent + anchor. (Hence the type shouldn't be \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 + 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. + 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 + 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. */ bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPixelPosition ) @@ -7995,7 +9253,8 @@ bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPix // 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 ); + 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: @@ -8015,12 +9274,15 @@ bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPix } 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, + // 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" + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which " + "itself depends on this position" << reinterpret_cast( parentAnchor ); return false; } @@ -8028,7 +9290,8 @@ bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPix } } - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + // if previously no parent set and PosType is still ptPlotCoords, set to + // ptAbsolute: if( !mParentAnchor && mPositionType == ptPlotCoords ) setType( ptAbsolute ); @@ -8052,14 +9315,20 @@ bool QCPItemPosition::setParentAnchor( QCPItemAnchor* parentAnchor, bool keepPix } /*! - Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type + Sets the coordinates of this QCPItemPosition. What the coordinates mean, is + defined by the type (\ref setType). - 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 + 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. \see setPixelPoint @@ -8072,7 +9341,8 @@ void QCPItemPosition::setCoords( double key, double value ) /*! \overload - Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the + 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 ) @@ -8081,8 +9351,10 @@ void QCPItemPosition::setCoords( const QPointF& pos ) } /*! - 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). + 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 */ @@ -8102,12 +9374,14 @@ QPointF QCPItemPosition::pixelPoint() const { if( mParentAnchor ) { - return QPointF( mKey * mParentPlot->viewport().width(), mValue * mParentPlot->viewport().height() ) + + return QPointF( mKey * mParentPlot->viewport().width(), + mValue * mParentPlot->viewport().height() ) + mParentAnchor->pixelPoint(); } else { - return QPointF( mKey * mParentPlot->viewport().width(), mValue * mParentPlot->viewport().height() ) + + return QPointF( mKey * mParentPlot->viewport().width(), + mValue * mParentPlot->viewport().height() ) + mParentPlot->viewport().topLeft(); } } @@ -8139,7 +9413,8 @@ QPointF QCPItemPosition::pixelPoint() const double x, y; if( mKeyAxis && mValueAxis ) { - // both key and value axis are given, translate key/value to x/y coordinates: + // both key and value axis are given, translate key/value to x/y + // coordinates: if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { x = mKeyAxis.data()->coordToPixel( mKey ); @@ -8153,7 +9428,8 @@ QPointF QCPItemPosition::pixelPoint() const } else if( mKeyAxis ) { - // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: + // only key axis is given, depending on orientation only transform x or y + // to key coordinate, other stays pixel: if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { x = mKeyAxis.data()->coordToPixel( mKey ); @@ -8167,7 +9443,8 @@ QPointF QCPItemPosition::pixelPoint() const } else if( mValueAxis ) { - // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays + // only value axis is given, depending on orientation only transform x or + // y to value coordinate, other stays // pixel: if( mValueAxis.data()->orientation() == Qt::Horizontal ) { @@ -8194,8 +9471,10 @@ QPointF QCPItemPosition::pixelPoint() const } /*! - 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 + 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 ) @@ -8205,8 +9484,10 @@ void QCPItemPosition::setAxes( QCPAxis* keyAxis, QCPAxis* 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 + 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 ) @@ -8215,11 +9496,15 @@ void QCPItemPosition::setAxisRect( QCPAxisRect* 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. + 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 + 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 @@ -8288,7 +9573,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) double newKey, newValue; if( mKeyAxis && mValueAxis ) { - // both key and value axis are given, translate point to key/value coordinates: + // both key and value axis are given, translate point to key/value + // coordinates: if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.x() ); @@ -8302,7 +9588,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) } else if( mKeyAxis ) { - // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: + // only key axis is given, depending on orientation only transform x or y + // to key coordinate, other stays pixel: if( mKeyAxis.data()->orientation() == Qt::Horizontal ) { newKey = mKeyAxis.data()->pixelToCoord( pixelPoint.x() ); @@ -8316,7 +9603,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) } else if( mValueAxis ) { - // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays + // only value axis is given, depending on orientation only transform x or + // y to value coordinate, other stays // pixel: if( mValueAxis.data()->orientation() == Qt::Horizontal ) { @@ -8349,35 +9637,48 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) /*! \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 + 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 + 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:
    QCustomPlot *\b mParentPlotA pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the + A pointer to the parent QCustomPlot instance. The parent plot is + inferred from the axes that are passed in the constructor.
    QString \b mName The 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 + The 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, + The 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)The 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 + The 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 + The 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 + 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 mSelected
    - - - - - +
    QCPItemLineA line defined by a start and an end point. May have different ending styles on each side +
    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 +
    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 +
    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 +
    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.
    - Items are by default clipped to the main axis rect. To make an item visible outside that axis + Items are by default clipped to the main axis rect. To make an item visible + outside that axis rect, disable clipping via \ref setClipToAxisRect. \section items-using Using items @@ -8387,14 +9688,17 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) QCPItemLine *line = new QCPItemLine(customPlot); customPlot->addItem(line); \endcode - by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just + 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: \code line->start->setCoords(-0.1, 0.8); line->end->setCoords(1.1, 0.2); \endcode - 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: + 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: \code line->start->setType(QCPItemPosition::ptAbsolute); line->end->setType(QCPItemPosition::ptAbsolute); @@ -8407,7 +9711,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) \section items-subclassing Creating own items - To create an own item, you implement a subclass of QCPAbstractItem. These are the pure + 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 @@ -8416,17 +9721,23 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) \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 + 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 + 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. + 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 @@ -8440,35 +9751,48 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) \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 + 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 + 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 + 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 + 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 + 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 + 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. */ @@ -8483,7 +9807,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) /*! \fn QList QCPAbstractItem::anchors() const - Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always + 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 @@ -8497,8 +9822,10 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) 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 + 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. */ @@ -8506,7 +9833,8 @@ void QCPItemPosition::setPixelPoint( const QPointF& pixelPoint ) /* 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 + 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. */ @@ -8528,18 +9856,21 @@ QCPAbstractItem::QCPAbstractItem( QCustomPlot* parentPlot ) QCPAbstractItem::~QCPAbstractItem() { - // don't delete mPositions because every position is also an anchor and thus in mAnchors + // 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 */ +/* 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 + 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 @@ -8552,7 +9883,8 @@ void QCPAbstractItem::setClipToAxisRect( bool clip ) } /*! - Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref + 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 @@ -8565,10 +9897,12 @@ void QCPAbstractItem::setClipAxisRect( QCPAxisRect* rect ) } /*! - Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. + 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, + 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 @@ -8583,16 +9917,20 @@ void QCPAbstractItem::setSelectable( bool selectable ) } /*! - Sets whether this item is selected or not. When selected, it might use a different visual + 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 + 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. + 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. + emits the \ref selectionChanged signal when \a selected is different from the + previous selection state. \see setSelectable, selectTest */ @@ -8606,11 +9944,14 @@ void QCPAbstractItem::setSelected( bool selected ) } /*! - Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by + 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 + 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 @@ -8627,11 +9968,14 @@ QCPItemPosition* QCPAbstractItem::position( const QString& name ) const } /*! - Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by + 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 + 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 @@ -8650,7 +9994,8 @@ QCPItemAnchor* QCPAbstractItem::anchor( const QString& name ) const /*! 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 + 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 @@ -8667,10 +10012,13 @@ bool QCPAbstractItem::hasAnchor( const QString& name ) const /*! \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. + 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. + If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport + rect is returned. \see draw */ @@ -8684,12 +10032,15 @@ QRect QCPAbstractItem::clipRect() const /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 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 + 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. @@ -8702,17 +10053,21 @@ void QCPAbstractItem::applyDefaultAntialiasingHint( QCPPainter* painter ) const /*! \internal - Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + 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 + 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 +double QCPAbstractItem::distSqrToLine( const QPointF& start, + const QPointF& end, + const QPointF& point ) const { QVector2D a( start ); QVector2D b( end ); @@ -8736,29 +10091,40 @@ double QCPAbstractItem::distSqrToLine( const QPointF& start, const QPointF& end, /*! \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 + 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 + 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 which were greater or equal to zero. (Because this function may return -1.0 when \a pos - doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item + 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 which were greater or equal to zero. (Because this function may return + -1.0 when \a pos + doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, + because your item wasn't hit. \see distSqrToLine */ -double QCPAbstractItem::rectSelectTest( const QRectF& rect, const QPointF& pos, bool filledRect ) const +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() ); + 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 < lines.size(); ++i ) { @@ -8779,31 +10145,40 @@ double QCPAbstractItem::rectSelectTest( const QRectF& rect, const QPointF& pos, /*! \internal - Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in + 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 + 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" + 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). + 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. + 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 + 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 @@ -8825,19 +10200,28 @@ QCPItemPosition* QCPAbstractItem::createPosition( const QString& name ) /*! \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). + 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 \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. + 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 + 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 @@ -8892,89 +10276,130 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const \image html qcp-doc-logo.png - Below is a brief overview of and guide to the classes and their relations. If you are new to - QCustomPlot and just want to start using it, it's recommended to look at the tutorials and + Below is a brief overview of and guide to the classes and their relations. If + you are new to + QCustomPlot and just want to start using it, it's recommended to look at the + tutorials and examples at http://www.qcustomplot.com/ - This documentation is especially helpful as a reference, when you're familiar with the basic - concept of how to use %QCustomPlot and you wish to learn more about specific functionality. - See the \ref classoverview "class overview" for diagrams explaining the relationships between + This documentation is especially helpful as a reference, when you're familiar + with the basic + concept of how to use %QCustomPlot and you wish to learn more about specific + functionality. + See the \ref classoverview "class overview" for diagrams explaining the + relationships between the most important classes of the QCustomPlot library. - The central widget which displays the plottables and axes on its surface is QCustomPlot. Every - QCustomPlot contains four axes by default. They can be accessed via the members \ref - QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2" - and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary - number of axes and axis rects, see the documentation of QCPAxisRect for details. + The central widget which displays the plottables and axes on its surface is + QCustomPlot. Every + QCustomPlot contains four axes by default. They can be accessed via the + members \ref + QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref + QCustomPlot::xAxis2 "xAxis2" + and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot + supports an arbitrary + number of axes and axis rects, see the documentation of QCPAxisRect for + details. \section mainpage-plottables Plottables - \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive - from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph + \a Plottables are classes that display any kind of data inside the + QCustomPlot. They all derive + from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that + displays a graph inside the plot with different line styles, scatter styles, filling etc. - Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working + Since plotting graphs is such a dominant use case, QCustomPlot has a special + interface for working with QCPGraph plottables, that makes it very easy to handle them:\n - You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph. + You create a new graph with QCustomPlot::addGraph and access them with + QCustomPlot::graph. For all other plottables, you need to use the normal plottable interface:\n First, you create an instance of the plottable you want, e.g. \code - QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, + customPlot->yAxis);\endcode add it to the customPlot: \code customPlot->addPlottable(newCurve);\endcode - and then modify the properties of the newly created plottable via the newCurve pointer. + and then modify the properties of the newly created plottable via the + newCurve pointer. - Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type - of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will - probably want to qobject_cast the returned pointer to the respective plottable subclass. (As - usual, if the cast returns zero, the plottable wasn't of that specific subclass.) + Plottables (including graphs) can be retrieved via QCustomPlot::plottable. + Since the return type + of that function is the abstract base class of all plottables, + QCPAbstractPlottable, you will + probably want to qobject_cast the returned pointer to the respective plottable + subclass. (As + usual, if the cast returns zero, the plottable wasn't of that specific + subclass.) - All further interfacing with plottables (e.g how to set data) is specific to the plottable type. - See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox, + All further interfacing with plottables (e.g how to set data) is specific to + the plottable type. + See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, + QCPStatisticalBox, QCPColorMap. \section mainpage-axes Controlling the Axes - As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2 + As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a + yAxis (left), \a xAxis2 (top), \a yAxis2 (right). - Their range is handled by the simple QCPRange class. You can set the range with the - QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic - scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely + Their range is handled by the simple QCPRange class. You can set the range + with the + QCPAxis::setRange function. By default, the axes represent a linear scale. To + set a logarithmic + scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The + logarithm base can be set freely with \ref QCPAxis::setScaleLogBase. - By default, an axis automatically creates and labels ticks in a sensible manner. See the - following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks, + By default, an axis automatically creates and labels ticks in a sensible + manner. See the + following functions for tick manipulation:\n QCPAxis::setTicks, + QCPAxis::setAutoTicks, QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels, - QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep, + QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, + QCPAxis::setTickStep, QCPAxis::setTickLength,... - Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel. + Each axis can be given an axis label (e.g. "Voltage (mV)") with + QCPAxis::setLabel. - The distance of an axis backbone to the respective viewport border is called its margin. + The distance of an axis backbone to the respective viewport border is called + its margin. Normally, the margins are calculated automatically. To change this, set - \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with - \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect(). + \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set + the margins manually with + \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref + QCustomPlot::axisRect(). \section mainpage-legend Plot Legend - Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small - layout element inside the plot which lists the plottables with an icon of the plottable - line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from + Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. + A legend is a small + layout element inside the plot which lists the plottables with an icon of the + plottable + line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be + added and removed from the main legend via \ref QCPAbstractPlottable::addToLegend and \ref - QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot - automatically adds it to the legend, too. This behaviour can be modified with the + QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to + QCustomPlot + automatically adds it to the legend, too. This behaviour can be modified with + the QCustomPlot::setAutoAddPlottableToLegend property. - The QCPLegend provides an interface to access, add and remove legend items directly, too. See - QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for + The QCPLegend provides an interface to access, add and remove legend items + directly, too. See + QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, + QCPLegend::removeItem for example. - Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a + Multiple legends are supported via the \link thelayoutsystem layout + system\endlink (as a QCPLegend simply is a normal layout element). \section mainpage-userinteraction User Interactions @@ -8983,84 +10408,129 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref QCPAxisRect::setRangeZoom) and a complete selection mechanism. - The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For + The availability of these interactions is controlled with \ref + QCustomPlot::setInteractions. For details about the interaction system, see the documentation there. - Further, QCustomPlot always emits corresponding signals, when objects are clicked or - doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick + Further, QCustomPlot always emits corresponding signals, when objects are + clicked or + doubleClicked. See \ref QCustomPlot::plottableClick, \ref + QCustomPlot::plottableDoubleClick and \ref QCustomPlot::axisClick for example. \section mainpage-items Items - Apart from plottables there is another category of plot objects that are important: Items. The - base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that - it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel - coordinates or placed at a relative position on an axis rect. Further, it usually doesn't + Apart from plottables there is another category of plot objects that are + important: Items. The + base class of all items is QCPAbstractItem. An item sets itself apart from + plottables in that + it's not necessarily bound to any axes. This means it may also be positioned + in absolute pixel + coordinates or placed at a relative position on an axis rect. Further, it + usually doesn't represent data directly, but acts as decoration, emphasis, description etc. - Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For - example, you could place the head of an arrow at a fixed plot coordinate, so it always points to - some important area in the plot. The tail of the arrow can be anchored to a text item which - always resides in the top center of the axis rect, independent of where the user drags the axis - ranges. This way the arrow stretches and turns so it always points from the label to the + Multiple items can be arranged in a parent-child-hierarchy allowing for + dynamical behaviour. For + example, you could place the head of an arrow at a fixed plot coordinate, so + it always points to + some important area in the plot. The tail of the arrow can be anchored to a + text item which + always resides in the top center of the axis rect, independent of where the + user drags the axis + ranges. This way the arrow stretches and turns so it always points from the + label to the specified plot coordinate, without any further code necessary. - For a more detailed introduction, see the QCPAbstractItem documentation, and from there the + For a more detailed introduction, see the QCPAbstractItem documentation, and + from there the documentations of the individual built-in items, to find out how to use them. \section mainpage-layoutelements Layout elements and layouts - QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like - the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by + QCustomPlot uses an internal layout system to provide dynamic sizing and + positioning of objects like + the axis rect(s), legends and the plot title. They are all based on \ref + QCPLayoutElement and are arranged by placing them inside a \ref QCPLayout. - Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink. + Details on this topic are given on the dedicated page about \link + thelayoutsystem the layout system\endlink. \section mainpage-performancetweaks Performance Tweaks - Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick - lines can cause a significant slow down. If you notice this in your application, here are some - thoughts on how to increase performance. By far the most time is spent in the drawing functions, - specifically the drawing of graphs. For maximum performance, consider the following (most + Although QCustomPlot is quite fast, some features like translucent fills, + antialiasing and thick + lines can cause a significant slow down. If you notice this in your + application, here are some + thoughts on how to increase performance. By far the most time is spent in the + drawing functions, + specifically the drawing of graphs. For maximum performance, consider the + following (most recommended/effective measures first): - \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However - QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >= - 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8. - \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true. - \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying - "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster") - before creating the QApplication object. (Only available for Qt versions before 5.0) - \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem - opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only - available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the - quality of antialiasing, but extremely increase performance especially with alpha - (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note - however, that the maximum frame rate might be constrained by the vertical sync frequency of your - monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots - (where the potential framerate is far above 60 frames per second), OpenGL acceleration might - achieve numerically lower frame rates than the other graphics systems, because they are not + \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt + 4.7.4. However + QPainter was broken and drawing pixel precise things, e.g. scatters, isn't + possible with Qt >= + 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt + 4.8. + \li To increase responsiveness during dragging, consider setting \ref + QCustomPlot::setNoAntialiasingOnDrag to true. + \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by + supplying + "-graphicssystem raster" as command line argument or calling + QApplication::setGraphicsSystem("raster") + before creating the QApplication object. (Only available for Qt versions + before 5.0) + \li On all operating systems, use OpenGL hardware acceleration by supplying + "-graphicssystem + opengl" as command line argument or calling + QApplication::setGraphicsSystem("opengl") (Only + available for Qt versions before 5.0). If OpenGL is available, this will + slightly decrease the + quality of antialiasing, but extremely increase performance especially with + alpha + (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing + surface. Note + however, that the maximum frame rate might be constrained by the vertical sync + frequency of your + monitor (VSync can be disabled in the graphics card driver configuration). So + for simple plots + (where the potential framerate is far above 60 frames per second), OpenGL + acceleration might + achieve numerically lower frame rates than the other graphics systems, because + they are not capped at the VSync frequency. \li Avoid any kind of alpha (transparency), especially in fills \li Avoid lines with a pen width greater than one - \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements) - \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if + \li Avoid any kind of antialiasing, especially in graph lines (see \ref + QCustomPlot::setNotAntialiasedElements) + \li Avoid repeatedly setting the complete data set with \ref + QCPGraph::setData. Use \ref QCPGraph::addData instead, if most data points stay unchanged, e.g. in a running measurement. - \li Set the \a copy parameter of the setData functions to false, so only pointers get - transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000) + \li Set the \a copy parameter of the setData functions to false, so only + pointers get + transferred. (Relevant only if preparing data maps with a large number of + points, i.e. over 10000) \section mainpage-flags Preprocessor Define Flags - QCustomPlot understands some preprocessor defines that are useful for debugging and compilation: + QCustomPlot understands some preprocessor defines that are useful for + debugging and compilation:
    \c QCUSTOMPLOT_COMPILE_LIBRARY -
    Define this flag when you compile QCustomPlot as a shared library (.so/.dll) +
    Define this flag when you compile QCustomPlot as a shared library + (.so/.dll)
    \c QCUSTOMPLOT_USE_LIBRARY -
    Define this flag before including the header, when using QCustomPlot as a shared library +
    Define this flag before including the header, when using QCustomPlot as a + shared library
    \c QCUSTOMPLOT_CHECK_DATA -
    If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw. - This means they will give qDebug output when you plot \e inf or \e nan values, they will not +
    If this flag is defined, the QCustomPlot plottables will perform data + validity checks on every redraw. + This means they will give qDebug output when you plot \e inf or \e nan + values, they will not fix your data.
    @@ -9068,13 +10538,17 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \page classoverview Class Overview - The following diagrams may help to gain a deeper understanding of the relationships between classes that make up - the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown. + The following diagrams may help to gain a deeper understanding of the + relationships between classes that make up + the QCustomPlot library. The diagrams are not exhaustive, so only the classes + deemed most relevant are shown. \section classoverview-relations Class Relationship Diagram - \image html RelationOverview.png "Overview of most important classes and their relations" + \image html RelationOverview.png "Overview of most important classes and their + relations" \section classoverview-inheritance Class Inheritance Tree - \image html InheritanceOverview.png "Inheritance tree of most important classes" + \image html InheritanceOverview.png "Inheritance tree of most important + classes" */ @@ -9084,7 +10558,8 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \class QCustomPlot - \brief The central class of the library. This is the QWidget which displays the plot and + \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 @@ -9095,22 +10570,30 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 + 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. + 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, savePdf etc.) the viewport is temporarily modified + Only when saving to a file (see \ref savePng, 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 + Returns the top level layout of this QCustomPlot instance. It is a \ref + QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ @@ -9119,15 +10602,18 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) - This signal is emitted when the QCustomPlot receives a mouse double click 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 + 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. */ @@ -9135,13 +10621,18 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + 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 + \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. */ @@ -9149,8 +10640,10 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + 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. */ @@ -9158,26 +10651,32 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + 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) +/*! \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 + \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) +/*! \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 + \a event is the mouse event that caused the click and \a plottable is the + plottable that received the click. \see plottableClick @@ -9187,61 +10686,76 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + \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) +/*! \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 + \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) +/*! \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 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) +/*! \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 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) +/*! \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 + \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) +/*! \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 + \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 @@ -9251,17 +10765,20 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + \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) +/*! \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 + \a event is the mouse event that caused the click and \a title is the plot + title that received the click. \see titleClick @@ -9269,25 +10786,33 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \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 + 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 + 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 the documentation of \ref setInteractions for details about the selection + mechanism. - \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends + \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 + 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 + 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 @@ -9295,10 +10820,12 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::afterReplot() - This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref + 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 + 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 @@ -9311,12 +10838,18 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + 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. */ @@ -9324,57 +10857,85 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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. */ @@ -9384,28 +10945,28 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const 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 ) + : 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 ); @@ -9426,7 +10987,8 @@ QCustomPlot::QCustomPlot( QWidget* parent ) // 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 + mPlotLayout->setParent( this ); // important because if parent is QWidget, + // QCPLayout::sizeConstraintsChanged will // call QWidget::updateGeometry mPlotLayout->setLayer( "main" ); QCPAxisRect* defaultAxisRect = new QCPAxisRect( this, true ); @@ -9468,23 +11030,31 @@ QCustomPlot::~QCustomPlot() } mCurrentLayer = 0; - qDeleteAll( mLayers ); // don't use removeLayer, because it would prevent the last layer to be removed + 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. + 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 + 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 + 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 + if an element in \a antialiasedElements is already set in \ref + setNotAntialiasedElements, it is removed from there. \see setNotAntialiasedElements @@ -9493,13 +11063,15 @@ void QCustomPlot::setAntialiasedElements( const QCP::AntialiasedElements& antial { mAntialiasedElements = antialiasedElements; - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + // 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. + Sets whether the specified \a antialiasedElement is forcibly drawn + antialiased. See \ref setAntialiasedElements for details. @@ -9512,59 +11084,73 @@ void QCustomPlot::setAntialiasedElement( QCP::AntialiasedElement antialiasedElem else if( enabled && !mAntialiasedElements.testFlag( antialiasedElement ) ) mAntialiasedElements |= antialiasedElement; - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + // 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 + 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 + 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 + 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 + 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& notAntialiasedElements ) +void QCustomPlot::setNotAntialiasedElements( + const QCP::AntialiasedElements& notAntialiasedElements ) { mNotAntialiasedElements = notAntialiasedElements; - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + // 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. + 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 ) +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: + // 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 + 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 @@ -9575,55 +11161,86 @@ void QCustomPlot::setAutoAddPlottableToLegend( bool on ) } /*! - Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction + 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, + 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 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 + 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 + 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(). + 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 + 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 + 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 + 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 + 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 + \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 @@ -9649,14 +11266,20 @@ void QCustomPlot::setInteraction( const QCP::Interaction& interaction, bool enab } /*! - Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or + 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 + 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 @@ -9667,10 +11290,14 @@ void QCustomPlot::setSelectionTolerance( int 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 + 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 @@ -9681,7 +11308,8 @@ void QCustomPlot::setNoAntialiasingOnDrag( bool enabled ) } /*! - Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. + Sets the plotting hints for this QCustomPlot instance as an \a or combination + of QCP::PlottingHint. \see setPlottingHint */ @@ -9710,7 +11338,8 @@ void QCustomPlot::setPlottingHint( QCP::PlottingHint hint, bool enabled ) /*! 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 + 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. @@ -9723,10 +11352,13 @@ void QCustomPlot::setMultiSelectModifier( Qt::KeyboardModifier 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. + 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 + 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 ) @@ -9737,16 +11369,22 @@ void QCustomPlot::setViewport( const QRect& rect ) } /*! - Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn + 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, + 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 + 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 @@ -9760,13 +11398,18 @@ void QCustomPlot::setBackground( const QPixmap& pm ) /*! 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 + 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. + 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 */ @@ -9777,10 +11420,12 @@ void QCustomPlot::setBackground( const QBrush& brush ) /*! \overload - Allows setting the background pixmap of the viewport, whether it shall be scaled and how it + 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 + \see setBackground(const QPixmap &pm), setBackgroundScaled, + setBackgroundScaledMode */ void QCustomPlot::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode ) { @@ -9791,12 +11436,16 @@ void QCustomPlot::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatio } /*! - 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 + 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.) + 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 */ @@ -9806,8 +11455,10 @@ void QCustomPlot::setBackgroundScaled( bool 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. + 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 */ @@ -9819,7 +11470,8 @@ void QCustomPlot::setBackgroundScaledMode( Qt::AspectRatioMode 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 + There is an overloaded version of this function with no parameter which + returns the last added plottable, see QCustomPlot::plottable() \see plottableCount, addPlottable @@ -9839,7 +11491,8 @@ QCPAbstractPlottable* QCustomPlot::plottable( int index ) /*! \overload - Returns the last plottable that was added with \ref addPlottable. If there are no plottables in + Returns the last plottable that was added with \ref addPlottable. If there are + no plottables in the plot, returns 0. \see plottableCount, addPlottable @@ -9855,11 +11508,15 @@ QCPAbstractPlottable* QCustomPlot::plottable() } /*! - Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to - the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. + 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 + 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 @@ -9868,14 +11525,14 @@ bool QCustomPlot::addPlottable( QCPAbstractPlottable* plottable ) { if( mPlottables.contains( plottable ) ) { - qDebug() << Q_FUNC_INFO - << "plottable already added to this QCustomPlot:" << reinterpret_cast( 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 ); + qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" + << reinterpret_cast( plottable ); return false; } @@ -9886,14 +11543,16 @@ bool QCustomPlot::addPlottable( QCPAbstractPlottable* plottable ) // 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 + 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). + Removes the specified plottable from the plot and, if necessary, from the + legend (QCustomPlot::legend). Returns true on success. @@ -9934,7 +11593,8 @@ bool QCustomPlot::removePlottable( int index ) } /*! - Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). + Removes all plottables from the plot (and the QCustomPlot::legend, if + necessary). Returns the number of plottables removed. @@ -9959,11 +11619,14 @@ int QCustomPlot::plottableCount() const } /*! - Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. + 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. + There is a convenience function if you're only interested in selected graphs, + see \ref selectedGraphs. - \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected + \see setInteractions, QCPAbstractPlottable::setSelectable, + QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedPlottables() const { @@ -9977,8 +11640,10 @@ QList QCustomPlot::selectedPlottables() const } /*! - 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 + 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 @@ -9991,17 +11656,22 @@ QList QCustomPlot::selectedPlottables() const 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 + 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 + 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 + .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 ); @@ -10029,7 +11699,8 @@ bool QCustomPlot::hasPlottable( QCPAbstractPlottable* plottable ) const /*! 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 + There is an overloaded version of this function with no parameter which + returns the last created graph, see QCustomPlot::graph() \see graphCount, addGraph @@ -10049,7 +11720,8 @@ QCPGraph* QCustomPlot::graph( int index ) const /*! \overload - Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, + Returns the last graph, that was created with \ref addGraph. If there are no + graphs in the plot, returns 0. \see graphCount, addGraph @@ -10065,11 +11737,14 @@ QCPGraph* QCustomPlot::graph() const } /*! - 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 + 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 + \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. @@ -10084,13 +11759,15 @@ QCPGraph* QCustomPlot::addGraph( QCPAxis* keyAxis, QCPAxis* 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)"; + 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"; + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this " + "QCustomPlot as parent"; return 0; } @@ -10108,8 +11785,10 @@ QCPGraph* QCustomPlot::addGraph( QCPAxis* keyAxis, QCPAxis* valueAxis ) } /*! - 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 + 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. @@ -10159,12 +11838,15 @@ int QCustomPlot::graphCount() const } /*! - Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. + 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, + 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 + \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, + QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedGraphs() const { @@ -10180,7 +11862,8 @@ QList QCustomPlot::selectedGraphs() const /*! 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 + There is an overloaded version of this function with no parameter which + returns the last added item, see QCustomPlot::item() \see itemCount, addItem @@ -10200,7 +11883,8 @@ QCPAbstractItem* QCustomPlot::item( int index ) const /*! \overload - Returns the last item, that was added with \ref addItem. If there are no items in the plot, + Returns the last item, that was added with \ref addItem. If there are no items + in the plot, returns 0. \see itemCount, addItem @@ -10218,7 +11902,8 @@ QCPAbstractItem* QCustomPlot::item() const /*! 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 + 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 @@ -10232,7 +11917,8 @@ bool QCustomPlot::addItem( QCPAbstractItem* item ) } else { - qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" + qDebug() << Q_FUNC_INFO << "item either already in list or not created " + "with this QCustomPlot as parent:" << reinterpret_cast( item ); return false; } @@ -10301,9 +11987,11 @@ int QCustomPlot::itemCount() const } /*! - Returns a list of the selected items. If no items are currently selected, the list is empty. + Returns a list of the selected items. If no items are currently selected, the + list is empty. - \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected + \see setInteractions, QCPAbstractItem::setSelectable, + QCPAbstractItem::setSelected */ QList QCustomPlot::selectedItems() const { @@ -10317,12 +12005,15 @@ QList QCustomPlot::selectedItems() const } /*! - Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref + 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 + 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 + 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. @@ -10332,18 +12023,23 @@ QList QCustomPlot::selectedItems() const 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 + 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 + 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 + 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 ) @@ -10368,7 +12064,8 @@ bool QCustomPlot::hasItem( QCPAbstractItem* item ) const } /*! - Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is + 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. @@ -10413,10 +12110,12 @@ QCPLayer* QCustomPlot::currentLayer() const } /*! - Sets the layer with the specified \a name to be the current layer. All layerables (\ref + 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. + Returns true on success, i.e. if there is a layer with the specified \a name + in the QCustomPlot. Layer names are case-sensitive. @@ -10439,7 +12138,8 @@ bool QCustomPlot::setCurrentLayer( const QString& name ) 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. + Returns true on success, i.e. when \a layer is a valid layer in the + QCustomPlot. \see addLayer, moveLayer, removeLayer */ @@ -10447,7 +12147,8 @@ bool QCustomPlot::setCurrentLayer( QCPLayer* layer ) { if( !mLayers.contains( layer ) ) { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); + qDebug() << Q_FUNC_INFO + << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); return false; } @@ -10466,26 +12167,32 @@ int QCustomPlot::layerCount() const } /*! - 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. + 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 + 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. + 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 ) +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 ); + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" + << reinterpret_cast( otherLayer ); return false; } if( layer( name ) ) @@ -10503,11 +12210,15 @@ bool QCustomPlot::addLayer( const QString& name, QCPLayer* otherLayer, QCustomPl /*! 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. + 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 + 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. @@ -10518,7 +12229,8 @@ bool QCustomPlot::removeLayer( QCPLayer* layer ) { if( !mLayers.contains( layer ) ) { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); + qDebug() << Q_FUNC_INFO + << "layer not a layer of this QCustomPlot:" << reinterpret_cast( layer ); return false; } if( mLayers.size() < 2 ) @@ -10527,12 +12239,15 @@ bool QCustomPlot::removeLayer( QCPLayer* layer ) return false; } - // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + // 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 ); + 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) + 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 ); @@ -10542,7 +12257,8 @@ bool QCustomPlot::removeLayer( QCPLayer* layer ) for( int i = 0; i < children.size(); ++i ) children.at( i )->moveToLayer( targetLayer, false ); } - // if removed layer is current layer, change current layer to layer below/above: + // if removed layer is current layer, change current layer to layer + // below/above: if( layer == mCurrentLayer ) setCurrentLayer( targetLayer ); // remove layer: @@ -10553,25 +12269,30 @@ bool QCustomPlot::removeLayer( QCPLayer* layer ) } /*! - Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or + 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 + 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 ) +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 ); + 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 ); + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" + << reinterpret_cast( otherLayer ); return false; } @@ -10597,9 +12318,12 @@ int QCustomPlot::axisRectCount() const /*! 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). + 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 */ @@ -10646,10 +12370,12 @@ QList QCustomPlot::axisRects() const } /*! - Returns the layout element at pixel position \a pos. If there is no element at that position, + 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 + 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 @@ -10675,10 +12401,12 @@ QCPLayoutElement* QCustomPlot::layoutElementAt( const QPointF& pos ) const } /*! - Returns the axes that currently have selected parts, i.e. whose selection state is not \ref + Returns the axes that currently have selected parts, i.e. whose selection + state is not \ref QCPAxis::spNone. - \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, + \see selectedPlottables, selectedLegends, setInteractions, + QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ QList QCustomPlot::selectedAxes() const @@ -10697,10 +12425,12 @@ QList QCustomPlot::selectedAxes() const } /*! - Returns the legends that currently have selected parts, i.e. whose selection state is not \ref + Returns the legends that currently have selected parts, i.e. whose selection + state is not \ref QCPLegend::spNone. - \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, + \see selectedPlottables, selectedAxes, setInteractions, + QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ QList QCustomPlot::selectedLegends() const @@ -10731,13 +12461,17 @@ QList QCustomPlot::selectedLegends() const } /*! - Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. + 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 + 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 + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, + selectedLegends */ void QCustomPlot::deselectAll() { @@ -10749,16 +12483,23 @@ void QCustomPlot::deselectAll() } /*! - 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, + 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). + 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 + 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 ) @@ -10768,13 +12509,15 @@ void QCustomPlot::replot( QCustomPlot::RefreshPriority refreshPriority ) mReplotting = true; emit beforeReplot(); - mPaintBuffer.fill( mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent ); + 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 + 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 ); @@ -10793,9 +12536,11 @@ void QCustomPlot::replot( QCustomPlot::RefreshPriority refreshPriority ) } /*! - Rescales the axes such that all plottables (like graphs) in the plot are fully visible. + 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 + 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 @@ -10811,39 +12556,59 @@ void QCustomPlot::rescaleAxes( bool 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 + 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 + \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 + 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 + \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 + \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. + \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 */ @@ -10860,7 +12625,8 @@ bool QCustomPlot::savePdf( const QString& fileName, Q_UNUSED( noCosmeticPen ) Q_UNUSED( width ) Q_UNUSED( height ) - qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; + 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 ) @@ -10893,7 +12659,8 @@ bool QCustomPlot::savePdf( const QString& fileName, 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 + mBackgroundBrush.color().alpha() > + 0 ) // draw pdf background color if not white/transparent printpainter.fillRect( viewport(), mBackgroundBrush ); draw( &printpainter ); printpainter.end(); @@ -10905,113 +12672,176 @@ bool QCustomPlot::savePdf( const QString& fileName, } /*! - 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. + 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 + 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 + 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 + \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 + 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. + 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 + 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 + 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 ) +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. + 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 + 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 + 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 + \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 + 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 + 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 + 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 ) +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. + 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 + 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 + 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 + \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 + 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 + 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 @@ -11023,10 +12853,14 @@ bool QCustomPlot::saveBmp( const QString& fileName, int width, int height, doubl /*! \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 + 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 @@ -11046,7 +12880,8 @@ QSize QCustomPlot::sizeHint() const /*! \internal - Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but + 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 ) @@ -11058,8 +12893,10 @@ void QCustomPlot::paintEvent( QPaintEvent* event ) /*! \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 + 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 ) @@ -11067,14 +12904,18 @@ 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 + 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 + 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 @@ -11104,7 +12945,8 @@ void QCustomPlot::mouseDoubleClickEvent( QMouseEvent* event ) if( QCPLayoutElement* el = layoutElementAt( event->pos() ) ) el->mouseDoubleClickEvent( event ); - // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the + // call release event of affected layout element (as in mouseReleaseEvent, + // since the mouseDoubleClick replaces the // second release event in double click case): if( mMouseEventElement ) { @@ -11112,13 +12954,15 @@ void QCustomPlot::mouseDoubleClickEvent( QMouseEvent* event ) mMouseEventElement = 0; } - // QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a + // 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 + 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 @@ -11126,7 +12970,8 @@ void QCustomPlot::mouseDoubleClickEvent( QMouseEvent* event ) 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 + 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: @@ -11141,7 +12986,8 @@ void QCustomPlot::mousePressEvent( QMouseEvent* event ) 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 + 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 @@ -11159,14 +13005,19 @@ void QCustomPlot::mouseMoveEvent( QMouseEvent* event ) /*! \internal - Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. + 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 + 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 + 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 @@ -11176,7 +13027,8 @@ 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( ( mMousePressPos - event->pos() ).manhattanLength() < + 5 ) // determine whether it was a click operation { if( event->button() == Qt::LeftButton ) { @@ -11184,8 +13036,8 @@ void QCustomPlot::mouseReleaseEvent( QMouseEvent* event ) QVariant details; QCPLayerable* clickedLayerable = layerableAt( event->pos(), true, &details ); bool selectionStateChanged = false; - bool additive = - mInteractions.testFlag( QCP::iMultiSelect ) && event->modifiers().testFlag( mMultiSelectModifier ); + bool additive = mInteractions.testFlag( QCP::iMultiSelect ) && + event->modifiers().testFlag( mMultiSelectModifier ); // deselect all other layerables if not additive selection: if( !additive ) { @@ -11193,7 +13045,8 @@ void QCustomPlot::mouseReleaseEvent( QMouseEvent* event ) { foreach( QCPLayerable* layerable, layer->children() ) { - if( layerable != clickedLayerable && mInteractions.testFlag( layerable->selectionCategory() ) ) + if( layerable != clickedLayerable && + mInteractions.testFlag( layerable->selectionCategory() ) ) { bool selChanged = false; layerable->deselectEvent( &selChanged ); @@ -11217,8 +13070,9 @@ void QCustomPlot::mouseReleaseEvent( QMouseEvent* event ) // 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 + 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 ) ) @@ -11248,7 +13102,8 @@ void QCustomPlot::mouseReleaseEvent( QMouseEvent* event ) /*! \internal - Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then + 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. */ @@ -11265,10 +13120,14 @@ void QCustomPlot::wheelEvent( QWheelEvent* 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). + 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 ) { @@ -11312,15 +13171,21 @@ void QCustomPlot::draw( QCPPainter* painter ) 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 + 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 + 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 + 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 @@ -11338,10 +13203,11 @@ void QCustomPlot::drawBackground( QCPPainter* painter ) 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() ); + mScaledBackgroundPixmap = mBackgroundPixmap.scaled( mViewport.size(), mBackgroundScaledMode, + Qt::SmoothTransformation ); + painter->drawPixmap( + mViewport.topLeft(), mScaledBackgroundPixmap, + QRect( 0, 0, mViewport.width(), mViewport.height() ) & mScaledBackgroundPixmap.rect() ); } else { @@ -11353,8 +13219,10 @@ void QCustomPlot::drawBackground( QCPPainter* painter ) /*! \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. + 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 ) { @@ -11367,12 +13235,14 @@ void QCustomPlot::axisRemoved( QCPAxis* axis ) 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 + // 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 + 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 ) @@ -11383,8 +13253,10 @@ void QCustomPlot::legendRemoved( QCPLegend* legend ) /*! \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 + 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 @@ -11395,17 +13267,25 @@ void QCustomPlot::updateLayerIndices() const /*! \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 + 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. + \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 +QCPLayerable* QCustomPlot::layerableAt( const QPointF& pos, + bool onlySelectable, + QVariant* selectionDetails ) const { for( int layerIndex = mLayers.size() - 1; layerIndex >= 0; --layerIndex ) { @@ -11433,12 +13313,16 @@ QCPLayerable* QCustomPlot::layerableAt( const QPointF& pos, bool onlySelectable, } /*! - 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 + 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 + 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 @@ -11460,14 +13344,16 @@ bool QCustomPlot::saveRastered( const QString& fileName, /*! 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 + 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, + // 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 ) @@ -11484,10 +13370,11 @@ QPixmap QCustomPlot::toPixmap( int width, int height, double scale ) 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 + 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() ) @@ -11497,7 +13384,8 @@ QPixmap QCustomPlot::toPixmap( int width, int height, double scale ) 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 + 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 ); @@ -11519,19 +13407,24 @@ QPixmap QCustomPlot::toPixmap( int width, int height, double scale ) /*! 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 + 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 + \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. + 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, + // 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 ) @@ -11550,7 +13443,8 @@ void QCustomPlot::toPainter( QCPPainter* painter, int width, int height ) QRect oldViewport = viewport(); setViewport( QRect( 0, 0, newWidth, newHeight ) ); painter->setMode( QCPPainter::pmNoCaching ); - // warning: the following is different in toPixmap, because a solid background color is applied there via + // warning: the following is different in toPixmap, because a solid + // background color is applied there via // QPixmap::fill // here, we need to do this via QPainter::fillRect. if( mBackgroundBrush.style() != Qt::NoBrush ) @@ -11569,37 +13463,51 @@ void QCustomPlot::toPainter( QCPPainter* painter, int width, int height ) /*! \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 a \ref QCPColorMap::setGradient "setGradient" method which - takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) + This class describes a color gradient which can be used to encode data with + color. For example, + QCPColorMap and QCPColorScale have a \ref QCPColorMap::setGradient + "setGradient" method which + takes 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. + 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 + 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 + 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.: \code colorMap->setGradient(QCPColorGradient::gpHot); \endcode - 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. + 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 + 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 ) + : mLevelCount( 350 ) + , mColorInterpolation( ciRGB ) + , mPeriodic( false ) + , mColorBufferInvalidated( true ) { mColorBuffer.fill( qRgb( 0, 0, 0 ), mLevelCount ); loadPreset( preset ); @@ -11608,12 +13516,14 @@ QCPColorGradient::QCPColorGradient( GradientPreset preset ) /* undocumented operator */ bool QCPColorGradient::operator==( const QCPColorGradient& other ) const { - return ( ( other.mLevelCount == this->mLevelCount ) && ( other.mColorInterpolation == this->mColorInterpolation ) && + 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 + 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 @@ -11633,11 +13543,14 @@ void QCPColorGradient::setLevelCount( int n ) } /*! - 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 + 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 + 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 @@ -11649,8 +13562,10 @@ void QCPColorGradient::setColorStops( const QMap& colorStops ) } /*! - 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. + 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 */ @@ -11661,10 +13576,12 @@ void QCPColorGradient::setColorStopAt( double position, const QColor& color ) } /*! - Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be + 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, + 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 ) @@ -11678,17 +13595,23 @@ void QCPColorGradient::setColorInterpolation( QCPColorGradient::ColorInterpolati /*! 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. + 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 + 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 + 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 ) @@ -11697,15 +13620,22 @@ void QCPColorGradient::setPeriodic( bool 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 + 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 + 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, @@ -11736,7 +13666,8 @@ void QCPColorGradient::colorize( const double* data, { for( int i = 0; i < n; ++i ) { - int index = (int)( ( data[dataIndexFactor * i] - range.lower ) * posToIndexFactor ) % mLevelCount; + int index = + (int)( ( data[dataIndexFactor * i] - range.lower ) * posToIndexFactor ) % mLevelCount; if( index < 0 ) index += mLevelCount; scanLine[i] = mColorBuffer.at( index ); @@ -11761,9 +13692,9 @@ void QCPColorGradient::colorize( const double* data, { for( int i = 0; i < n; ++i ) { - int index = - (int)( qLn( data[dataIndexFactor * i] / range.lower ) / qLn( range.upper / range.lower ) * mLevelCount ) % - mLevelCount; + int index = (int)( qLn( data[dataIndexFactor * i] / range.lower ) / + qLn( range.upper / range.lower ) * mLevelCount ) % + mLevelCount; if( index < 0 ) index += mLevelCount; scanLine[i] = mColorBuffer.at( index ); @@ -11773,7 +13704,8 @@ void QCPColorGradient::colorize( const double* data, { for( int i = 0; i < n; ++i ) { - int index = qLn( data[dataIndexFactor * i] / range.lower ) / qLn( range.upper / range.lower ) * mLevelCount; + int index = qLn( data[dataIndexFactor * i] / range.lower ) / + qLn( range.upper / range.lower ) * mLevelCount; if( index < 0 ) index = 0; else if( index >= mLevelCount ) @@ -11786,11 +13718,15 @@ void QCPColorGradient::colorize( const double* data, /*! \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. + 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 + 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 ) @@ -11820,7 +13756,8 @@ QRgb QCPColorGradient::color( double position, const QCPRange& range, bool logar } /*! - Clears the current color stops and loads the specified \a preset. A preset consists of predefined + 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: @@ -11942,7 +13879,8 @@ void QCPColorGradient::clearColorStops() } /*! - Returns an inverted gradient. The inverted gradient has all properties as this \ref + 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 @@ -11951,15 +13889,18 @@ QCPColorGradient QCPColorGradient::inverted() const { QCPColorGradient result( *this ); result.clearColorStops(); - for( QMap::const_iterator it = mColorStops.constBegin(); it != mColorStops.constEnd(); ++it ) + 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. + 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() { @@ -11972,19 +13913,24 @@ void QCPColorGradient::updateColorBuffer() { double position = i * indexToPosFactor; QMap::const_iterator it = mColorStops.lowerBound( position ); - if( it == mColorStops.constEnd() ) // position is on or after last stop, use color of last stop + 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 + 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 + 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 + double t = + ( position - low.key() ) / ( high.key() - low.key() ); // interpolation factor 0..1 switch( mColorInterpolation ) { case ciRGB: @@ -12010,9 +13956,10 @@ void QCPColorGradient::updateColorBuffer() 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(); + mColorBuffer[i] = + QColor::fromHsvF( hue, ( 1 - t ) * lowHsv.saturationF() + t * highHsv.saturationF(), + ( 1 - t ) * lowHsv.valueF() + t * highHsv.valueF() ) + .rgb(); break; } } @@ -12037,37 +13984,55 @@ void QCPColorGradient::updateColorBuffer() /*! \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 + 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 + 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 + 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 + 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 + 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 + 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 +
    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.
    */ @@ -12075,7 +14040,8 @@ void QCPColorGradient::updateColorBuffer() /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const - Returns the inset layout of this axis rect. It can be used to place other layout elements (or + 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 @@ -12083,93 +14049,106 @@ void QCPColorGradient::updateColorBuffer() /*! \fn int QCPAxisRect::left() const - Returns the pixel position of the left border of this axis rect. Margins are not taken into + 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 + 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 + 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 + 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 + 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 + 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 + 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, + 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 + 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 + 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 + 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 + 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 + 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 ) + : 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 ); @@ -12224,7 +14203,8 @@ int QCPAxisRect::axisCount( QCPAxis::AxisType type ) const } /*! - Returns the axis with the given \a index on the axis rect side specified with \a type. + Returns the axis with the given \a index on the axis rect side specified with + \a type. \see axisCount, axes */ @@ -12245,7 +14225,8 @@ QCPAxis* QCPAxisRect::axis( QCPAxis::AxisType type, int index ) const /*! 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 + \a types may be a single \ref QCPAxis::AxisType or an or-combination, + to get the axes of multiple sides. \see axis @@ -12271,7 +14252,7 @@ QList QCPAxisRect::axes( QCPAxis::AxisTypes types ) const QList QCPAxisRect::axes() const { QList result; - QHashIterator > it( mAxes ); + QHashIterator> it( mAxes ); while( it.hasNext() ) { it.next(); @@ -12283,8 +14264,10 @@ QList QCPAxisRect::axes() const /*! Adds a new axis to the axis rect side specified with \a type, and returns it. - 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 initialized to \ref + 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 + initialized to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox @@ -12292,7 +14275,8 @@ QList QCPAxisRect::axes() const QCPAxis* QCPAxisRect::addAxis( QCPAxis::AxisType type ) { QCPAxis* newAxis = new QCPAxis( this, type ); - if( mAxes[type].size() > 0 ) // multiple axes on one side, add half-bar axis ending to additional axes with offset + 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 ) ); @@ -12303,8 +14287,10 @@ QCPAxis* QCPAxisRect::addAxis( QCPAxis::AxisType type ) } /*! - 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. + 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. @@ -12333,18 +14319,21 @@ QList QCPAxisRect::addAxes( QCPAxis::AxisTypes types ) */ bool QCPAxisRect::removeAxis( QCPAxis* axis ) { - // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis + // don't access axis->axisType() to provide safety when axis is an invalid + // pointer, rather go through all axis // containers: - QHashIterator > it( mAxes ); + 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) + 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; @@ -12355,8 +14344,10 @@ bool QCPAxisRect::removeAxis( QCPAxis* axis ) } /*! - 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 + 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) @@ -12375,10 +14366,13 @@ bool QCPAxisRect::removeAxis( QCPAxis* axis ) \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. + 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. + 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 ) { @@ -12452,14 +14446,16 @@ void QCPAxisRect::setupFullAxesBox( bool connectRanges ) /*! 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 + 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 + // Note: don't append all QCPAxis::plottables() into a list, because we might + // get duplicate entries QList result; for( int i = 0; i < mParentPlot->mPlottables.size(); ++i ) { @@ -12473,14 +14469,16 @@ QList QCPAxisRect::plottables() const /*! 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 + 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 + // Note: don't append all QCPAxis::graphs() into a list, because we might get + // duplicate entries QList result; for( int i = 0; i < mParentPlot->mGraphs.size(); ++i ) { @@ -12494,16 +14492,19 @@ QList QCPAxisRect::graphs() const /*! 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 + 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 + 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 + // 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; itemId < mParentPlot->mItems.size(); ++itemId ) @@ -12516,7 +14517,8 @@ QList QCPAxisRect::items() const QList positions = mParentPlot->mItems.at( itemId )->positions(); for( int posId = 0; posId < positions.size(); ++posId ) { - if( positions.at( posId )->axisRect() == this || positions.at( posId )->keyAxis()->axisRect() == this || + if( positions.at( posId )->axisRect() == this || + positions.at( posId )->keyAxis()->axisRect() == this || positions.at( posId )->valueAxis()->axisRect() == this ) { result.append( mParentPlot->mItems.at( itemId ) ); @@ -12528,11 +14530,14 @@ QList QCPAxisRect::items() const } /*! - This method is called automatically upon replot and doesn't need to be called by users of + 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 + 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 ) @@ -12557,7 +14562,8 @@ void QCPAxisRect::update( UpdatePhase phase ) break; } - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from + // pass update call on to inset layout (doesn't happen automatically, because + // QCPAxisRect doesn't derive from // QCPLayout): mInsetLayout->update( phase ); } @@ -12588,19 +14594,26 @@ void QCPAxisRect::draw( QCPPainter* 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 + 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, + 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 + 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) + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush + &brush) */ void QCPAxisRect::setBackground( const QPixmap& pm ) { @@ -12610,11 +14623,14 @@ void QCPAxisRect::setBackground( const QPixmap& pm ) /*! \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 + 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 + 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. @@ -12628,10 +14644,12 @@ void QCPAxisRect::setBackground( const QBrush& brush ) /*! \overload - Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it + 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 + \see setBackground(const QPixmap &pm), setBackgroundScaled, + setBackgroundScaledMode */ void QCPAxisRect::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode ) { @@ -12642,12 +14660,16 @@ void QCPAxisRect::setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatio } /*! - 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 + 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.) + 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 */ @@ -12657,8 +14679,10 @@ void QCPAxisRect::setBackgroundScaled( bool 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. + 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 ) @@ -12697,17 +14721,21 @@ double QCPAxisRect::rangeZoomFactor( Qt::Orientation orientation ) } /*! - Sets which axis orientation may be range dragged by the user with mouse interaction. + 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 | + 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 + 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, setNoAntialiasingOnDrag @@ -12718,16 +14746,22 @@ void QCPAxisRect::setRangeDrag( Qt::Orientations 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 + 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 | + 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 + 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 @@ -12738,7 +14772,8 @@ void QCPAxisRect::setRangeZoom( Qt::Orientations orientations ) } /*! - Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging + Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse + range dragging on the QCustomPlot widget. \see setRangeZoomAxes @@ -12750,9 +14785,12 @@ void QCPAxisRect::setRangeDragAxes( QCPAxis* horizontal, QCPAxis* 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). + 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 */ @@ -12763,13 +14801,18 @@ void QCPAxisRect::setRangeZoomAxes( QCPAxis* horizontal, QCPAxis* 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 + 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 + 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 ) @@ -12790,18 +14833,25 @@ void QCPAxisRect::setRangeZoomFactor( double factor ) /*! \internal - Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a + 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 + 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 + 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 + 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 @@ -12821,24 +14871,29 @@ void QCPAxisRect::drawBackground( QCPPainter* painter ) 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(), mScaledBackgroundPixmap, - QRect( 0, 0, mRect.width(), mRect.height() ) & mScaledBackgroundPixmap.rect() ); + mScaledBackgroundPixmap = mBackgroundPixmap.scaled( mRect.size(), mBackgroundScaledMode, + Qt::SmoothTransformation ); + painter->drawPixmap( + mRect.topLeft(), mScaledBackgroundPixmap, + QRect( 0, 0, mRect.width(), mRect.height() ) & mScaledBackgroundPixmap.rect() ); } else { - painter->drawPixmap( mRect.topLeft(), mBackgroundPixmap, QRect( 0, 0, mRect.width(), mRect.height() ) ); + painter->drawPixmap( mRect.topLeft(), 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). + 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 + 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. @@ -12849,14 +14904,17 @@ void QCPAxisRect::updateAxesOffset( QCPAxis::AxisType 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 + 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; i < axesList.size(); ++i ) { int offset = axesList.at( i - 1 )->offset() + 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( 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(); @@ -12874,7 +14932,8 @@ int QCPAxisRect::calculateAutoMargin( QCP::MarginSide side ) updateAxesOffset( QCPAxis::marginSideToAxisType( side ) ); - // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + // 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(); @@ -12884,19 +14943,23 @@ int QCPAxisRect::calculateAutoMargin( QCP::MarginSide side ) /*! \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 + 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 + 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) + 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; @@ -12919,7 +14982,8 @@ void QCPAxisRect::mousePressEvent( QMouseEvent* event ) /*! \internal - Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a + 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 @@ -12935,15 +14999,17 @@ void QCPAxisRect::mouseMoveEvent( QMouseEvent* event ) { if( rangeDragHorzAxis->mScaleType == QCPAxis::stLinear ) { - double diff = - rangeDragHorzAxis->pixelToCoord( mDragStart.x() ) - rangeDragHorzAxis->pixelToCoord( event->pos().x() ); - rangeDragHorzAxis->setRange( mDragStartHorzRange.lower + diff, mDragStartHorzRange.upper + diff ); + 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 ); + double diff = rangeDragHorzAxis->pixelToCoord( mDragStart.x() ) / + rangeDragHorzAxis->pixelToCoord( event->pos().x() ); + rangeDragHorzAxis->setRange( mDragStartHorzRange.lower * diff, + mDragStartHorzRange.upper * diff ); } } } @@ -12953,15 +15019,17 @@ void QCPAxisRect::mouseMoveEvent( QMouseEvent* event ) { if( rangeDragVertAxis->mScaleType == QCPAxis::stLinear ) { - double diff = - rangeDragVertAxis->pixelToCoord( mDragStart.y() ) - rangeDragVertAxis->pixelToCoord( event->pos().y() ); - rangeDragVertAxis->setRange( mDragStartVertRange.lower + diff, mDragStartVertRange.upper + diff ); + 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 ); + double diff = rangeDragVertAxis->pixelToCoord( mDragStart.y() ) / + rangeDragVertAxis->pixelToCoord( event->pos().y() ); + rangeDragVertAxis->setRange( mDragStartVertRange.lower * diff, + mDragStartVertRange.upper * diff ); } } } @@ -12988,16 +15056,25 @@ void QCPAxisRect::mouseReleaseEvent( QMouseEvent* event ) /*! \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. + 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 + 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 ) @@ -13013,13 +15090,15 @@ void QCPAxisRect::wheelEvent( QWheelEvent* event ) { factor = pow( mRangeZoomFactorHorz, wheelSteps ); if( mRangeZoomHorzAxis.data() ) - mRangeZoomHorzAxis.data()->scaleRange( factor, mRangeZoomHorzAxis.data()->pixelToCoord( event->pos().x() ) ); + mRangeZoomHorzAxis.data()->scaleRange( + factor, mRangeZoomHorzAxis.data()->pixelToCoord( event->pos().x() ) ); } if( mRangeZoom.testFlag( Qt::Vertical ) ) { factor = pow( mRangeZoomFactorVert, wheelSteps ); if( mRangeZoomVertAxis.data() ) - mRangeZoomVertAxis.data()->scaleRange( factor, mRangeZoomVertAxis.data()->pixelToCoord( event->pos().y() ) ); + mRangeZoomVertAxis.data()->scaleRange( + factor, mRangeZoomVertAxis.data()->pixelToCoord( event->pos().y() ) ); } mParentPlot->replot(); } @@ -13033,10 +15112,12 @@ void QCPAxisRect::wheelEvent( QWheelEvent* event ) /*! \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 + 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 + 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: @@ -13049,7 +15130,8 @@ void QCPAxisRect::wheelEvent( QWheelEvent* event ) A pointer to the parent QCPLegend. QFont \b mFont - The generic font of the item. You should use this font for all or at least the most prominent text of the + The generic font of the item. You should use this font for all or at + least the most prominent text of the item. @@ -13059,25 +15141,28 @@ void QCPAxisRect::wheelEvent( QWheelEvent* event ) /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) - This signal is emitted when the selection state of this legend item has changed, either by user + 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. + 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 ) + : QCPLayoutElement( parent->parentPlot() ) + , mParentLegend( parent ) + , mFont( parent->font() ) + , mTextColor( parent->textColor() ) + , mSelectedFont( parent->selectedFont() ) + , mSelectedTextColor( parent->selectedTextColor() ) + , mSelectable( true ) + , mSelected( false ) { setLayer( "legend" ); setMargins( QMargins( 8, 2, 8, 2 ) ); @@ -13104,7 +15189,8 @@ void QCPAbstractLegendItem::setTextColor( const QColor& color ) } /*! - When this legend item is selected, \a font is used to draw generic text, instead of the normal + 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 @@ -13115,7 +15201,8 @@ void QCPAbstractLegendItem::setSelectedFont( const QFont& font ) } /*! - When this legend item is selected, \a color is used to draw generic text, instead of the normal + 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 @@ -13142,7 +15229,8 @@ void QCPAbstractLegendItem::setSelectable( bool selectable ) /*! 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 + 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 @@ -13157,12 +15245,15 @@ void QCPAbstractLegendItem::setSelected( bool selected ) } /* inherits documentation from base class */ -double QCPAbstractLegendItem::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +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 ) ) ) + if( onlySelectable && + ( !mSelectable || !mParentLegend->selectableParts().testFlag( QCPLegend::spItems ) ) ) return -1; if( mRect.contains( pos.toPoint() ) ) @@ -13217,27 +15308,40 @@ void QCPAbstractLegendItem::deselectEvent( bool* selectionStateChanged ) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableLegendItem - \brief A legend item representing a plottable with an icon and the plottable name. + \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 + 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 + 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 + 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 + 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 + 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. */ @@ -13246,8 +15350,10 @@ void QCPAbstractLegendItem::deselectEvent( bool* selectionStateChanged ) 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. + 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 ) @@ -13256,7 +15362,8 @@ QCPPlottableLegendItem::QCPPlottableLegendItem( QCPLegend* parent, QCPAbstractPl /*! \internal - Returns the pen that shall be used to draw the icon border, taking into account the selection + 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 @@ -13266,7 +15373,8 @@ QPen QCPPlottableLegendItem::getIconBorderPen() const /*! \internal - Returns the text color that shall be used to draw text, taking into account the selection state + Returns the text color that shall be used to draw text, taking into account + the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const @@ -13276,7 +15384,8 @@ QColor QCPPlottableLegendItem::getTextColor() const /*! \internal - Returns the font that shall be used to draw text, taking into account the selection state of this + Returns the font that shall be used to draw text, taking into account the + selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const @@ -13286,8 +15395,10 @@ QFont QCPPlottableLegendItem::getFont() const /*! \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 + 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 ) @@ -13297,15 +15408,14 @@ void QCPPlottableLegendItem::draw( QCPPainter* painter ) 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 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() ); + 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 ); @@ -13322,7 +15432,8 @@ void QCPPlottableLegendItem::draw( QCPPainter* painter ) /*! \internal - Calculates and returns the size of this item. This includes the icon, the text and the padding in + Calculates and returns the size of this item. This includes the icon, the text + and the padding in between. */ QSize QCPPlottableLegendItem::minimumSizeHint() const @@ -13333,10 +15444,12 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const 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() ); + 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; } @@ -13347,25 +15460,39 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /*! \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. + 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 + 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 + 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. + 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 */ @@ -13380,9 +15507,11 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /* end of documentation of signals */ /*! - Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. + 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 + Note that by default, QCustomPlot already contains a legend ready to be used + as QCustomPlot::legend */ QCPLegend::QCPLegend() @@ -13418,7 +15547,8 @@ QCPLegend::~QCPLegend() /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { - // check whether any legend elements selected, if yes, add spItems to return value + // check whether any legend elements selected, if yes, add spItems to return + // value bool hasSelectedItems = false; for( int i = 0; i < itemCount(); ++i ) { @@ -13451,8 +15581,10 @@ void QCPLegend::setBrush( const QBrush& 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 + 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. @@ -13470,8 +15602,10 @@ void QCPLegend::setFont( const QFont& font ) } /*! - 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 + 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. @@ -13506,8 +15640,10 @@ void QCPLegend::setIconSize( int width, int 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 + 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 ) @@ -13516,7 +15652,8 @@ void QCPLegend::setIconTextPadding( int padding ) } /*! - Sets the pen used to draw a border around each legend icon. Legend items that draw an + 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. @@ -13527,11 +15664,14 @@ void QCPLegend::setIconBorderPen( const QPen& pen ) } /*! - Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + 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 + 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 @@ -13546,37 +15686,49 @@ void QCPLegend::setSelectableParts( const SelectableParts& selectable ) } /*! - 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 + 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 + 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 + 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. + 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. + 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, + \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 + 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"; + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be " + "unset with this function"; newSelected &= ~spItems; } if( mSelectedParts.testFlag( spItems ) && @@ -13594,7 +15746,8 @@ void QCPLegend::setSelectedParts( const SelectableParts& selected ) } /*! - When the legend box is selected, this pen is used to draw the border instead of the normal pen + 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 @@ -13605,7 +15758,8 @@ void QCPLegend::setSelectedBorderPen( const QPen& pen ) } /*! - Sets the pen legend items will use to draw their icon borders, when they are selected. + Sets the pen legend items will use to draw their icon borders, when they are + selected. \see setSelectedParts, setSelectableParts, setSelectedFont */ @@ -13615,7 +15769,8 @@ void QCPLegend::setSelectedIconBorderPen( const QPen& pen ) } /*! - When the legend box is selected, this brush is used to draw the legend background instead of the normal brush + 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 @@ -13643,7 +15798,8 @@ void QCPLegend::setSelectedFont( const QFont& font ) } /*! - Sets the default text color that is used by legend items when they are selected. + 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. @@ -13670,7 +15826,8 @@ QCPAbstractLegendItem* QCPLegend::item( int index ) const } /*! - Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + 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 @@ -13711,7 +15868,8 @@ bool QCPLegend::hasItem( QCPAbstractLegendItem* item ) const } /*! - Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref + 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. @@ -13725,7 +15883,8 @@ bool QCPLegend::hasItemWithPlottable( const QCPAbstractPlottable* plottable ) co /*! 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. + 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. */ @@ -13783,7 +15942,8 @@ void QCPLegend::clearItems() } /*! - Returns the legend items that are currently selected. If no items are selected, + Returns the legend items that are currently selected. If no items are + selected, the list is empty. \see QCPAbstractLegendItem::setSelected, setSelectable @@ -13804,12 +15964,15 @@ QList QCPLegend::selectedItems() const /*! \internal - A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + 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 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 + 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. @@ -13822,7 +15985,8 @@ void QCPLegend::applyDefaultAntialiasingHint( QCPPainter* painter ) const /*! \internal - Returns the pen used to paint the border of the legend, taking into account the selection state + 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 @@ -13832,7 +15996,8 @@ QPen QCPLegend::getBorderPen() const /*! \internal - Returns the brush used to paint the background of the legend, taking into account the selection + 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 @@ -13842,7 +16007,8 @@ QBrush QCPLegend::getBrush() const /*! \internal - Draws the legend box with the provided \a painter. The individual legend items are layerables + 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 ) @@ -13871,7 +16037,10 @@ double QCPLegend::selectTest( const QPointF& pos, bool onlySelectable, QVariant* } /* inherits documentation from base class */ -void QCPLegend::selectEvent( QMouseEvent* event, bool additive, const QVariant& details, bool* selectionStateChanged ) +void QCPLegend::selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ) { Q_UNUSED( event ) mSelectedParts = selectedParts(); // in case item selection has changed @@ -13879,9 +16048,12 @@ void QCPLegend::selectEvent( QMouseEvent* event, bool additive, const QVariant& { 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) + : 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; } @@ -13925,17 +16097,22 @@ void QCPLegend::parentPlotInitialized( QCustomPlot* parentPlot ) /*! \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 + 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: \code - customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect - customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title")); + customPlot->plotLayout()->insertRow(0); // inserts an empty row above the + default axis rect + customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your + Plot Title")); \endcode - 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 + 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. */ @@ -13944,7 +16121,8 @@ void QCPLegend::parentPlotInitialized( QCustomPlot* parentPlot ) /*! \fn void QCPPlotTitle::selectionChanged(bool selected) - This signal is emitted when the selection state has changed to \a selected, either by user + 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 @@ -13953,48 +16131,55 @@ void QCPLegend::parentPlotInitialized( QCustomPlot* parentPlot ) /* end documentation of signals */ /*! - Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). + 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). + 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( "sans serif", 13 * 1.5, QFont::Bold ) ), - mTextColor( Qt::black ), - mSelectedFont( QFont( "sans serif", 13 * 1.6, QFont::Bold ) ), - mSelectedTextColor( Qt::blue ), - mSelectable( false ), - mSelected( false ) + : QCPLayoutElement( parentPlot ) + , mFont( QFont( "sans serif", 13 * 1.5, QFont::Bold ) ) + , mTextColor( Qt::black ) + , mSelectedFont( QFont( "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 ); + 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. + 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 ) + : 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( "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". + Sets the text that will be displayed to \a text. Multiple lines can be created + by insertion of "\n". \see setFont, setTextColor */ @@ -14024,7 +16209,8 @@ void QCPPlotTitle::setTextColor( const QColor& color ) } /*! - Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). + Sets the \a font of the title text that will be used if the plot title is + selected (\ref setSelected). \see setFont */ @@ -14034,7 +16220,8 @@ void QCPPlotTitle::setSelectedFont( const QFont& font ) } /*! - Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). + Sets the \a color of the title text that will be used if the plot title is + selected (\ref setSelected). \see setTextColor */ @@ -14046,7 +16233,8 @@ void QCPPlotTitle::setSelectedTextColor( const QColor& 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 + 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 ) @@ -14059,10 +16247,12 @@ void QCPPlotTitle::setSelectable( bool selectable ) } /*! - Sets the selection state of this plot title to \a selected. If the selection has changed, \ref + 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 + Note that this function can change the selection state independently of the + current \ref setSelectable state. */ void QCPPlotTitle::setSelected( bool selected ) @@ -14152,7 +16342,8 @@ double QCPPlotTitle::selectTest( const QPointF& pos, bool onlySelectable, QVaria /*! \internal - Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to + 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 @@ -14162,7 +16353,8 @@ QFont QCPPlotTitle::mainFont() const /*! \internal - Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to + 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 @@ -14177,37 +16369,50 @@ QColor QCPPlotTitle::mainTextColor() const /*! \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". + 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. + 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 + 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 + 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 \code colorScale->axis()->setAutoTickCount(3); \endcode - Placing a color scale next to the main axis rect works like with any other layout element: + Placing a color scale next to the main axis rect works like with any other + layout element: \code QCPColorScale *colorScale = new QCPColorScale(customPlot); customPlot->plotLayout()->addElement(0, 1, colorScale); colorScale->setLabel("Some Label Text"); \endcode - 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 + 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 + 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: \code QCPMarginGroup *group = new QCPMarginGroup(customPlot); @@ -14215,10 +16420,14 @@ QColor QCPPlotTitle::mainTextColor() const customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group); \endcode - 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 + 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. \ref setMinimumMargins(QMargins(6, 0, 6, 0)). */ @@ -14227,15 +16436,22 @@ QColor QCPPlotTitle::mainTextColor() const /*! \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 + 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. + 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 */ @@ -14268,15 +16484,19 @@ QColor QCPPlotTitle::mainTextColor() const 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 ) ) + : 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) + 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 ) ); } @@ -14329,10 +16549,13 @@ bool QCPColorScale::rangeZoom() const } /*! - Sets at which side of the color scale the axis is placed, and thus also its orientation. + 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 + 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 ) @@ -14355,12 +16578,14 @@ void QCPColorScale::setType( QCPAxis::AxisType type ) labelTransfer = mColorAxis.data()->label(); logBaseTransfer = mColorAxis.data()->scaleLogBase(); mColorAxis.data()->setLabel( "" ); - disconnect( mColorAxis.data(), SIGNAL( rangeChanged( QCPRange ) ), this, SLOT( setDataRange( QCPRange ) ) ); + disconnect( mColorAxis.data(), SIGNAL( rangeChanged( QCPRange ) ), this, + SLOT( setDataRange( QCPRange ) ) ); disconnect( mColorAxis.data(), SIGNAL( scaleTypeChanged( QCPAxis::ScaleType ) ), this, SLOT( setDataScaleType( QCPAxis::ScaleType ) ) ); } - foreach( QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight - << QCPAxis::atBottom << QCPAxis::atTop ) + foreach( QCPAxis::AxisType atype, QList() + << QCPAxis::atLeft << QCPAxis::atRight + << QCPAxis::atBottom << QCPAxis::atTop ) { mAxisRect.data()->axis( atype )->setTicks( atype == mType ); mAxisRect.data()->axis( atype )->setTickLabels( atype == mType ); @@ -14368,25 +16593,34 @@ void QCPColorScale::setType( QCPAxis::AxisType type ) // 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()->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 ) ) ); + 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 ); + 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. + 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 + 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 @@ -14403,11 +16637,14 @@ void QCPColorScale::setDataRange( const QCPRange& dataRange ) } /*! - Sets the scale type of the color scale, i.e. whether values are linearly associated with colors + 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 + 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 @@ -14428,7 +16665,8 @@ void QCPColorScale::setDataScaleType( QCPAxis::ScaleType scaleType ) /*! 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. + It is equivalent to calling QCPColorMap::setGradient on any of the connected + color maps. \see setDataRange, setDataScaleType */ @@ -14444,7 +16682,8 @@ void QCPColorScale::setGradient( const QCPColorGradient& gradient ) } /*! - Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on + 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 ) @@ -14459,7 +16698,8 @@ void QCPColorScale::setLabel( const QString& str ) } /*! - Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed + Sets the width (or height, for horizontal color scales) the bar where the + gradient is displayed will have. */ void QCPColorScale::setBarWidth( int width ) @@ -14488,7 +16728,8 @@ void QCPColorScale::setRangeDrag( bool enabled ) } /*! - Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. + 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. @@ -14523,7 +16764,8 @@ QList QCPColorScale::colorMaps() const } /*! - Changes the data range such that all color maps associated with this color scale are fully mapped + 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 @@ -14533,7 +16775,8 @@ 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 + 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 ); @@ -14572,12 +16815,15 @@ void QCPColorScale::rescaleDataRange( bool onlyVisibleMaps ) } 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 + 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 + 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; @@ -14612,18 +16858,21 @@ void QCPColorScale::update( UpdatePhase phase ) 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() ); + 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(), + 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(), + setMinimumSize( mBarWidth + mAxisRect.data()->margins().left() + + mAxisRect.data()->margins().right() + margins().left() + + margins().right(), 0 ); } break; @@ -14706,13 +16955,14 @@ void QCPColorScale::wheelEvent( QWheelEvent* event ) Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate( QCPColorScale* parentColorScale ) - : QCPAxisRect( parentColorScale->parentPlot(), true ), - mParentColorScale( parentColorScale ), - mGradientImageInvalidated( true ) + : QCPAxisRect( parentColorScale->parentPlot(), true ) + , mParentColorScale( parentColorScale ) + , mGradientImageInvalidated( true ) { setParentLayerable( parentColorScale ); setMinimumMargins( QMargins( 0, 0, 0, 0 ) ); - foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop + << QCPAxis::atLeft << QCPAxis::atRight ) { axis( type )->setVisible( true ); @@ -14732,26 +16982,32 @@ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate( QCPColorScale* paren 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 ) ) ); + 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, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + // 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, QList() << QCPAxis::atBottom << QCPAxis::atTop + << QCPAxis::atLeft << QCPAxis::atRight ) - connect( parentColorScale, SIGNAL( layerChanged( QCPLayer* ) ), axis( type ), SLOT( setLayer( QCPLayer* ) ) ); + 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. + 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 ) { @@ -14763,9 +17019,11 @@ void QCPColorScaleAxisRectPrivate::draw( QCPPainter* painter ) if( mParentColorScale->mColorAxis ) { mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && - ( mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop ); + ( mParentColorScale->type() == QCPAxis::atBottom || + mParentColorScale->type() == QCPAxis::atTop ); mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && - ( mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight ); + ( mParentColorScale->type() == QCPAxis::atLeft || + mParentColorScale->type() == QCPAxis::atRight ); } painter->drawImage( rect(), mGradientImage.mirrored( mirrorHorz, mirrorVert ) ); @@ -14774,8 +17032,10 @@ void QCPColorScaleAxisRectPrivate::draw( QCPPainter* 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. + 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() { @@ -14795,7 +17055,8 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() QVector pixels; for( int y = 0; y < h; ++y ) pixels.append( reinterpret_cast( mGradientImage.scanLine( y ) ) ); - mParentColorScale->mGradient.colorize( data.constData(), QCPRange( 0, n - 1 ), pixels.first(), n ); + mParentColorScale->mGradient.colorize( data.constData(), QCPRange( 0, n - 1 ), pixels.first(), + n ); for( int y = 1; y < h; ++y ) memcpy( pixels.at( y ), pixels.first(), n * sizeof( QRgb ) ); } @@ -14807,7 +17068,8 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() for( int y = 0; y < h; ++y ) { QRgb* pixels = reinterpret_cast( mGradientImage.scanLine( y ) ); - const QRgb lineColor = mParentColorScale->mGradient.color( data[h - 1 - y], QCPRange( 0, n - 1 ) ); + const QRgb lineColor = + mParentColorScale->mGradient.color( data[h - 1 - y], QCPRange( 0, n - 1 ) ); for( int x = 0; x < w; ++x ) pixels[x] = lineColor; } @@ -14817,13 +17079,15 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() /*! \internal - This slot is connected to the selectionChanged signals of the four axes in the constructor. It + This slot is connected to the selectionChanged signals of the four axes in the + constructor. It synchronizes the selection state of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectionChanged( QCPAxis::SelectableParts selectedParts ) { // axis bases of four axes shall always (de-)selected synchronously: - foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop + << QCPAxis::atLeft << QCPAxis::atRight ) { if( QCPAxis* senderAxis = qobject_cast( sender() ) ) @@ -14842,13 +17106,15 @@ void QCPColorScaleAxisRectPrivate::axisSelectionChanged( QCPAxis::SelectablePart /*! \internal - This slot is connected to the selectableChanged signals of the four axes in the constructor. It + 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: - foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft + foreach( QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop + << QCPAxis::atLeft << QCPAxis::atRight ) { if( QCPAxis* senderAxis = qobject_cast( sender() ) ) @@ -14889,15 +17155,26 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged( QCPAxis::SelectablePar 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 ) + : 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. + 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 ) + : key( key ) + , value( value ) + , keyErrorPlus( 0 ) + , keyErrorMinus( 0 ) + , valueErrorPlus( 0 ) + , valueErrorMinus( 0 ) { } @@ -14910,30 +17187,42 @@ QCPData::QCPData( double key, double value ) \image html QCPGraph.png - Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting + Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and + the resulting instance is 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 + 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 + 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. \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). + 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. + 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 + 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, QCPLegend::addGraph @@ -14943,25 +17232,33 @@ QCPData::QCPData( double key, double value ) /*! \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 + 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 + 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 + 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. + 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 ) +QCPGraph::QCPGraph( QCPAxis* keyAxis, QCPAxis* valueAxis ) + : QCPAbstractPlottable( keyAxis, valueAxis ) { mData = new QCPDataMap; @@ -14987,11 +17284,14 @@ QCPGraph::~QCPGraph() /*! 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 + 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 + 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 ) @@ -15009,8 +17309,10 @@ void QCPGraph::setData( QCPDataMap* data, bool copy ) /*! \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 + 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 ) @@ -15028,13 +17330,17 @@ void QCPGraph::setData( const QVector& key, const QVector& value } /*! - 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. + 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 + 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. + For asymmetrical errors (plus different from minus), see the overloaded + version of this function. */ void QCPGraph::setDataValueError( const QVector& key, const QVector& value, @@ -15057,11 +17363,14 @@ void QCPGraph::setDataValueError( const QVector& key, /*! \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 + 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 + 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, @@ -15086,13 +17395,16 @@ void QCPGraph::setDataValueError( const QVector& key, } /*! - Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + 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 + 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. + For asymmetrical errors (plus different from minus), see the overloaded + version of this function. */ void QCPGraph::setDataKeyError( const QVector& key, const QVector& value, @@ -15115,11 +17427,14 @@ void QCPGraph::setDataKeyError( const QVector& key, /*! \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 + 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 + 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, @@ -15144,13 +17459,17 @@ void QCPGraph::setDataKeyError( const QVector& key, } /*! - 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. + 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 + 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. + For asymmetrical errors (plus different from minus), see the overloaded + version of this function. */ void QCPGraph::setDataBothError( const QVector& key, const QVector& value, @@ -15177,12 +17496,16 @@ void QCPGraph::setDataBothError( const QVector& key, /*! \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 + 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. + 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 + 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, @@ -15213,7 +17536,8 @@ void QCPGraph::setDataBothError( const QVector& key, } /*! - Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to + 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 @@ -15224,7 +17548,8 @@ void QCPGraph::setLineStyle( LineStyle ls ) } /*! - Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter + 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). @@ -15236,9 +17561,12 @@ void QCPGraph::setScatterStyle( const QCPScatterStyle& 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 + 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 @@ -15266,12 +17594,15 @@ void QCPGraph::setErrorBarSize( double size ) } /*! - If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but + 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 + 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 + 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 @@ -15282,10 +17613,12 @@ void QCPGraph::setErrorBarSkipSymbol( bool enabled ) } /*! - Sets the target graph for filling the area between this graph and \a targetGraph with the current + 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 + 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 @@ -15311,34 +17644,54 @@ void QCPGraph::setChannelFillGraph( QCPGraph* 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. + 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 + 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" + \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. + 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" + \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, + 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 + 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 ) @@ -15349,7 +17702,8 @@ void QCPGraph::setAdaptiveSampling( bool 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 + 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 @@ -15362,7 +17716,8 @@ void QCPGraph::addData( const QCPDataMap& 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 + 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 @@ -15373,9 +17728,11 @@ void QCPGraph::addData( const QCPData& data ) } /*! \overload - Adds the provided single data point as \a key and \a value pair to the current data. + 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 + 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 @@ -15389,9 +17746,11 @@ void QCPGraph::addData( double key, double value ) } /*! \overload - Adds the provided data points as \a key and \a value pairs to the current data. + 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 + 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 @@ -15434,7 +17793,8 @@ void QCPGraph::removeDataAfter( double key ) /*! 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 + 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 @@ -15451,8 +17811,10 @@ void QCPGraph::removeData( double fromKey, double toKey ) /*! \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 + 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 @@ -15491,10 +17853,12 @@ double QCPGraph::selectTest( const QPointF& pos, bool onlySelectable, QVariant* /*! \overload - Allows to define whether error bars are taken into consideration when determining the new axis + Allows to define whether error bars are taken into consideration when + determining the new axis range. - \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes + \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, + QCustomPlot::rescaleAxes */ void QCPGraph::rescaleAxes( bool onlyEnlarge, bool includeErrorBars ) const { @@ -15504,14 +17868,16 @@ void QCPGraph::rescaleAxes( bool onlyEnlarge, bool includeErrorBars ) const /*! \overload - Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration + 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 + // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only + // change // that getKeyRange is passed the includeErrorBars value. if( mData->isEmpty() ) return; @@ -15545,14 +17911,16 @@ void QCPGraph::rescaleKeyAxis( bool onlyEnlarge, bool includeErrorBars ) const /*! \overload - Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration + 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 + // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only + // change // is that getValueRange is passed the includeErrorBars value. if( mData->isEmpty() ) return; @@ -15645,17 +18013,19 @@ void QCPGraph::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const 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 ); + 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 + 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() ) @@ -15667,8 +18037,8 @@ void QCPGraph::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const mScatterStyle.pixmap().size().height() > rect.height() ) ) { QCPScatterStyle scaledStyle( mScatterStyle ); - scaledStyle.setPixmap( - scaledStyle.pixmap().scaled( rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation ) ); + scaledStyle.setPixmap( scaledStyle.pixmap().scaled( rect.size().toSize(), Qt::KeepAspectRatio, + Qt::SmoothTransformation ) ); scaledStyle.applyTo( painter, mPen ); scaledStyle.drawShape( painter, QRectF( rect ).center() ); } @@ -15682,20 +18052,29 @@ void QCPGraph::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const /*! \internal - This function branches out to the line style specific "get(...)PlotData" functions, according to + 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 + \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. + \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, + \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, + getStepRightPlotData, getStepCenterPlotData, getImpulsePlotData */ void QCPGraph::getPlotData( QVector* lineData, QVector* scatterData ) const @@ -15725,12 +18104,16 @@ void QCPGraph::getPlotData( QVector* lineData, QVector* scatte /*! \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 + 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. + 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 */ @@ -15741,16 +18124,21 @@ void QCPGraph::getScatterPlotData( QVector* scatterData ) const /*! \internal - Places the raw data points needed for a normal linearly connected graph in \a linePixelData. + 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 + 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 +void QCPGraph::getLinePlotData( QVector* linePixelData, + QVector* scatterData ) const { QCPAxis* keyAxis = mKeyAxis.data(); QCPAxis* valueAxis = mValueAxis.data(); @@ -15767,9 +18155,9 @@ void QCPGraph::getLinePlotData( QVector* linePixelData, 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->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: @@ -15793,16 +18181,21 @@ void QCPGraph::getLinePlotData( QVector* linePixelData, QVector* linePixelData, QVector* scatterData ) const +void QCPGraph::getStepLeftPlotData( QVector* linePixelData, + QVector* scatterData ) const { QCPAxis* keyAxis = mKeyAxis.data(); QCPAxis* valueAxis = mValueAxis.data(); @@ -15819,9 +18212,10 @@ void QCPGraph::getStepLeftPlotData( QVector* linePixelData, 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->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: @@ -15857,16 +18251,21 @@ void QCPGraph::getStepLeftPlotData( QVector* linePixelData, QVector* linePixelData, QVector* scatterData ) const +void QCPGraph::getStepRightPlotData( QVector* linePixelData, + QVector* scatterData ) const { QCPAxis* keyAxis = mKeyAxis.data(); QCPAxis* valueAxis = mValueAxis.data(); @@ -15883,9 +18282,10 @@ void QCPGraph::getStepRightPlotData( QVector* linePixelData, 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->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: @@ -15921,16 +18321,21 @@ void QCPGraph::getStepRightPlotData( QVector* linePixelData, QVector* linePixelData, QVector* scatterData ) const +void QCPGraph::getStepCenterPlotData( QVector* linePixelData, + QVector* scatterData ) const { QCPAxis* keyAxis = mKeyAxis.data(); QCPAxis* valueAxis = mValueAxis.data(); @@ -15947,9 +18352,10 @@ void QCPGraph::getStepCenterPlotData( QVector* linePixelData, 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->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 ) @@ -15998,14 +18404,18 @@ void QCPGraph::getStepCenterPlotData( QVector* linePixelData, QVector* linePixelData, QVector* scatterData ) const +void QCPGraph::getImpulsePlotData( QVector* linePixelData, + QVector* scatterData ) const { QCPAxis* keyAxis = mKeyAxis.data(); QCPAxis* valueAxis = mValueAxis.data(); @@ -16022,7 +18432,8 @@ void QCPGraph::getImpulsePlotData( QVector* linePixelData, QVector lineData; getPreparedData( &lineData, scatterData ); - linePixelData->resize( lineData.size() * 2 ); // no need to reserve 2 extra points because impulse plot has no fill + 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 ) @@ -16057,12 +18468,16 @@ void QCPGraph::getImpulsePlotData( QVector* linePixelData, QVector* lineData ) const /*! \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" + 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 @@ -16149,10 +18567,14 @@ void QCPGraph::drawScatterPlot( QCPPainter* painter, QVector* scatterDa /*! \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. + 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 */ @@ -16180,8 +18602,10 @@ void QCPGraph::drawLinePlot( QCPPainter* painter, QVector* lineData ) c } */ - // 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 && + // 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 ) ) { @@ -16197,7 +18621,8 @@ void QCPGraph::drawLinePlot( QCPPainter* painter, QVector* lineData ) c /*! \internal - Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was + 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 @@ -16218,15 +18643,20 @@ void QCPGraph::drawImpulsePlot( QCPPainter* painter, QVector* 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 + 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 + 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. + 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 { @@ -16239,23 +18669,27 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc } // 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 + 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 + // 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() ) ); + 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( mAdaptiveSampling && dataCount >= maxCount ) // use adaptive sampling only + // if there are at least two + // points per pixel on average { if( lineData ) { @@ -16264,29 +18698,36 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator currentIntervalFirstPoint = 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 + 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 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) + 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 + ++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.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; @@ -16296,47 +18737,57 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc } else // new pixel interval started { - if( intervalDataCount >= 2 ) // last pixel had multiple data points, consolidate them to a cluster + 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 ) ); + 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 ) ); + 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 ) ); + 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 ) ); + currentIntervalStartKey = + keyAxis->pixelToCoord( (int)( keyAxis->coordToPixel( it.key() ) + reversedRound ) ); if( keyEpsilonVariable ) - keyEpsilon = qAbs( - currentIntervalStartKey - - keyAxis->pixelToCoord( keyAxis->coordToPixel( currentIntervalStartKey ) + 1.0 * reversedFactor ) ); + 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( 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 ) ); + 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 ) ); + lineData->append( + QCPData( currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value ) ); } if( scatterData ) @@ -16350,35 +18801,44 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc 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 + 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) + 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 + ++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.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 ) + 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 ) + else if( it.value().value > maxValue && it.value().value > valueMinRange && + it.value().value < valueMaxRange ) { maxValue = it.value().value; maxValueIt = it; @@ -16389,19 +18849,23 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc { 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 + // 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 ) ); + 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 + 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 ) + intervalIt.value().value > valueMinRange && + intervalIt.value().value < valueMaxRange ) scatterData->append( intervalIt.value() ); ++c; ++intervalIt; @@ -16413,11 +18877,13 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc minValue = it.value().value; maxValue = it.value().value; currentIntervalStart = it; - currentIntervalStartKey = keyAxis->pixelToCoord( (int)( keyAxis->coordToPixel( it.key() ) + reversedRound ) ); + currentIntervalStartKey = + keyAxis->pixelToCoord( (int)( keyAxis->coordToPixel( it.key() ) + reversedRound ) ); if( keyEpsilonVariable ) - keyEpsilon = qAbs( - currentIntervalStartKey - - keyAxis->pixelToCoord( keyAxis->coordToPixel( currentIntervalStartKey ) + 1.0 * reversedFactor ) ); + keyEpsilon = + qAbs( currentIntervalStartKey - + keyAxis->pixelToCoord( keyAxis->coordToPixel( currentIntervalStartKey ) + + 1.0 * reversedFactor ) ); intervalDataCount = 1; } ++it; @@ -16425,12 +18891,15 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc // 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 + // 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 ) ); + 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 + 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 ) @@ -16447,7 +18916,8 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc scatterData->append( currentIntervalStart.value() ); } } - else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters + else // don't use adaptive sampling algorithm, transfer points one-to-one + // from the map into the output parameters { QVector* dataVector = 0; if( lineData ) @@ -16472,9 +18942,12 @@ void QCPGraph::getPreparedData( QVector* lineData, QVector* sc /*! \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 + 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 @@ -16489,7 +18962,9 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData 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 + double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, + // when mErrorBarSkipSymbol is + // true if( keyAxis->orientation() == Qt::Vertical ) { @@ -16503,7 +18978,8 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData // draw spine: if( mErrorBarSkipSymbol ) { - if( a - y > skipSymbolMargin ) // don't draw spine if error is so small it's within skipSymbolmargin + 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 ) ); @@ -16523,7 +18999,8 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData // draw spine: if( mErrorBarSkipSymbol ) { - if( x - a > skipSymbolMargin ) // don't draw spine if error is so small it's within skipSymbolmargin + 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 ) ); @@ -16547,7 +19024,8 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData // draw spine: if( mErrorBarSkipSymbol ) { - if( x - a > skipSymbolMargin ) // don't draw spine if error is so small it's within skipSymbolmargin + 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 ) ); @@ -16567,7 +19045,8 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData // draw spine: if( mErrorBarSkipSymbol ) { - if( a - y > skipSymbolMargin ) // don't draw spine if error is so small it's within skipSymbolmargin + 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 ) ); @@ -16583,19 +19062,24 @@ void QCPGraph::drawError( QCPPainter* painter, double x, double y, const QCPData /*! \internal - called by \ref getPreparedData to determine which data (key) range is visible at the current key + 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 + \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 + \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 +void QCPGraph::getVisibleDataBounds( QCPDataMap::const_iterator& lower, + QCPDataMap::const_iterator& upper ) const { if( !mKeyAxis ) { @@ -16612,8 +19096,11 @@ void QCPGraph::getVisibleDataBounds( QCPDataMap::const_iterator& lower, QCPDataM // 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 + 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 @@ -16621,12 +19108,16 @@ void QCPGraph::getVisibleDataBounds( QCPDataMap::const_iterator& lower, QCPDataM /*! \internal - Counts the number of data points between \a lower and \a upper (including them), up to a maximum + 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 + 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, @@ -16647,15 +19138,22 @@ int QCPGraph::countDataInBounds( const QCPDataMap::const_iterator& lower, /*! \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 + 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 + 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 @@ -16683,7 +19181,8 @@ void QCPGraph::addFillBasePoints( QVector* lineData ) const /*! \internal - removes the two points from \a lineData that were added by \ref addFillBasePoints. + removes the two points from \a lineData that were added by \ref + addFillBasePoints. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ @@ -16694,14 +19193,20 @@ void QCPGraph::removeFillBasePoints( QVector* lineData ) const /*! \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 + 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 + \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 @@ -16742,13 +19247,15 @@ QPointF QCPGraph::lowerFillBasePoint( double lowerKey ) const } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { - // In logarithmic scaling we can't just draw to value zero so we just fill all the way + // 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 + 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() ); @@ -16759,7 +19266,8 @@ QPointF QCPGraph::lowerFillBasePoint( double lowerKey ) const 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 + 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() ); @@ -16770,14 +19278,20 @@ QPointF QCPGraph::lowerFillBasePoint( double lowerKey ) const /*! \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 + 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 + \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 @@ -16818,13 +19332,15 @@ QPointF QCPGraph::upperFillBasePoint( double upperKey ) const } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { - // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // 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 + 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() ); @@ -16835,7 +19351,8 @@ QPointF QCPGraph::upperFillBasePoint( double upperKey ) const 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 + 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() ); @@ -16846,11 +19363,16 @@ QPointF QCPGraph::upperFillBasePoint( double upperKey ) const /*! \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 + 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 @@ -16872,7 +19394,8 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat } 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 + 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() ) @@ -16882,20 +19405,27 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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; i < lineData->size(); ++i ) // don't use the vector<<(vector), it squeezes internally, which ruins - // the performance tuning with reserve() + thisData.reserve( lineData->size() + otherData.size() ); // because we will join + // both vectors at end + // of this function + for( int i = 0; i < lineData->size(); ++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: + // 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): + // 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 + // 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() ) { @@ -16916,7 +19446,8 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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 + // 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 @@ -16937,7 +19468,8 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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 + // 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 @@ -16954,9 +19486,12 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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 + // 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() ) { @@ -16977,12 +19512,14 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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 + // 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 + 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 @@ -16998,12 +19535,14 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat 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 + // 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 + 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 @@ -17014,15 +19553,18 @@ const QPolygonF QCPGraph::getChannelFillPolygon( const QVector* lineDat } // return joined: - for( int i = otherData.size() - 1; i >= 0; --i ) // insert reversed, otherwise the polygon will be twisted + 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. + 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. */ @@ -17043,8 +19585,10 @@ int QCPGraph::findIndexAboveX( const QVector* data, double x ) const /*! \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. + 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. */ @@ -17065,8 +19609,10 @@ int QCPGraph::findIndexBelowX( const QVector* data, double x ) const /*! \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. + 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. */ @@ -17087,12 +19633,16 @@ int QCPGraph::findIndexAboveY( const QVector* data, double y ) const /*! \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 + 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 + 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 500. */ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const @@ -17104,7 +19654,8 @@ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const } if( mData->size() == 1 ) { - QPointF dataPoint = coordsToPixels( mData->constBegin().key(), mData->constBegin().value().value ); + QPointF dataPoint = + coordsToPixels( mData->constBegin().key(), mData->constBegin().value().value ); return QVector2D( dataPoint - pixelPoint ).length(); } @@ -17119,9 +19670,10 @@ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const getScatterPlotData( scatterData ); double minDistSqr = std::numeric_limits::max(); QPointF ptA; - QPointF ptB = coordsToPixels( - scatterData->at( 0 ).key, - scatterData->at( 0 ).value ); // getScatterPlotData returns in plot coordinates, so transform to pixels + QPointF ptB = coordsToPixels( scatterData->at( 0 ).key, + scatterData->at( 0 ).value ); // getScatterPlotData returns + // in plot coordinates, so + // transform to pixels for( int i = 1; i < scatterData->size(); ++i ) { ptA = ptB; @@ -17141,10 +19693,12 @@ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const 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: + // impulse plot differs from other line styles in that the lineData points + // are only pairwise connected: for( int i = 0; i < lineData->size() - 1; i += 2 ) // iterate pairs { - double currentDistSqr = distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); + double currentDistSqr = + distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } @@ -17154,7 +19708,8 @@ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const // all other line plots (line and step) connect points directly: for( int i = 0; i < lineData->size() - 1; ++i ) { - double currentDistSqr = distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); + double currentDistSqr = + distSqrToLine( lineData->at( i ), lineData->at( i + 1 ), pixelPoint ); if( currentDistSqr < minDistSqr ) minDistSqr = currentDistSqr; } @@ -17166,8 +19721,10 @@ double QCPGraph::pointDistance( const QPointF& pixelPoint ) const /*! \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 + 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. @@ -17190,26 +19747,33 @@ int QCPGraph::findIndexBelowY( const QVector* data, double y ) const /* 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. + // 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. + // 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. + 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 QCPGraph::getKeyRange( bool& foundRange, + SignDomain inSignDomain, + bool includeErrors ) const { QCPRange range; bool haveLower = false; @@ -17246,17 +19810,20 @@ QCPRange QCPGraph::getKeyRange( bool& foundRange, SignDomain inSignDomain, bool 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 ) + if( ( current - currentErrorMinus < range.lower || !haveLower ) && + current - currentErrorMinus < 0 ) { range.lower = current - currentErrorMinus; haveLower = true; } - if( ( current + currentErrorPlus > range.upper || !haveUpper ) && current + currentErrorPlus < 0 ) + 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 + 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 ) @@ -17281,17 +19848,20 @@ QCPRange QCPGraph::getKeyRange( bool& foundRange, SignDomain inSignDomain, bool 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 ) + if( ( current - currentErrorMinus < range.lower || !haveLower ) && + current - currentErrorMinus > 0 ) { range.lower = current - currentErrorMinus; haveLower = true; } - if( ( current + currentErrorPlus > range.upper || !haveUpper ) && current + currentErrorPlus > 0 ) + 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 + 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 ) @@ -17315,11 +19885,14 @@ QCPRange QCPGraph::getKeyRange( bool& foundRange, SignDomain inSignDomain, bool /*! \overload - Allows to specify whether the error bars should be included in the range calculation. + 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 QCPGraph::getValueRange( bool& foundRange, + SignDomain inSignDomain, + bool includeErrors ) const { QCPRange range; bool haveLower = false; @@ -17356,17 +19929,20 @@ QCPRange QCPGraph::getValueRange( bool& foundRange, SignDomain inSignDomain, boo current = it.value().value; currentErrorMinus = ( includeErrors ? it.value().valueErrorMinus : 0 ); currentErrorPlus = ( includeErrors ? it.value().valueErrorPlus : 0 ); - if( ( current - currentErrorMinus < range.lower || !haveLower ) && current - currentErrorMinus < 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 ) + 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 + 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 ) @@ -17391,17 +19967,20 @@ QCPRange QCPGraph::getValueRange( bool& foundRange, SignDomain inSignDomain, boo current = it.value().value; currentErrorMinus = ( includeErrors ? it.value().valueErrorMinus : 0 ); currentErrorPlus = ( includeErrors ? it.value().valueErrorPlus : 0 ); - if( ( current - currentErrorMinus < range.lower || !haveLower ) && current - currentErrorMinus > 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 ) + 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 + 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 ) @@ -17433,7 +20012,8 @@ QCPRange QCPGraph::getValueRange( bool& foundRange, SignDomain inSignDomain, boo 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 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 @@ -17450,7 +20030,8 @@ 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 ) +QCPCurveData::QCPCurveData( double t, double key, double value ) + : t( t ), key( key ), value( value ) { } @@ -17463,25 +20044,32 @@ QCPCurveData::QCPCurveData( double t, double key, double value ) : t( t ), key( \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 + 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. \section appearance Changing the appearance - The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). + 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, + 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: \code - QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, + customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(newCurve);\endcode @@ -17492,15 +20080,20 @@ QCPCurveData::QCPCurveData( double t, double key, double value ) : t( t ), key( */ /*! - 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 + 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 + 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 ) +QCPCurve::QCPCurve( QCPAxis* keyAxis, QCPAxis* valueAxis ) + : QCPAbstractPlottable( keyAxis, valueAxis ) { mData = new QCPCurveDataMap; mPen.setColor( Qt::blue ); @@ -17524,8 +20117,10 @@ QCPCurve::~QCPCurve() /*! 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 + 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 ) @@ -17543,11 +20138,15 @@ void QCPCurve::setData( QCPCurveDataMap* data, bool copy ) /*! \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 + 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 ) +void QCPCurve::setData( const QVector& t, + const QVector& key, + const QVector& value ) { mData->clear(); int n = t.size(); @@ -17565,8 +20164,10 @@ void QCPCurve::setData( const QVector& t, const QVector& key, co /*! \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. + 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 ) { @@ -17585,7 +20186,8 @@ void QCPCurve::setData( const QVector& key, const QVector& value /*! 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 + QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots + with appropriate line style). \see QCPScatterStyle, setLineStyle @@ -17596,8 +20198,10 @@ void QCPCurve::setScatterStyle( const QCPScatterStyle& 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 + 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 @@ -17626,7 +20230,8 @@ void QCPCurve::addData( const QCPCurveData& data ) } /*! \overload - Adds the provided single data point as \a t, \a key and \a value tuple to the current data + 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 ) @@ -17640,8 +20245,10 @@ void QCPCurve::addData( double t, double key, double value ) /*! \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 + 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 @@ -17659,10 +20266,13 @@ void QCPCurve::addData( double key, double value ) } /*! \overload - Adds the provided data points as \a t, \a key and \a value tuples to the current data. + 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 ) +void QCPCurve::addData( const QVector& ts, + const QVector& keys, + const QVector& values ) { int n = ts.size(); n = qMin( n, keys.size() ); @@ -17702,8 +20312,10 @@ void QCPCurve::removeDataAfter( double t ) } /*! - 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 + 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 @@ -17720,9 +20332,12 @@ void QCPCurve::removeData( double fromt, double tot ) /*! \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 + 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 @@ -17776,7 +20391,8 @@ void QCPCurve::draw( QCPPainter* painter ) 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 ) ) + 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(); } @@ -17797,8 +20413,10 @@ void QCPCurve::draw( QCPPainter* painter ) 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 && + // 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 ) ) { @@ -17826,17 +20444,19 @@ void QCPCurve::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const 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 ); + 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 + 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() ) @@ -17848,8 +20468,8 @@ void QCPCurve::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const mScatterStyle.pixmap().size().height() > rect.height() ) ) { QCPScatterStyle scaledStyle( mScatterStyle ); - scaledStyle.setPixmap( - scaledStyle.pixmap().scaled( rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation ) ); + scaledStyle.setPixmap( scaledStyle.pixmap().scaled( rect.size().toSize(), Qt::KeepAspectRatio, + Qt::SmoothTransformation ) ); scaledStyle.applyTo( painter, mPen ); scaledStyle.drawShape( painter, QRectF( rect ).center() ); } @@ -17863,8 +20483,10 @@ void QCPCurve::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const /*! \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. + 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 { @@ -17877,8 +20499,10 @@ void QCPCurve::drawScatterPlot( QCPPainter* painter, const QVector* poi /*! \internal - called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the - curve. Line segments that aren't visible in the current axis rect are handled in an optimized + called by QCPCurve::draw to generate a point vector (pixels) which represents + the line of the + curve. Line segments that aren't visible in the current axis rect are handled + in an optimized way. */ void QCPCurve::getCurveData( QVector* lineData ) const @@ -17887,9 +20511,11 @@ void QCPCurve::getCurveData( QVector* lineData ) const 1__|_4_|__7 2__|_R_|__8 3 | 6 | 9 - General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner + General idea: If the two points of a line segment are in the same region + (that is not R), the line segment corner is removed. - Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look + Curves outside R become straight lines closely outside of R which greatly + reduces drawing time, yet keeps the look of lines and fills inside R consistent. The region R has index 5. @@ -17913,7 +20539,8 @@ void QCPCurve::getCurveData( QVector* lineData ) const double RTop = valueAxis->range().upper; double x, y; // current key/value bool addedLastAlready = true; - bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly + bool firstPoint = true; // first point must always be drawn, to make sure fill + // works correctly for( it = mData->constBegin(); it != mData->constEnd(); ++it ) { x = it.value().key; @@ -17948,37 +20575,51 @@ void QCPCurve::getCurveData( QVector* lineData ) const } /* - Watch out, the next part is very tricky. It modifies the curve such that it seems like the - whole thing is still drawn, but actually the points outside the axisRect are simplified - ("optimized") greatly. There are some subtle special cases when line segments are large and - thereby each subsequent point may be in a different region or even skip some. + Watch out, the next part is very tricky. It modifies the curve such that + it seems like the + whole thing is still drawn, but actually the points outside the axisRect + are simplified + ("optimized") greatly. There are some subtle special cases when line + segments are large and + thereby each subsequent point may be in a different region or even skip + some. */ // determine whether to keep current point: if( currentRegion == 5 || - ( firstPoint && - mBrush.style() != Qt::NoBrush ) ) // current is in R, add current and last if it wasn't added already + ( firstPoint && mBrush.style() != Qt::NoBrush ) ) // current is in R, add + // current and last if it + // wasn't added already { - if( !addedLastAlready ) // in case curve just entered R, make sure the last point outside R is also drawn + if( !addedLastAlready ) // in case curve just entered R, make sure the last + // point outside R is also drawn // correctly - lineData->append( - coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); // add last point to vector - else if( lastRegion != 5 ) // added last already. If that's the case, we probably added it at optimized position. - // So go back and make sure it's at original position (else the angle changes under - // which this segment enters R) + lineData->append( coordsToPixels( ( it - 1 ).value().key, + ( it - 1 ).value().value ) ); // add last point to vector + else if( lastRegion != 5 ) // added last already. If that's the case, we + // probably added it at optimized position. + // So go back and make sure it's at original position (else the angle + // changes under + // which this segment enters R) { - if( !firstPoint ) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is + if( !firstPoint ) // because on firstPoint, currentRegion is 5 and + // addedLastAlready is true, although there is // no last point - lineData->replace( lineData->size() - 1, coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); + lineData->replace( lineData->size() - 1, + coordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value ) ); } - lineData->append( coordsToPixels( it.value().key, it.value().value ) ); // add current point to vector + lineData->append( + coordsToPixels( it.value().key, it.value().value ) ); // add current point to vector addedLastAlready = true; // so in next iteration, we don't add this point twice } - else if( currentRegion != lastRegion ) // changed region, add current and last if not added already + else if( currentRegion != lastRegion ) // changed region, add current and + // last if not added already { - // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside + // using outsideCoordsToPixels instead of coorsToPixels for optimized + // point placement (places points just outside // axisRect instead of potentially far away) - // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we + // if we're coming from R or we skip diagonally over the corner regions + // (so line might still be visible in R), we // can't place points optimized if( lastRegion == 5 || // coming from R ( ( lastRegion == 2 && currentRegion == 4 ) || @@ -17997,17 +20638,20 @@ void QCPCurve::getCurveData( QVector* lineData ) const // add current point, original: lineData->append( coordsToPixels( it.value().key, it.value().value ) ); } - else // no special case that forbids optimized point placement, so do it: + else // no special case that forbids optimized point placement, so do + // it: { // always add last point if not added already, optimized: if( !addedLastAlready ) - lineData->append( - outsideCoordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value, currentRegion, axisRect ) ); + lineData->append( outsideCoordsToPixels( ( it - 1 ).value().key, ( it - 1 ).value().value, + currentRegion, axisRect ) ); // add current point, optimized: - lineData->append( outsideCoordsToPixels( it.value().key, it.value().value, currentRegion, axisRect ) ); + lineData->append( + outsideCoordsToPixels( it.value().key, it.value().value, currentRegion, axisRect ) ); } - addedLastAlready = - true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice + addedLastAlready = true; // so that if next point enters 5, or crosses + // another region boundary, we don't add this + // point twice } else // neither in R, nor crossed a region boundary, skip current point { @@ -18016,17 +20660,20 @@ void QCPCurve::getCurveData( QVector* lineData ) const lastRegion = currentRegion; firstPoint = false; } - // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started + // If curve ends outside R, we want to add very last point so the fill looks + // like it should when the curve started // inside R: if( lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty() ) - lineData->append( - coordsToPixels( ( mData->constEnd() - 1 ).value().key, ( mData->constEnd() - 1 ).value().value ) ); + lineData->append( coordsToPixels( ( mData->constEnd() - 1 ).value().key, + ( mData->constEnd() - 1 ).value().value ) ); } /*! \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 + 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 @@ -18038,7 +20685,8 @@ double QCPCurve::pointDistance( const QPointF& pixelPoint ) const } if( mData->size() == 1 ) { - QPointF dataPoint = coordsToPixels( mData->constBegin().key(), mData->constBegin().value().value ); + QPointF dataPoint = + coordsToPixels( mData->constBegin().key(), mData->constBegin().value().value ); return QVector2D( dataPoint - pixelPoint ).length(); } @@ -18058,16 +20706,26 @@ double QCPCurve::pointDistance( const QPointF& pixelPoint ) const /*! \internal - This is a specialized \ref coordsToPixels function for points that are outside the visible - axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments - to those line segments that cross region boundaries, see documentation there). It only uses the - coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just - outside the axisRect (how far is determined by the scatter size and the line width). Together - with the optimization in \ref getCurveData this improves performance for large curves (or zoomed - in ones) significantly while keeping the illusion the whole curve and its filling is still being + This is a specialized \ref coordsToPixels function for points that are outside + the visible + axisRect and just crossing a boundary (since \ref getCurveData reduces + non-visible curve segments + to those line segments that cross region boundaries, see documentation there). + It only uses the + coordinate parallel to the region boundary of the axisRect. The other + coordinate is picked just + outside the axisRect (how far is determined by the scatter size and the line + width). Together + with the optimization in \ref getCurveData this improves performance for large + curves (or zoomed + in ones) significantly while keeping the illusion the whole curve and its + filling is still being drawn for the viewer. */ -QPointF QCPCurve::outsideCoordsToPixels( double key, double value, int region, QRect axisRect ) const +QPointF QCPCurve::outsideCoordsToPixels( double key, + double value, + int region, + QRect axisRect ) const { int margin = qCeil( qMax( mScatterStyle.size(), (double)mPen.widthF() ) ) + 2; QPointF result = coordsToPixels( key, value ); @@ -18216,17 +20874,21 @@ QCPBarData::QCPBarData( double key, double value ) : key( key ), value( value ) \section appearance Changing the appearance - The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). + The appearance of the bars is determined by the pen and the brush (\ref + setPen, \ref setBrush). - Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other - (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear + Bar charts are stackable. This means, Two QCPBars plottables can be placed on + top of each other + (see \ref QCPBars::moveAbove). Then, when two bars are at the same key + position, they will appear stacked. \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.) + (QCustomPlot::plottable, QCustomPlot::addPlottable, + QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code @@ -18255,15 +20917,20 @@ QCPBarData::QCPBarData( double key, double value ) : key( key ), value( value ) */ /*! - 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 + 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 + 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 ) +QCPBars::QCPBars( QCPAxis* keyAxis, QCPAxis* valueAxis ) + : QCPAbstractPlottable( keyAxis, valueAxis ) { mData = new QCPBarDataMap; mPen.setColor( Qt::blue ); @@ -18296,8 +20963,10 @@ void QCPBars::setWidth( double width ) /*! 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 + 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 ) @@ -18315,8 +20984,10 @@ void QCPBars::setData( QCPBarDataMap* data, bool copy ) /*! \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 + 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 ) @@ -18334,13 +21005,18 @@ void QCPBars::setData( const QVector& key, const QVector& value } /*! - 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 + 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 + 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. @@ -18353,11 +21029,13 @@ void QCPBars::moveBelow( QCPBars* bars ) 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"; + 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 + 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 ) { @@ -18368,13 +21046,18 @@ void QCPBars::moveBelow( QCPBars* 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 + 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 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 + 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. @@ -18387,11 +21070,13 @@ void QCPBars::moveAbove( QCPBars* bars ) 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"; + 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 + 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 ) { @@ -18420,7 +21105,8 @@ void QCPBars::addData( const QCPBarData& data ) } /*! \overload - Adds the provided single data point as \a key and \a value tuple to the current data + 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 ) @@ -18432,7 +21118,8 @@ void QCPBars::addData( double key, double value ) } /*! \overload - Adds the provided data points as \a key and \a value tuples to the current data. + 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 ) @@ -18473,8 +21160,10 @@ void QCPBars::removeDataAfter( double key ) } /*! - 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 + 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 @@ -18491,9 +21180,12 @@ void QCPBars::removeData( double fromKey, double toKey ) /*! \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. + 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 */ @@ -18598,7 +21290,8 @@ void QCPBars::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) const /*! \internal - Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom + 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). */ QPolygonF QCPBars::getBarPolygon( double key, double value ) const @@ -18614,11 +21307,14 @@ QPolygonF QCPBars::getBarPolygon( double key, double value ) const /*! \internal - This function is called to find at which value to start drawing the base of a bar at \a key, when + 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 0-value upwards, - negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the + positive and negative bars are separated per stack (positive are stacked above + 0-value upwards, + negative are stacked below 0-value 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::getBaseValue( double key, bool positive ) const @@ -18626,7 +21322,8 @@ double QCPBars::getBaseValue( double key, bool positive ) const if( mBarBelow ) { double max = 0; - // find bars of mBarBelow that are approximately at key and find largest one: + // find bars of mBarBelow that are approximately at key and find largest + // one: QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound( key - mWidth * 0.1 ); QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound( key + mWidth * 0.1 ); while( it != itEnd ) @@ -18644,8 +21341,10 @@ double QCPBars::getBaseValue( double key, bool positive ) const /*! \internal - Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. - The bar(s) currently below lower and upper will become disconnected to lower/upper. + Connects \a below and \a above to each other via their mBarAbove/mBarBelow + properties. + The bar(s) currently below lower and 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. @@ -18759,7 +21458,8 @@ QCPRange QCPBars::getValueRange( bool& foundRange, SignDomain inSignDomain ) con \image html QCPStatisticalBox.png - To plot data, assign it with the individual parameter functions or use \ref setData to set all + 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 @@ -18772,31 +21472,40 @@ QCPRange QCPBars::getValueRange( bool& foundRange, SignDomain inSignDomain ) con \section appearance Changing the appearance - The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change + 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 + 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 + 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 + 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 + Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a + plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies - (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + (QCustomPlot::plottable, QCustomPlot::addPlottable, + QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code - QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode + QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, + customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(newBox);\endcode @@ -18808,22 +21517,27 @@ QCPRange QCPBars::getValueRange( bool& foundRange, SignDomain inSignDomain ) con */ /*! - 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. + 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, + 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 ) + : 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 ); @@ -18847,8 +21561,10 @@ void QCPStatisticalBox::setKey( double 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. + 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 */ @@ -18858,8 +21574,10 @@ void QCPStatisticalBox::setMinimum( double 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 + 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 @@ -18870,8 +21588,10 @@ void QCPStatisticalBox::setLowerQuartile( double 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 + 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 @@ -18882,8 +21602,10 @@ void QCPStatisticalBox::setMedian( double 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 + 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 @@ -18894,8 +21616,10 @@ void QCPStatisticalBox::setUpperQuartile( double 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. + 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 */ @@ -18905,8 +21629,10 @@ void QCPStatisticalBox::setMaximum( double 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 + 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 @@ -18919,7 +21645,8 @@ void QCPStatisticalBox::setOutliers( const QVector& values ) /*! Sets all parameters of the statistical box plot at once. - \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum + \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, + setMaximum */ void QCPStatisticalBox::setData( double key, double minimum, @@ -18947,7 +21674,8 @@ void QCPStatisticalBox::setWidth( double width ) } /*! - Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. + Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key + coordinates. \see setWidth */ @@ -18957,9 +21685,11 @@ void QCPStatisticalBox::setWhiskerWidth( double width ) } /*! - Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). + 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 + 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 @@ -18970,7 +21700,8 @@ void QCPStatisticalBox::setWhiskerPen( const QPen& pen ) } /*! - Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at + 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 @@ -18981,7 +21712,8 @@ void QCPStatisticalBox::setWhiskerBarPen( const QPen& pen ) } /*! - Sets the pen used for drawing the median indicator line inside the statistical box. + Sets the pen used for drawing the median indicator line inside the statistical + box. */ void QCPStatisticalBox::setMedianPen( const QPen& pen ) { @@ -19011,7 +21743,9 @@ void QCPStatisticalBox::clearData() } /* inherits documentation from base class */ -double QCPStatisticalBox::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +double QCPStatisticalBox::selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details ) const { Q_UNUSED( details ) if( onlySelectable && !mSelectable ) @@ -19034,7 +21768,8 @@ double QCPStatisticalBox::selectTest( const QPointF& pos, bool onlySelectable, Q // min/max whiskers: if( QCPRange( mMinimum, mMaximum ).contains( posValue ) ) - return qAbs( mKeyAxis.data()->coordToPixel( mKey ) - mKeyAxis.data()->coordToPixel( posKey ) ); + return qAbs( mKeyAxis.data()->coordToPixel( mKey ) - + mKeyAxis.data()->coordToPixel( posKey ) ); } return -1; } @@ -19086,8 +21821,10 @@ void QCPStatisticalBox::drawLegendIcon( QCPPainter* painter, const QRectF& rect /*! \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 + 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 @@ -19190,7 +21927,8 @@ QCPRange QCPStatisticalBox::getKeyRange( bool& foundRange, SignDomain inSignDoma /* 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) + 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; @@ -19201,8 +21939,8 @@ QCPRange QCPStatisticalBox::getValueRange( bool& foundRange, SignDomain inSignDo double lower = 0; for( int i = 0; i < values.size(); ++i ) { - if( ( inSignDomain == sdNegative && values.at( i ) < 0 ) || ( inSignDomain == sdPositive && values.at( i ) > 0 ) || - ( inSignDomain == sdBoth ) ) + if( ( inSignDomain == sdNegative && values.at( i ) < 0 ) || + ( inSignDomain == sdPositive && values.at( i ) > 0 ) || ( inSignDomain == sdBoth ) ) { if( values.at( i ) > upper || !haveUpper ) { @@ -19236,28 +21974,44 @@ QCPRange QCPStatisticalBox::getValueRange( bool& foundRange, SignDomain inSignDo /*! \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 + 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 + 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 + 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 + 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. */ @@ -19265,27 +22019,33 @@ QCPRange QCPStatisticalBox::getValueRange( bool& foundRange, SignDomain inSignDo /*! \fn bool QCPColorMapData::isEmpty() const - Returns whether this instance carries no data. This is equivalent to having a size where at least + 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 + 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 ) +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 ); @@ -19298,7 +22058,8 @@ QCPColorMapData::~QCPColorMapData() } /*! - Constructs a new QCPColorMapData instance copying the data and range of \a other. + 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 ) @@ -19328,9 +22089,12 @@ QCPColorMapData& QCPColorMapData::operator=( const QCPColorMapData& other ) /* undocumented getter */ double QCPColorMapData::data( double key, double value ) { - int keyCell = ( key - mKeyRange.lower ) / ( mKeyRange.upper - mKeyRange.lower ) * ( mKeySize - 1 ) + 0.5; + int keyCell = + ( key - mKeyRange.lower ) / ( mKeyRange.upper - mKeyRange.lower ) * ( mKeySize - 1 ) + 0.5; int valueCell = - ( 1.0 - ( value - mValueRange.lower ) / ( mValueRange.upper - mValueRange.lower ) ) * ( mValueSize - 1 ) + 0.5; + ( 1.0 - ( 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 @@ -19347,13 +22111,16 @@ double QCPColorMapData::cell( int keyIndex, int valueIndex ) } /*! - Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in + 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 + 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 + 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 @@ -19371,7 +22138,8 @@ void QCPColorMapData::setSize( int keySize, int valueSize ) { #ifdef __EXCEPTIONS try - { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message + { // 2D arrays get memory intensive fast. So if the allocation fails, + // at least output debug message #endif mData = new double[mKeySize * mValueSize]; #ifdef __EXCEPTIONS @@ -19384,7 +22152,8 @@ void QCPColorMapData::setSize( int keySize, int valueSize ) if( mData ) fill( 0 ); else - qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*" << mValueSize; + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*" + << mValueSize; } else mData = 0; @@ -19395,10 +22164,12 @@ void QCPColorMapData::setSize( int keySize, int valueSize ) /*! 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 + 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. + Setting \a keySize to zero frees the internal data array and \ref isEmpty + returns true. \see setKeyRange, setSize, setValueSize */ @@ -19410,10 +22181,12 @@ void QCPColorMapData::setKeySize( int keySize ) /*! 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 + 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. + Setting \a valueSize to zero frees the internal data array and \ref isEmpty + returns true. \see setValueRange, setSize, setKeySize */ @@ -19423,11 +22196,14 @@ void QCPColorMapData::setValueSize( int valueSize ) } /*! - Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area + 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 + 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 @@ -19439,11 +22215,15 @@ void QCPColorMapData::setRange( const QCPRange& keyRange, const QCPRange& valueR } /*! - 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. + 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 + 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 @@ -19454,11 +22234,15 @@ void QCPColorMapData::setKeyRange( const QCPRange& 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. + 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 + 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 @@ -19469,15 +22253,19 @@ void QCPColorMapData::setValueRange( const QCPRange& valueRange ) } /*! - Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a + Sets the data of the cell, which lies at the plot coordinates given by \a key + and \a value, to \a z. \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; + 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; @@ -19490,12 +22278,16 @@ void QCPColorMapData::setData( double key, double value, double z ) } /*! - 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 + 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 + 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 @@ -19514,16 +22306,23 @@ void QCPColorMapData::setCell( int keyIndex, int valueIndex, double z ) } /*! - Goes through the data and updates the buffered minimum and maximum data values. + 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 + 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 + 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() @@ -19567,13 +22366,17 @@ void QCPColorMapData::fill( double z ) } /*! - Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData - instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a + Transforms plot coordinates given by \a key and \a value to cell indices of + this QCPColorMapData + instance. The resulting cell indices are returned via the output parameters \a + keyIndex and \a valueIndex. - The retrieved key/value cell indices can then be used for example with \ref setCell. + The retrieved key/value cell indices can then be used for example with \ref + setCell. - If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a + If you are only interested in a key or value index, you may pass 0 as \a + valueIndex or \a keyIndex. \see cellToCoord, QCPAxis::coordToPixel @@ -19581,17 +22384,23 @@ void QCPColorMapData::fill( double z ) void QCPColorMapData::coordToCell( double key, double value, int* keyIndex, int* valueIndex ) const { if( keyIndex ) - *keyIndex = ( key - mKeyRange.lower ) / ( mKeyRange.upper - mKeyRange.lower ) * ( mKeySize - 1 ) + 0.5; + *keyIndex = + ( key - mKeyRange.lower ) / ( mKeyRange.upper - mKeyRange.lower ) * ( mKeySize - 1 ) + 0.5; if( valueIndex ) - *valueIndex = ( value - mValueRange.lower ) / ( mValueRange.upper - mValueRange.lower ) * ( mValueSize - 1 ) + 0.5; + *valueIndex = ( value - mValueRange.lower ) / ( mValueRange.upper - mValueRange.lower ) * + ( mValueSize - 1 ) + + 0.5; } /*! - Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData - instance. The resulting coordinates are returned via the output parameters \a key and \a + Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices + of this QCPColorMapData + instance. The resulting coordinates are returned via the output parameters \a + key and \a value. - If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a + If you are only interested in a key or value coordinate, you may pass 0 as \a + key or \a value. \see coordToCell, QCPAxis::pixelToCoord @@ -19599,9 +22408,11 @@ void QCPColorMapData::coordToCell( double key, double value, int* keyIndex, int* void QCPColorMapData::cellToCoord( int keyIndex, int valueIndex, double* key, double* value ) const { if( key ) - *key = keyIndex / (double)( mKeySize - 1 ) * ( mKeyRange.upper - mKeyRange.lower ) + mKeyRange.lower; + *key = keyIndex / (double)( mKeySize - 1 ) * ( mKeyRange.upper - mKeyRange.lower ) + + mKeyRange.lower; if( value ) - *value = valueIndex / (double)( mValueSize - 1 ) * ( mValueRange.upper - mValueRange.lower ) + mValueRange.lower; + *value = valueIndex / (double)( mValueSize - 1 ) * ( mValueRange.upper - mValueRange.lower ) + + mValueRange.lower; } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19613,50 +22424,71 @@ void QCPColorMapData::cellToCoord( int keyIndex, int valueIndex, double* key, do \image html QCPColorMap.png - The data is stored in the class \ref QCPColorMapData, which can be accessed via the data() + The data is stored in the class \ref QCPColorMapData, which can be accessed + via the data() method. - A color map has three dimensions to represent a data point: The \a key dimension, the \a value - dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value - correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QColorMap - constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a + A color map has three dimensions to represent a data point: The \a key + dimension, the \a value + dimension and the \a data dimension. As with other plottables such as graphs, + \a key and \a value + correspond to two orthogonal axes on the QCustomPlot surface that you specify + in the QColorMap + constructor. The \a data dimension however is encoded as the color of the + point at (\a key, \a value). Set the number of points (or \a cells) in the key/value dimension via \ref - QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is - specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range - boundary and the last cell will be centered on the upper range boundary. The data can be set by - either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via - their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer - setCell, since it doesn't need to do any coordinate transformation and thus performs a bit + QCPColorMapData::setSize. The plot coordinate range over which these points + will be displayed is + specified via \ref QCPColorMapData::setRange. The first cell will be centered + on the lower range + boundary and the last cell will be centered on the upper range boundary. The + data can be set by + either accessing the cells directly with QCPColorMapData::setCell or by + addressing the cells via + their plot coordinates with \ref QCPColorMapData::setData. If possible, you + should prefer + setCell, since it doesn't need to do any coordinate transformation and thus + performs a bit better. - The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed) + The cell with index (0, 0) is at the bottom left, if the color map uses normal + (i.e. not reversed) key and value axes. - To show the user which colors correspond to which \a data values, a \ref QCPColorScale is - typically placed to the right of the axis rect. See the documentation there for details on how to + To show the user which colors correspond to which \a data values, a \ref + QCPColorScale is + typically placed to the right of the axis rect. See the documentation there + for details on how to add and use a color scale. \section appearance Changing the appearance - The central part of the appearance is the color gradient, which can be specified via \ref - setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color + The central part of the appearance is the color gradient, which can be + specified via \ref + setGradient. See the documentation of \ref QCPColorGradient for details on + configuring a color gradient. - The \a data range that is mapped to the colors of the gradient can be specified with \ref - setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref + The \a data range that is mapped to the colors of the gradient can be + specified with \ref + setDataRange. To make the data range encompass the whole data set minimum to + maximum, call \ref rescaleDataRange. \section usage Usage - Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable + Like all data representing objects in QCustomPlot, the QCPColorMap is a + plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies - (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + (QCustomPlot::plottable, QCustomPlot::addPlottable, + QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code - QCPColorMap *colorMap = new QCPColorMap(customPlot->xAxis, customPlot->yAxis);\endcode + QCPColorMap *colorMap = new QCPColorMap(customPlot->xAxis, + customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(colorMap);\endcode @@ -19673,9 +22505,12 @@ void QCPColorMapData::cellToCoord( int keyIndex, int valueIndex, double* key, do customPlot->replot(); \endcode - \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 + \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. */ @@ -19684,7 +22519,8 @@ void QCPColorMapData::cellToCoord( int keyIndex, int valueIndex, double* key, do /*! \fn QCPColorMapData *QCPColorMap::data() const - Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to + Returns a pointer to the internal data storage of type \ref QCPColorMapData. + Access this to modify data points (cells) and the color map key/value range. \see setData @@ -19720,16 +22556,17 @@ void QCPColorMapData::cellToCoord( int keyIndex, int valueIndex, double* key, do /*! Constructs a color map with the specified \a keyAxis and \a valueAxis. - The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + The constructed QCPColorMap can be added to the plot with + QCustomPlot::addPlottable, QCustomPlot then takes ownership of the color map. */ QCPColorMap::QCPColorMap( QCPAxis* keyAxis, QCPAxis* valueAxis ) - : QCPAbstractPlottable( keyAxis, valueAxis ), - mDataScaleType( QCPAxis::stLinear ), - mMapData( new QCPColorMapData( 10, 10, QCPRange( 0, 5 ), QCPRange( 0, 5 ) ) ), - mInterpolate( true ), - mTightBoundary( false ), - mMapImageInvalidated( true ) + : QCPAbstractPlottable( keyAxis, valueAxis ) + , mDataScaleType( QCPAxis::stLinear ) + , mMapData( new QCPColorMapData( 10, 10, QCPRange( 0, 5 ), QCPRange( 0, 5 ) ) ) + , mInterpolate( true ) + , mTightBoundary( false ) + , mMapImageInvalidated( true ) { } @@ -19741,8 +22578,10 @@ QCPColorMap::~QCPColorMap() /*! Replaces the current \ref data with the provided \a data. - If \a copy is set to true, the \a data object will only be copied. if false, the color map - takes ownership of the passed data and replaces the internal data pointer with it. This is + If \a copy is set to true, the \a data object will only be copied. if false, + the color map + takes ownership of the passed data and replaces the internal data pointer with + it. This is significantly faster than copying for large datasets. */ void QCPColorMap::setData( QCPColorMapData* data, bool copy ) @@ -19760,10 +22599,12 @@ void QCPColorMap::setData( QCPColorMapData* data, bool copy ) } /*! - Sets the data range of this color map to \a dataRange. The data range defines which data values + 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. + To make the data range span the full range of the data set, use \ref + rescaleDataRange. \see QCPColorScale::setDataRange */ @@ -19783,7 +22624,8 @@ void QCPColorMap::setDataRange( const QCPRange& dataRange ) } /*! - Sets whether the data is correlated with the color gradient linearly or logarithmically. + Sets whether the data is correlated with the color gradient linearly or + logarithmically. \see QCPColorScale::setDataScaleType */ @@ -19800,12 +22642,16 @@ void QCPColorMap::setDataScaleType( QCPAxis::ScaleType scaleType ) } /*! - Sets the color gradient that is used to represent the data. For more details on how to create an + 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, + 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 @@ -19821,10 +22667,12 @@ void QCPColorMap::setGradient( const QCPColorGradient& gradient ) } /*! - Sets whether the color map image shall use bicubic interpolation when displaying the color map + 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" + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation + and without interpolation enabled" */ void QCPColorMap::setInterpolate( bool enabled ) { @@ -19832,15 +22680,22 @@ void QCPColorMap::setInterpolate( bool enabled ) } /*! - 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). + 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. + 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" + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary + enabled and disabled" */ void QCPColorMap::setTightBoundary( bool enabled ) { @@ -19850,27 +22705,35 @@ void QCPColorMap::setTightBoundary( bool 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 + 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 + 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. + 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( 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( dataRangeChanged( QCPRange ) ), this, + SLOT( setDataRange( QCPRange ) ) ); disconnect( mColorScale.data(), SIGNAL( gradientChanged( QCPColorGradient ) ), this, SLOT( setGradient( QCPColorGradient ) ) ); disconnect( mColorScale.data(), SIGNAL( dataScaleTypeChanged( QCPAxis::ScaleType ) ), this, @@ -19882,12 +22745,14 @@ void QCPColorMap::setColorScale( QCPColorScale* colorScale ) 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( 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( dataRangeChanged( QCPRange ) ), this, + SLOT( setDataRange( QCPRange ) ) ); connect( mColorScale.data(), SIGNAL( gradientChanged( QCPColorGradient ) ), this, SLOT( setGradient( QCPColorGradient ) ) ); connect( mColorScale.data(), SIGNAL( dataScaleTypeChanged( QCPAxis::ScaleType ) ), this, @@ -19896,21 +22761,33 @@ void QCPColorMap::setColorScale( QCPColorScale* colorScale ) } /*! - 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, + 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 + 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 + 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 @@ -19923,35 +22800,46 @@ void QCPColorMap::rescaleDataRange( bool recalculateDataBounds ) } /*! - Takes the current appearance of the color map and updates the legend icon, which is used to + 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 + 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. + 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) + 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 + 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(); + 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 + Clears the colormap data by calling \ref QCPColorMapData::clear() on the + internal data. This also resizes the map to 0x0 cells. */ void QCPColorMap::clearData() @@ -19983,11 +22871,15 @@ double QCPColorMap::selectTest( const QPointF& pos, bool onlySelectable, QVarian /*! \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. + 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 + 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). */ void QCPColorMap::updateMapImage() @@ -19996,12 +22888,15 @@ void QCPColorMap::updateMapImage() if( !keyAxis ) return; - // resize mMapImage to correct dimensions, according to key/value axes orientation: + // resize mMapImage to correct dimensions, according to key/value axes + // orientation: if( keyAxis->orientation() == Qt::Horizontal && - ( mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize() ) ) + ( mMapImage.size().width() != mMapData->keySize() || + mMapImage.size().height() != mMapData->valueSize() ) ) mMapImage = QImage( QSize( mMapData->keySize(), mMapData->valueSize() ), QImage::Format_RGB32 ); else if( keyAxis->orientation() == Qt::Vertical && - ( mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize() ) ) + ( mMapImage.size().width() != mMapData->valueSize() || + mMapImage.size().height() != mMapData->keySize() ) ) mMapImage = QImage( QSize( mMapData->valueSize(), mMapData->keySize() ), QImage::Format_RGB32 ); const int keySize = mMapData->keySize(); @@ -20014,10 +22909,10 @@ void QCPColorMap::updateMapImage() const int rowCount = keySize; for( int line = 0; line < lineCount; ++line ) { - QRgb* pixels = reinterpret_cast( - mMapImage.scanLine( lineCount - 1 - line ) ); // invert scanline index because QImage counts scanlines from - // top, but our vertical index counts from bottom (mathematical - // coordinate system) + QRgb* pixels = reinterpret_cast( mMapImage.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 ); } @@ -20028,10 +22923,10 @@ void QCPColorMap::updateMapImage() const int rowCount = valueSize; for( int line = 0; line < lineCount; ++line ) { - QRgb* pixels = reinterpret_cast( - mMapImage.scanLine( lineCount - 1 - line ) ); // invert scanline index because QImage counts scanlines from - // top, but our vertical index counts from bottom (mathematical - // coordinate system) + QRgb* pixels = reinterpret_cast( mMapImage.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 ); } @@ -20059,22 +22954,26 @@ void QCPColorMap::draw( QCPPainter* painter ) halfSampleKey = 0.5 * mMapData->keyRange().size() / (double)( mMapData->keySize() - 1 ); if( mMapData->valueSize() > 1 ) halfSampleValue = 0.5 * mMapData->valueRange().size() / (double)( mMapData->valueSize() - 1 ); - QRectF imageRect( - coordsToPixels( mMapData->keyRange().lower - halfSampleKey, mMapData->valueRange().lower - halfSampleValue ), - coordsToPixels( mMapData->keyRange().upper + halfSampleKey, mMapData->valueRange().upper + halfSampleValue ) ); + QRectF imageRect( coordsToPixels( mMapData->keyRange().lower - halfSampleKey, + mMapData->valueRange().lower - halfSampleValue ), + coordsToPixels( mMapData->keyRange().upper + halfSampleKey, + mMapData->valueRange().upper + halfSampleValue ) ); imageRect = imageRect.normalized(); - bool mirrorX = ( keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis() )->rangeReversed(); - bool mirrorY = ( valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis() )->rangeReversed(); + bool mirrorX = + ( keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis() )->rangeReversed(); + bool mirrorY = + ( valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis() )->rangeReversed(); bool smoothBackup = painter->renderHints().testFlag( QPainter::SmoothPixmapTransform ); painter->setRenderHint( QPainter::SmoothPixmapTransform, mInterpolate ); QRegion clipBackup; if( mTightBoundary ) { clipBackup = painter->clipRegion(); - painter->setClipRect( QRectF( coordsToPixels( mMapData->keyRange().lower, mMapData->valueRange().lower ), - coordsToPixels( mMapData->keyRange().upper, mMapData->valueRange().upper ) ) - .normalized(), - Qt::IntersectClip ); + painter->setClipRect( + QRectF( coordsToPixels( mMapData->keyRange().lower, mMapData->valueRange().lower ), + coordsToPixels( mMapData->keyRange().upper, mMapData->valueRange().upper ) ) + .normalized(), + Qt::IntersectClip ); } painter->drawImage( imageRect, mMapImage.mirrored( mirrorX, mirrorY ) ); if( mTightBoundary ) @@ -20089,7 +22988,8 @@ void QCPColorMap::drawLegendIcon( QCPPainter* painter, const QRectF& rect ) cons // draw map thumbnail: if( !mLegendIcon.isNull() ) { - QPixmap scaledIcon = mLegendIcon.scaled( rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation ); + 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 ); @@ -20155,7 +23055,8 @@ QCPRange QCPColorMap::getValueRange( bool& foundRange, SignDomain inSignDomain ) /*! \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 + \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. @@ -20167,7 +23068,9 @@ QCPRange QCPColorMap::getValueRange( bool& foundRange, SignDomain inSignDomain ) The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemStraightLine::QCPItemStraightLine( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), point1( createPosition( "point1" ) ), point2( createPosition( "point2" ) ) + : QCPAbstractItem( parentPlot ) + , point1( createPosition( "point1" ) ) + , point2( createPosition( "point2" ) ) { point1->setCoords( 0, 0 ); point2->setCoords( 1, 1 ); @@ -20201,14 +23104,17 @@ void QCPItemStraightLine::setSelectedPen( const QPen& pen ) } /* inherits documentation from base class */ -double QCPItemStraightLine::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +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 ) ); + QVector2D( point2->pixelPoint() - point1->pixelPoint() ), + QVector2D( pos ) ); } /* inherits documentation from base class */ @@ -20218,8 +23124,8 @@ void QCPItemStraightLine::draw( QCPPainter* painter ) 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 ) ); + QLineF line = getRectClippedStraightLine( + start, end - start, clipRect().adjusted( -clipPad, -clipPad, clipPad, clipPad ) ); // paint visible segment, if existent: if( !line.isNull() ) { @@ -20230,7 +23136,8 @@ void QCPItemStraightLine::draw( QCPPainter* painter ) /*! \internal - finds the shortest distance of \a point to the straight line defined by the base point \a + 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. @@ -20239,12 +23146,14 @@ 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(); + 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 + 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. @@ -20266,7 +23175,8 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine( const QVector2D& base, 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 + rect.bottom() ); // no need to check bottom because we know + // line is vertical } else if( qFuzzyIsNull( vec.y() ) ) // line is horizontal { @@ -20276,7 +23186,8 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine( const QVector2D& base, 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 + by + gamma ); // no need to check right because we know line + // is horizontal } else // line is skewed { @@ -20313,7 +23224,8 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine( const QVector2D& base, } 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 + // 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; @@ -20353,11 +23265,14 @@ QPen QCPItemStraightLine::mainPen() const /*! \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." + \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. + 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. + With \ref setHead and \ref setTail you may set different line ending styles, + e.g. to create an arrow. */ /*! @@ -20366,7 +23281,9 @@ QPen QCPItemStraightLine::mainPen() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemLine::QCPItemLine( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), start( createPosition( "start" ) ), end( createPosition( "end" ) ) + : QCPAbstractItem( parentPlot ) + , start( createPosition( "start" ) ) + , end( createPosition( "end" ) ) { start->setCoords( 0, 0 ); end->setCoords( 1, 1 ); @@ -20400,10 +23317,13 @@ void QCPItemLine::setSelectedPen( const QPen& pen ) } /*! - Sets the line ending style of the head. The head corresponds to the \a end position. + 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 + 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 */ @@ -20413,10 +23333,13 @@ void QCPItemLine::setHead( const QCPLineEnding& head ) } /*! - Sets the line ending style of the tail. The tail corresponds to the \a start position. + 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 + 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 */ @@ -20445,7 +23368,8 @@ void QCPItemLine::draw( QCPPainter* painter ) // 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 ) ); + QLineF line = getRectClippedLine( startVec, endVec, + clipRect().adjusted( -clipPad, -clipPad, clipPad, clipPad ) ); // paint visible segment, if existent: if( !line.isNull() ) { @@ -20461,12 +23385,15 @@ void QCPItemLine::draw( QCPPainter* painter ) /*! \internal - Returns the section of the line defined by \a start and \a end, that is visible in the specified + 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 +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() ); @@ -20539,7 +23466,8 @@ QLineF QCPItemLine::getRectClippedLine( const QVector2D& start, const QVector2D& } 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 + // 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; @@ -20578,18 +23506,25 @@ QPen QCPItemLine::mainPen() const /*! \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." + \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 + 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 + 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. + 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. */ /*! @@ -20598,11 +23533,11 @@ QPen QCPItemLine::mainPen() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemCurve::QCPItemCurve( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - start( createPosition( "start" ) ), - startDir( createPosition( "startDir" ) ), - endDir( createPosition( "endDir" ) ), - end( createPosition( "end" ) ) + : QCPAbstractItem( parentPlot ) + , start( createPosition( "start" ) ) + , startDir( createPosition( "startDir" ) ) + , endDir( createPosition( "endDir" ) ) + , end( createPosition( "end" ) ) { start->setCoords( 0, 0 ); startDir->setCoords( 0.5, 0 ); @@ -20638,10 +23573,13 @@ void QCPItemCurve::setSelectedPen( const QPen& pen ) } /*! - Sets the line ending style of the head. The head corresponds to the \a end position. + 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 + 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 */ @@ -20651,10 +23589,13 @@ void QCPItemCurve::setHead( const QCPLineEnding& head ) } /*! - Sets the line ending style of the tail. The tail corresponds to the \a start position. + 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 + 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 */ @@ -20703,9 +23644,11 @@ void QCPItemCurve::draw( QCPPainter* painter ) cubicPath.cubicTo( startDirVec, endDirVec, endVec ); // paint visible segment, if existent: - QRect clip = clipRect().adjusted( -mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF() ); + 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 + 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 ) ) { @@ -20713,7 +23656,8 @@ void QCPItemCurve::draw( QCPPainter* painter ) 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 ); + 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 ); } @@ -20736,9 +23680,11 @@ QPen QCPItemCurve::mainPen() const /*! \class QCPItemRect \brief A rectangle - \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." + \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. + It has two positions, \a topLeft and \a bottomRight, which define the + rectangle. */ /*! @@ -20747,15 +23693,15 @@ QPen QCPItemCurve::mainPen() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemRect::QCPItemRect( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - topLeft( createPosition( "topLeft" ) ), - bottomRight( createPosition( "bottomRight" ) ), - top( createAnchor( "top", aiTop ) ), - topRight( createAnchor( "topRight", aiTopRight ) ), - right( createAnchor( "right", aiRight ) ), - bottom( createAnchor( "bottom", aiBottom ) ), - bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), - left( createAnchor( "left", aiLeft ) ) + : QCPAbstractItem( parentPlot ) + , topLeft( createPosition( "topLeft" ) ) + , bottomRight( createPosition( "bottomRight" ) ) + , top( createAnchor( "top", aiTop ) ) + , topRight( createAnchor( "topRight", aiTopRight ) ) + , right( createAnchor( "right", aiRight ) ) + , bottom( createAnchor( "bottom", aiBottom ) ) + , bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ) + , left( createAnchor( "left", aiLeft ) ) { topLeft->setCoords( 0, 1 ); bottomRight->setCoords( 1, 0 ); @@ -20791,7 +23737,8 @@ void QCPItemRect::setSelectedPen( const QPen& pen ) } /*! - Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to + Sets the brush that will be used to fill the rectangle. To disable filling, + set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen @@ -20802,7 +23749,8 @@ void QCPItemRect::setBrush( const QBrush& brush ) } /*! - Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a + Sets the brush that will be used to fill the rectangle when selected. To + disable filling, set \a brush to Qt::NoBrush. \see setBrush @@ -20834,7 +23782,8 @@ void QCPItemRect::draw( QCPPainter* painter ) 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 + if( boundingRect.intersects( clipRect() ) ) // only draw if bounding rect of rect + // item is visible in cliprect { painter->setPen( mainPen() ); painter->setBrush( mainBrush() ); @@ -20868,7 +23817,8 @@ QPointF QCPItemRect::anchorPixelPoint( int anchorId ) const /*! \internal - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + 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 @@ -20878,7 +23828,8 @@ QPen QCPItemRect::mainPen() const /*! \internal - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + 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 @@ -20893,12 +23844,16 @@ QBrush QCPItemRect::mainBrush() const /*! \class QCPItemText \brief A text label - \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." + \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. + 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 + 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. @@ -20910,16 +23865,16 @@ QBrush QCPItemRect::mainBrush() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemText::QCPItemText( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - position( createPosition( "position" ) ), - topLeft( createAnchor( "topLeft", aiTopLeft ) ), - top( createAnchor( "top", aiTop ) ), - topRight( createAnchor( "topRight", aiTopRight ) ), - right( createAnchor( "right", aiRight ) ), - bottomRight( createAnchor( "bottomRight", aiBottomRight ) ), - bottom( createAnchor( "bottom", aiBottom ) ), - bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), - left( createAnchor( "left", aiLeft ) ) + : QCPAbstractItem( parentPlot ) + , position( createPosition( "position" ) ) + , topLeft( createAnchor( "topLeft", aiTopLeft ) ) + , top( createAnchor( "top", aiTop ) ) + , topRight( createAnchor( "topRight", aiTopRight ) ) + , right( createAnchor( "right", aiRight ) ) + , bottomRight( createAnchor( "bottomRight", aiBottomRight ) ) + , bottom( createAnchor( "bottom", aiBottom ) ) + , bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ) + , left( createAnchor( "left", aiLeft ) ) { position->setCoords( 0, 0 ); @@ -20957,7 +23912,8 @@ void QCPItemText::setSelectedColor( const QColor& color ) } /*! - Sets the pen that will be used do draw a rectangular border around the text. To disable the + 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 @@ -20968,7 +23924,8 @@ void QCPItemText::setPen( const QPen& pen ) } /*! - Sets the pen that will be used do draw a rectangular border around the text, when the item is + 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 @@ -20979,7 +23936,8 @@ void QCPItemText::setSelectedPen( const QPen& pen ) } /*! - Sets the brush that will be used do fill the background of the text. To disable the + 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 @@ -20990,7 +23948,8 @@ void QCPItemText::setBrush( const QBrush& brush ) } /*! - Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the + 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 @@ -21021,7 +23980,8 @@ void QCPItemText::setSelectedFont( const QFont& font ) } /*! - Sets the text that will be displayed. Multi-line texts are supported by inserting a line break + 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 @@ -21035,12 +23995,15 @@ void QCPItemText::setText( const QString& 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 + \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 + \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 + If you want to control the alignment of (multi-lined) text within the text + rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment( Qt::Alignment alignment ) @@ -21049,7 +24012,8 @@ void QCPItemText::setPositionAlignment( Qt::Alignment alignment ) } /*! - Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or + 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 ) @@ -21058,7 +24022,8 @@ void QCPItemText::setTextAlignment( Qt::Alignment alignment ) } /*! - Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated + 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 ) @@ -21067,8 +24032,10 @@ void QCPItemText::setRotation( double 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. + 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 ) { @@ -21082,8 +24049,10 @@ double QCPItemText::selectTest( const QPointF& pos, bool onlySelectable, QVarian 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: + // 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() ); @@ -21092,7 +24061,8 @@ double QCPItemText::selectTest( const QPointF& pos, bool onlySelectable, QVarian 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() ); + QRect textBoxRect = + textRect.adjusted( -mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom() ); QPointF textPos = getTextDrawPoint( positionPixels, textBoxRect, mPositionAlignment ); textBoxRect.moveTopLeft( textPos.toPoint() ); @@ -21108,10 +24078,13 @@ void QCPItemText::draw( QCPPainter* painter ) 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 + 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(); @@ -21143,9 +24116,11 @@ QPointF QCPItemText::anchorPixelPoint( int anchorId ) const 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 + 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 ) ); @@ -21175,15 +24150,22 @@ QPointF QCPItemText::anchorPixelPoint( int anchorId ) const /*! \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 + 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. + 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 +QPointF QCPItemText::getTextDrawPoint( const QPointF& pos, + const QRectF& rect, + Qt::Alignment positionAlignment ) const { if( positionAlignment == 0 || positionAlignment == ( Qt::AlignLeft | Qt::AlignTop ) ) return pos; @@ -21202,7 +24184,8 @@ QPointF QCPItemText::getTextDrawPoint( const QPointF& pos, const QRectF& rect, Q /*! \internal - Returns the font that should be used for drawing text. Returns mFont when the item is not selected + 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 @@ -21212,7 +24195,8 @@ QFont QCPItemText::mainFont() const /*! \internal - Returns the color that should be used for drawing text. Returns mColor when the item is not + 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 @@ -21222,7 +24206,8 @@ QColor QCPItemText::mainColor() const /*! \internal - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + 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 @@ -21232,7 +24217,8 @@ QPen QCPItemText::mainPen() const /*! \internal - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + 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 @@ -21247,9 +24233,11 @@ QBrush QCPItemText::mainBrush() const /*! \class QCPItemEllipse \brief An ellipse - \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." + \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. + It has two positions, \a topLeft and \a bottomRight, which define the rect the + ellipse will be drawn in. */ /*! @@ -21258,18 +24246,18 @@ QBrush QCPItemText::mainBrush() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemEllipse::QCPItemEllipse( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - topLeft( createPosition( "topLeft" ) ), - bottomRight( createPosition( "bottomRight" ) ), - topLeftRim( createAnchor( "topLeftRim", aiTopLeftRim ) ), - top( createAnchor( "top", aiTop ) ), - topRightRim( createAnchor( "topRightRim", aiTopRightRim ) ), - right( createAnchor( "right", aiRight ) ), - bottomRightRim( createAnchor( "bottomRightRim", aiBottomRightRim ) ), - bottom( createAnchor( "bottom", aiBottom ) ), - bottomLeftRim( createAnchor( "bottomLeftRim", aiBottomLeftRim ) ), - left( createAnchor( "left", aiLeft ) ), - center( createAnchor( "center", aiCenter ) ) + : QCPAbstractItem( parentPlot ) + , topLeft( createPosition( "topLeft" ) ) + , bottomRight( createPosition( "bottomRight" ) ) + , topLeftRim( createAnchor( "topLeftRim", aiTopLeftRim ) ) + , top( createAnchor( "top", aiTop ) ) + , topRightRim( createAnchor( "topRightRim", aiTopRightRim ) ) + , right( createAnchor( "right", aiRight ) ) + , bottomRightRim( createAnchor( "bottomRightRim", aiBottomRightRim ) ) + , bottom( createAnchor( "bottom", aiBottom ) ) + , bottomLeftRim( createAnchor( "bottomLeftRim", aiBottomLeftRim ) ) + , left( createAnchor( "left", aiLeft ) ) + , center( createAnchor( "center", aiCenter ) ) { topLeft->setCoords( 0, 1 ); bottomRight->setCoords( 1, 0 ); @@ -21305,7 +24293,8 @@ void QCPItemEllipse::setSelectedPen( const QPen& pen ) } /*! - Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to + Sets the brush that will be used to fill the ellipse. To disable filling, set + \a brush to Qt::NoBrush. \see setSelectedBrush, setPen @@ -21316,7 +24305,8 @@ void QCPItemEllipse::setBrush( const QBrush& brush ) } /*! - Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a + Sets the brush that will be used to fill the ellipse when selected. To disable + filling, set \a brush to Qt::NoBrush. \see setBrush @@ -21327,7 +24317,9 @@ void QCPItemEllipse::setSelectedBrush( const QBrush& brush ) } /* inherits documentation from base class */ -double QCPItemEllipse::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +double QCPItemEllipse::selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details ) const { Q_UNUSED( details ) if( onlySelectable && !mSelectable ) @@ -21363,8 +24355,10 @@ void QCPItemEllipse::draw( QCPPainter* painter ) 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 + 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() ); @@ -21416,7 +24410,8 @@ QPointF QCPItemEllipse::anchorPixelPoint( int anchorId ) const /*! \internal - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + 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 @@ -21426,7 +24421,8 @@ QPen QCPItemEllipse::mainPen() const /*! \internal - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + 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 @@ -21441,14 +24437,19 @@ QBrush QCPItemEllipse::mainBrush() const /*! \class QCPItemPixmap \brief An arbitrary pixmap - \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." + \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 + 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 + 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. */ @@ -21458,15 +24459,15 @@ QBrush QCPItemEllipse::mainBrush() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemPixmap::QCPItemPixmap( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - topLeft( createPosition( "topLeft" ) ), - bottomRight( createPosition( "bottomRight" ) ), - top( createAnchor( "top", aiTop ) ), - topRight( createAnchor( "topRight", aiTopRight ) ), - right( createAnchor( "right", aiRight ) ), - bottom( createAnchor( "bottom", aiBottom ) ), - bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ), - left( createAnchor( "left", aiLeft ) ) + : QCPAbstractItem( parentPlot ) + , topLeft( createPosition( "topLeft" ) ) + , bottomRight( createPosition( "bottomRight" ) ) + , top( createAnchor( "top", aiTop ) ) + , topRight( createAnchor( "topRight", aiTopRight ) ) + , right( createAnchor( "right", aiRight ) ) + , bottom( createAnchor( "bottom", aiBottom ) ) + , bottomLeft( createAnchor( "bottomLeft", aiBottomLeft ) ) + , left( createAnchor( "left", aiLeft ) ) { topLeft->setCoords( 0, 1 ); bottomRight->setCoords( 1, 0 ); @@ -21491,7 +24492,8 @@ void QCPItemPixmap::setPixmap( const QPixmap& pixmap ) } /*! - Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a + 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 ) @@ -21512,7 +24514,8 @@ void QCPItemPixmap::setPen( const QPen& pen ) } /*! - Sets the pen that will be used to draw a border around the pixmap when selected + Sets the pen that will be used to draw a border around the pixmap when + selected \see setPen, setSelected */ @@ -21589,13 +24592,18 @@ QPointF QCPItemPixmap::anchorPixelPoint( int anchorId ) const /*! \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 + 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 + 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. @@ -21611,9 +24619,11 @@ void QCPItemPixmap::updateScaledPixmap( QRect finalRect, bool flipHorz, bool fli finalRect = getFinalRect( &flipHorz, &flipVert ); if( finalRect.size() != mScaledPixmap.size() ) { - mScaledPixmap = mPixmap.scaled( finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation ); + mScaledPixmap = + mPixmap.scaled( finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation ); if( flipHorz || flipVert ) - mScaledPixmap = QPixmap::fromImage( mScaledPixmap.toImage().mirrored( flipHorz, flipVert ) ); + mScaledPixmap = + QPixmap::fromImage( mScaledPixmap.toImage().mirrored( flipHorz, flipVert ) ); } } else if( !mScaledPixmap.isNull() ) @@ -21622,17 +24632,24 @@ void QCPItemPixmap::updateScaledPixmap( QRect finalRect, bool flipHorz, bool fli /*! \internal - Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions + 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 + 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. + 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 { @@ -21676,7 +24693,8 @@ QRect QCPItemPixmap::getFinalRect( bool* flippedHorz, bool* flippedVert ) const /*! \internal - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + 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 @@ -21691,31 +24709,46 @@ QPen QCPItemPixmap::mainPen() const /*! \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." + \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 + 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 + 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 + 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 + 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. + \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. */ /*! @@ -21773,7 +24806,8 @@ void QCPItemTracer::setBrush( const QBrush& brush ) } /*! - Sets the brush that will be used to draw any fills of the tracer, when selected. + Sets the brush that will be used to draw any fills of the tracer, when + selected. \see setBrush, setSelected */ @@ -21783,7 +24817,8 @@ void QCPItemTracer::setSelectedBrush( const QBrush& brush ) } /*! - Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare + 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 ) @@ -21794,7 +24829,8 @@ void QCPItemTracer::setSize( double 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 + 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 ) @@ -21803,11 +24839,15 @@ void QCPItemTracer::setStyle( QCPItemTracer::TracerStyle 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. + 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 + 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 @@ -21833,11 +24873,14 @@ void QCPItemTracer::setGraph( QCPGraph* graph ) } /*! - Sets the key of the graph's data point the tracer will be positioned at. This is the only free + 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. + 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 */ @@ -21847,13 +24890,18 @@ void QCPItemTracer::setGraphKey( double key ) } /*! - Sets whether the value of the graph's data points shall be interpolated, when positioning the + 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. + 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 */ @@ -21878,16 +24926,19 @@ double QCPItemTracer::selectTest( const QPointF& pos, bool onlySelectable, QVari 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 ) ) ); + 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 ) ) ); + 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: { @@ -21971,13 +25022,19 @@ void QCPItemTracer::draw( QCPPainter* painter ) } /*! - 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). + 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 + 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. @@ -22008,7 +25065,8 @@ void QCPItemTracer::updatePosition() 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 ); + position->setCoords( mGraphKey, + ( mGraphKey - prevIt.key() ) * slope + prevIt.value().value ); } else { @@ -22037,7 +25095,8 @@ void QCPItemTracer::updatePosition() /*! \internal - Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + 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 @@ -22047,7 +25106,8 @@ QPen QCPItemTracer::mainPen() const /*! \internal - Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + 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 @@ -22062,20 +25122,27 @@ QBrush QCPItemTracer::mainBrush() const /*! \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." + \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 + 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 + 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.
    +
    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 + 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. */ @@ -22085,10 +25152,10 @@ QBrush QCPItemTracer::mainBrush() const The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemBracket::QCPItemBracket( QCustomPlot* parentPlot ) - : QCPAbstractItem( parentPlot ), - left( createPosition( "left" ) ), - right( createPosition( "right" ) ), - center( createAnchor( "center", aiCenter ) ) + : QCPAbstractItem( parentPlot ) + , left( createPosition( "left" ) ) + , right( createPosition( "right" ) ) + , center( createAnchor( "center", aiCenter ) ) { left->setCoords( 0, 0 ); right->setCoords( 1, 1 ); @@ -22106,8 +25173,10 @@ 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 + 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 @@ -22128,12 +25197,16 @@ void QCPItemBracket::setSelectedPen( const QPen& 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) + 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.
    +
    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 ) { @@ -22151,7 +25224,9 @@ void QCPItemBracket::setStyle( QCPItemBracket::BracketStyle style ) } /* inherits documentation from base class */ -double QCPItemBracket::selectTest( const QPointF& pos, bool onlySelectable, QVariant* details ) const +double QCPItemBracket::selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details ) const { Q_UNUSED( details ) if( onlySelectable && !mSelectable ) @@ -22167,7 +25242,8 @@ double QCPItemBracket::selectTest( const QPointF& pos, bool onlySelectable, QVar lengthVec = lengthVec.normalized() * mLength; QVector2D centerVec = ( rightVec + leftVec ) * 0.5f - lengthVec; - return qSqrt( distSqrToLine( ( centerVec - widthVec ).toPointF(), ( centerVec + widthVec ).toPointF(), pos ) ); + return qSqrt( distSqrToLine( ( centerVec - widthVec ).toPointF(), + ( centerVec + widthVec ).toPointF(), pos ) ); } /* inherits documentation from base class */ @@ -22186,7 +25262,8 @@ void QCPItemBracket::draw( QCPPainter* painter ) 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() ); + QRect clip = clipRect().adjusted( -mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), + mainPen().widthF() ); if( clip.intersects( boundingPoly.boundingRect() ) ) { painter->setPen( mainPen() ); @@ -22194,9 +25271,12 @@ void QCPItemBracket::draw( QCPPainter* painter ) { 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() ); + 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: @@ -22204,7 +25284,8 @@ void QCPItemBracket::draw( QCPPainter* painter ) 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.toPointF() ); path.cubicTo( ( centerVec - widthVec ).toPointF(), ( centerVec - widthVec ).toPointF(), ( centerVec - widthVec + lengthVec ).toPointF() ); painter->drawPath( path ); @@ -22216,7 +25297,8 @@ void QCPItemBracket::draw( QCPPainter* painter ) QPainterPath path; path.moveTo( ( centerVec + widthVec + lengthVec ).toPointF() ); path.cubicTo( ( centerVec + widthVec - lengthVec * 0.8f ).toPointF(), - ( centerVec + 0.4f * widthVec + lengthVec ).toPointF(), centerVec.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() ); @@ -22231,7 +25313,8 @@ void QCPItemBracket::draw( QCPPainter* painter ) path.moveTo( ( centerVec + widthVec + lengthVec ).toPointF() ); path.cubicTo( ( centerVec + widthVec - lengthVec * 0.8f ).toPointF(), - ( centerVec + 0.4f * widthVec + 0.8f * lengthVec ).toPointF(), centerVec.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() ); diff --git a/app/external/qcustomplot.h b/app/external/qcustomplot.h index de6d57f..d6b5721 100644 --- a/app/external/qcustomplot.h +++ b/app/external/qcustomplot.h @@ -26,29 +26,29 @@ #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 #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 +#include +#include #else #include #include @@ -85,7 +85,8 @@ class QCPColorScale; #endif /*! - The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library + The QCP Namespace contains general enums and QFlags used throughout the + QCustomPlot library */ namespace QCP { @@ -111,13 +112,17 @@ enum MarginSide 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. + 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 + \see QCustomPlot::setAntialiasedElements, + QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { @@ -131,16 +136,18 @@ enum AntialiasedElement , aeLegendItems = 0x0010 ///< 0x0010 Legend items , - aePlottables = - 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) + 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) + 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) + aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between + /// graphs) , aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen , @@ -151,7 +158,8 @@ enum AntialiasedElement Q_DECLARE_FLAGS( AntialiasedElements, AntialiasedElement ) /*! - Defines plotting hints that control various aspects of the quality and speed of plotting. + Defines plotting hints that control various aspects of the quality and speed + of plotting. \see QCustomPlot::setPlottingHints */ @@ -159,17 +167,20 @@ 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.) + 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 + 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. + phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as + /// pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS( PlottingHints, PlottingHint ) @@ -182,35 +193,42 @@ Q_DECLARE_FLAGS( PlottingHints, PlottingHint ) */ enum Interaction { - iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref - /// QCPAxisRect::setRangeDragAxes) + 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) + 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 + 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) + 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) + 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) + 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) + 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,...) + 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 + 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 ) @@ -260,7 +278,8 @@ inline void setMarginValue( QMargins& margins, QCP::MarginSide side, int value ) /*! \internal - Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or + 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 @@ -297,17 +316,21 @@ class QCP_LIB_DECL QCPScatterStyle /*! 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 + 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) + 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) + 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 , @@ -315,31 +338,40 @@ class QCP_LIB_DECL QCPScatterStyle , 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) + 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 + 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 + ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing + /// on baseline , - ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner + ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral + /// triangle, standing on corner , - ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside + 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 + 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 + 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 + 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) + ssCustom ///< custom painter operations are performed per scatter (As + /// QPainterPath, see \ref setCustomPath) }; QCPScatterStyle(); @@ -394,7 +426,8 @@ 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 + 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. */ @@ -402,14 +435,18 @@ class QCP_LIB_DECL QCPPainter : public QPainter { 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. + 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 + 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.) + 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 ) @@ -541,7 +578,10 @@ class QCP_LIB_DECL QCPLayerable : public QObject 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // non-property methods: @@ -708,14 +748,17 @@ class QCP_LIB_DECL QCPMarginGroup : public QObject ~QCPMarginGroup(); // non-virtual methods: - QList elements( QCP::MarginSide side ) const { return mChildren.value( side ); } + QList elements( QCP::MarginSide side ) const + { + return mChildren.value( side ); + } bool isEmpty() const; void clear(); protected: // non-property members: QCustomPlot* mParentPlot; - QHash > mChildren; + QHash> mChildren; // non-virtual methods: int commonMargin( QCP::MarginSide side ) const; @@ -742,17 +785,20 @@ class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable /// \endcond public: /*! - Defines the phases of the update process, that happens just before a replot. At each phase, + 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 + 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 + upLayout ///< Final phase in which the layout system places the rects of the + /// elements }; Q_ENUMS( UpdatePhase ) @@ -768,7 +814,10 @@ class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable 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 ); } + QCPMarginGroup* marginGroup( QCP::MarginSide side ) const + { + return mMarginGroups.value( side, (QCPMarginGroup*)0 ); + } QHash marginGroups() const { return mMarginGroups; } // setters: void setOuterRect( const QRect& rect ); @@ -866,7 +915,8 @@ class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout /// \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 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 ) @@ -911,7 +961,7 @@ class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout protected: // property members: - QList > mElements; + QList> mElements; QList mColumnStretchFactors; QList mRowStretchFactors; int mColumnSpacing, mRowSpacing; @@ -929,13 +979,16 @@ 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. + 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 + 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 + ipBorderAligned ///< The element is aligned to one of the layout sides, see + ///\ref setInsetAlignment }; explicit QCPLayoutInset(); @@ -984,11 +1037,14 @@ class QCP_LIB_DECL QCPLineEnding \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 + 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, + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, + QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ Q_ENUMS( EndingStyle ) @@ -1010,8 +1066,9 @@ class QCP_LIB_DECL QCPLineEnding , 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) + 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) }; @@ -1135,11 +1192,15 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable 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( 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 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 ) @@ -1150,34 +1211,43 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable /// \endcond public: /*! - Defines at which side of the axis rect the axis will appear. This also affects how the tick + 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 + 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 + 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 + 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 + 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 + 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) + 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) + 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 ) /*! @@ -1188,8 +1258,9 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable { stLinear ///< Linear scaling , - stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base - /// power (see \ref setScaleLogBase). + stLogarithmic ///< Logarithmic scaling with correspondingly transformed + /// plots and (major) tick marks at every base + /// power (see \ref setScaleLogBase). }; Q_ENUMS( ScaleType ) /*! @@ -1202,7 +1273,8 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable , spAxis = 0x001 ///< The axis backbone and tick marks , - spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, + /// not individually) , spAxisLabel = 0x004 ///< The axis label }; @@ -1385,7 +1457,8 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable double mTickStep; int mSubTickCount, mAutoTickCount; bool mAutoTicks, mAutoTickStep, mAutoSubTicks; - // int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + // int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // + // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: @@ -1415,7 +1488,10 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // non-virtual methods: @@ -1465,8 +1541,9 @@ class QCPAxisPainterPrivate int tickLabelPadding; // directly accessed by QCPAxis setters/getters double tickLabelRotation; // 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 + 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; @@ -1492,7 +1569,8 @@ class QCPAxisPainterPrivate QFont baseFont, expFont; }; QCustomPlot* mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to + // be cleared due to changed parameters QCache mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; @@ -1503,10 +1581,15 @@ class QCPAxisPainterPrivate int distanceToAxis, const QString& text, QSize* tickLabelsSize ); - virtual void drawTickLabel( QCPPainter* painter, double x, double y, const TickLabelData& labelData ) const; + 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; + virtual void getMaxTickLabelSize( const QFont& font, + const QString& text, + QSize* tickLabelsSize ) const; }; class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable @@ -1558,7 +1641,9 @@ class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable // introduced virtual methods: virtual void clearData() = 0; - virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const = 0; + virtual double selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details = 0 ) const = 0; virtual bool addToLegend(); virtual bool removeFromLegend() const; @@ -1573,7 +1658,8 @@ class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable protected: /*! - Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. + Represents negative and positive sign domain for passing to \ref getKeyRange + and \ref getValueRange. */ enum SignDomain { @@ -1598,7 +1684,10 @@ class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // introduced virtual methods: @@ -1629,7 +1718,10 @@ class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable class QCP_LIB_DECL QCPItemAnchor { public: - QCPItemAnchor( QCustomPlot* parentPlot, QCPAbstractItem* parentItem, const QString name, int anchorId = -1 ); + QCPItemAnchor( QCustomPlot* parentPlot, + QCPAbstractItem* parentItem, + const QString name, + int anchorId = -1 ); virtual ~QCPItemAnchor(); // getters: @@ -1650,7 +1742,8 @@ class QCP_LIB_DECL QCPItemAnchor virtual QCPItemPosition* toQCPItemPosition() { return 0; } // non-virtual methods: void addChild( QCPItemPosition* pos ); // called from pos when this anchor is set as parent - void removeChild( QCPItemPosition* pos ); // called from pos when its parent anchor is reset or pos deleted + void removeChild( QCPItemPosition* pos ); // called from pos when its parent + // anchor is reset or pos deleted private: Q_DISABLE_COPY( QCPItemAnchor ) @@ -1662,29 +1755,37 @@ 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 + 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. + 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 + 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 + 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 + ///< 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). + ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two + /// axes (see \ref setAxes). }; QCPItemPosition( QCustomPlot* parentPlot, QCPAbstractItem* parentItem, const QString name ); @@ -1749,7 +1850,9 @@ class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable Q_SLOT void setSelected( bool selected ); // reimplemented virtual methods: - virtual double selectTest( const QPointF& pos, bool onlySelectable, QVariant* details = 0 ) const = 0; + virtual double selectTest( const QPointF& pos, + bool onlySelectable, + QVariant* details = 0 ) const = 0; // non-virtual methods: QList positions() const { return mPositions; } @@ -1776,7 +1879,10 @@ class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // introduced virtual methods: @@ -1802,12 +1908,15 @@ class QCP_LIB_DECL QCustomPlot : public QWidget 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( Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE + setBackgroundScaledMode ) Q_PROPERTY( QCPLayoutGrid* plotLayout READ plotLayout ) - Q_PROPERTY( bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend ) + 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 ) + Q_PROPERTY( Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE + setMultiSelectModifier ) /// \endcond public: /*! @@ -1824,19 +1933,23 @@ class QCP_LIB_DECL QCustomPlot : public QWidget Q_ENUMS( LayerInsertMode ) /*! - Defines with what timing the QCustomPlot surface is refreshed after a replot. + 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 + 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 + 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. + 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 ); @@ -1859,14 +1972,17 @@ class QCP_LIB_DECL QCustomPlot : public QWidget // 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 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& notAntialiasedElements ); - void setNotAntialiasedElement( QCP::AntialiasedElement notAntialiasedElement, bool enabled = true ); + 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 ); @@ -1918,7 +2034,9 @@ class QCP_LIB_DECL QCustomPlot : public QWidget bool setCurrentLayer( const QString& name ); bool setCurrentLayer( QCPLayer* layer ); int layerCount() const; - bool addLayer( const QString& name, QCPLayer* otherLayer = 0, LayerInsertMode insertMode = limAbove ); + bool addLayer( const QString& name, + QCPLayer* otherLayer = 0, + LayerInsertMode insertMode = limAbove ); bool removeLayer( QCPLayer* layer ); bool moveLayer( QCPLayer* layer, QCPLayer* otherLayer, LayerInsertMode insertMode = limAbove ); @@ -1939,8 +2057,16 @@ class QCP_LIB_DECL QCustomPlot : public QWidget int height = 0, const QString& pdfCreator = "", const QString& pdfTitle = "" ); - 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 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, @@ -1983,7 +2109,8 @@ class QCP_LIB_DECL QCustomPlot : public QWidget QCPLayoutGrid* mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mGraphs; // extra list of plottables also in mPlottables + // that are of type QCPGraph QList mItems; QList mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; @@ -2023,7 +2150,9 @@ class QCP_LIB_DECL QCustomPlot : public QWidget // non-virtual methods: void updateLayerIndices() const; - QCPLayerable* layerableAt( const QPointF& pos, bool onlySelectable, QVariant* selectionDetails = 0 ) const; + QCPLayerable* layerableAt( const QPointF& pos, + bool onlySelectable, + QVariant* selectionDetails = 0 ) const; void drawBackground( QCPPainter* painter ); friend class QCPLegend; @@ -2037,7 +2166,8 @@ class QCP_LIB_DECL QCPColorGradient Q_GADGET public: /*! - Defines the color spaces in which color interpolation between gradient stops can be performed. + Defines the color spaces in which color interpolation between gradient stops + can be performed. \see setColorInterpolation */ @@ -2045,46 +2175,59 @@ class QCP_LIB_DECL QCPColorGradient { 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) + 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 + 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) + 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) + 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) + 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) + 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 + 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) + 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 + 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 + 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) + 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) + 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) + 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 ) @@ -2135,7 +2278,8 @@ class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement /// \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::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 @@ -2155,7 +2299,9 @@ class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement // setters: void setBackground( const QPixmap& pm ); - void setBackground( const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding ); + 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 ); @@ -2213,7 +2359,7 @@ class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QPoint mDragStart; bool mDragging; - QHash > mAxes; + QHash> mAxes; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint( QCPPainter* painter ) const; @@ -2288,7 +2434,10 @@ class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); private: @@ -2330,8 +2479,10 @@ class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid 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( 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 ) @@ -2350,7 +2501,8 @@ class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid , spLegendBox = 0x001 ///< 0x001 The legend box (frame) , - spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + spItems = 0x002 ///< 0x002 Legend items individually (see \ref + /// selectedItems) }; Q_FLAGS( SelectablePart SelectableParts ) Q_DECLARE_FLAGS( SelectableParts, SelectablePart ) @@ -2429,7 +2581,10 @@ class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid 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 selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // non-virtual methods: @@ -2501,7 +2656,10 @@ class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // events: - virtual void selectEvent( QMouseEvent* event, bool additive, const QVariant& details, bool* selectionStateChanged ); + virtual void selectEvent( QMouseEvent* event, + bool additive, + const QVariant& details, + bool* selectionStateChanged ); virtual void deselectEvent( bool* selectionStateChanged ); // non-virtual methods: @@ -2522,7 +2680,8 @@ class QCPColorScaleAxisRectPrivate : public QCPAxisRect QCPColorScale* mParentColorScale; QImage mGradientImage; bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + // re-using some methods of QCPAxisRect to make them available to friend class + // QCPColorScale using QCPAxisRect::calculateAutoMargin; using QCPAxisRect::mousePressEvent; using QCPAxisRect::mouseMoveEvent; @@ -2542,7 +2701,8 @@ class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement /// \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( 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 ) @@ -2651,25 +2811,31 @@ class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable /// \endcond public: /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the + 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) + 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 + 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 + 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 + 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 + 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 ) /*! @@ -2683,7 +2849,8 @@ class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable , 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 + etBoth ///< Error bars for both key and value dimensions of the data point + /// are shown }; Q_ENUMS( ErrorType ) @@ -2703,12 +2870,16 @@ class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable // 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& 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& valueError ); void setDataValueError( const QVector& key, const QVector& value, const QVector& valueErrorMinus, @@ -2748,9 +2919,12 @@ class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable 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 + 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: @@ -2789,10 +2963,12 @@ class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable 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 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; + 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; @@ -2823,7 +2999,8 @@ class QCP_LIB_DECL QCPCurveData Q_DECLARE_TYPEINFO( QCPCurveData, Q_MOVABLE_TYPE ); /*! \typedef QCPCurveDataMap - Container for storing QCPCurveData items in a sorted fashion. The key of the map + Container for storing 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. @@ -2843,7 +3020,8 @@ class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable /// \endcond public: /*! - Defines how the curve's line is represented visually in the plot. The line is drawn with the + 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 */ @@ -2862,7 +3040,9 @@ class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable 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& t, + const QVector& key, + const QVector& value ); void setData( const QVector& key, const QVector& value ); void setScatterStyle( const QCPScatterStyle& style ); void setLineStyle( LineStyle style ); @@ -2872,7 +3052,9 @@ class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable 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 addData( const QVector& ts, + const QVector& keys, + const QVector& values ); void removeDataBefore( double t ); void removeDataAfter( double t ); void removeData( double fromt, double tot ); @@ -3032,7 +3214,12 @@ class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable 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 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 ); @@ -3072,7 +3259,10 @@ class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable class QCP_LIB_DECL QCPColorMapData { public: - QCPColorMapData( int keySize, int valueSize, const QCPRange& keyRange, const QCPRange& valueRange ); + QCPColorMapData( int keySize, + int valueSize, + const QCPRange& keyRange, + const QCPRange& valueRange ); ~QCPColorMapData(); QCPColorMapData( const QCPColorMapData& other ); QCPColorMapData& operator=( const QCPColorMapData& other ); @@ -3122,7 +3312,8 @@ 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( 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 ) @@ -3222,8 +3413,12 @@ class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem 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; + 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; }; @@ -3266,7 +3461,9 @@ class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem virtual void draw( QCPPainter* painter ); // non-virtual methods: - QLineF getRectClippedLine( const QVector2D& start, const QVector2D& end, const QRect& rect ) const; + QLineF getRectClippedLine( const QVector2D& start, + const QVector2D& end, + const QRect& rect ) const; QPen mainPen() const; }; @@ -3467,7 +3664,9 @@ class QCP_LIB_DECL QCPItemText : public QCPAbstractItem virtual QPointF anchorPixelPoint( int anchorId ) const; // non-virtual methods: - QPointF getTextDrawPoint( const QPointF& pos, const QRectF& rect, Qt::Alignment positionAlignment ) const; + QPointF getTextDrawPoint( const QPointF& pos, + const QRectF& rect, + Qt::Alignment positionAlignment ) const; QFont mainFont() const; QColor mainColor() const; QPen mainPen() const; @@ -3601,7 +3800,9 @@ class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem virtual QPointF anchorPixelPoint( int anchorId ) const; // non-virtual methods: - void updateScaledPixmap( QRect finalRect = QRect(), bool flipHorz = false, bool flipVert = false ); + void updateScaledPixmap( QRect finalRect = QRect(), + bool flipHorz = false, + bool flipVert = false ); QRect getFinalRect( bool* flippedHorz = 0, bool* flippedVert = 0 ) const; QPen mainPen() const; }; @@ -3622,7 +3823,8 @@ class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem /// \endcond public: /*! - The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. + The different visual appearances a tracer item can have. Some styles size + may be controlled with \ref setSize. \see setStyle */ @@ -3708,7 +3910,8 @@ class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem , bsCurly ///< A curly brace , - bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression + bsCalligraphic ///< A curly brace with varying stroke width giving a + /// calligraphic impression }; QCPItemBracket( QCustomPlot* parentPlot ); diff --git a/app/main.cpp b/app/main.cpp index ad6191a..7a3d9db 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -22,12 +22,12 @@ * \brief main file */ +#include "ConfigureFormatDialog.h" +#include "PlaYUVerApp.h" +#include "PlaYUVerAppDefs.h" +#include "VideoSubWindow.h" #include "config.h" #include -#include "PlaYUVerAppDefs.h" -#include "PlaYUVerApp.h" -#include "VideoSubWindow.h" -#include "ConfigureFormatDialog.h" #ifdef USE_QTDBUS #include "PlaYUVerAppAdaptor.h" #endif @@ -74,16 +74,17 @@ int main( int argc, char* argv[] ) bool foundRunningService = false; if( !force_new ) { - QDBusReply there = sessionBusInterface->isServiceRegistered( PLAYUVER_DBUS_SESSION_NAME ); + QDBusReply there = + sessionBusInterface->isServiceRegistered( PLAYUVER_DBUS_SESSION_NAME ); foundRunningService = there.isValid() && there.value(); } if( foundRunningService ) { // open given session - QDBusMessage m = - QDBusMessage::createMethodCall( PLAYUVER_DBUS_SESSION_NAME, QStringLiteral( PLAYUVER_DBUS_PATH ), - QStringLiteral( PLAYUVER_DBUS_SESSION_NAME ), QStringLiteral( "activate" ) ); + QDBusMessage m = QDBusMessage::createMethodCall( + PLAYUVER_DBUS_SESSION_NAME, QStringLiteral( PLAYUVER_DBUS_PATH ), + QStringLiteral( PLAYUVER_DBUS_SESSION_NAME ), QStringLiteral( "activate" ) ); QDBusConnection::sessionBus().call( m ); @@ -120,7 +121,8 @@ int main( int argc, char* argv[] ) } } } - // this will wait until exiting is emitted by the used instance, if wanted... + // this will wait until exiting is emitted by the used instance, if + // wanted... return needToBlock ? application.exec() : 0; } } @@ -138,8 +140,9 @@ int main( int argc, char* argv[] ) } #ifdef USE_FERVOR - FvUpdater::sharedUpdater()->SetFeedURL( "http://192.168.96.201/share/PlaYUVerProject/PlaYUVerUpdate-" UPDATE_CHANNEL - ".xml" ); + FvUpdater::sharedUpdater()->SetFeedURL( + "http://192.168.96.201/share/PlaYUVerProject/" + "PlaYUVerUpdate-" UPDATE_CHANNEL ".xml" ); FvUpdater::sharedUpdater()->SetDependencies( "ALL" ); #endif diff --git a/lib/PlaYUVerDefs.h b/lib/PlaYUVerDefs.h index c2e4951..f3bbaeb 100644 --- a/lib/PlaYUVerDefs.h +++ b/lib/PlaYUVerDefs.h @@ -82,10 +82,14 @@ typedef UChar Byte; // Limits definition // ==================================================================================================================== -// #define MAX_UINT 0xFFFFFFFFU ///< max. value of unsigned 32-bit integer -// #define MAX_INT 2147483647 ///< max. value of signed 32-bit integer -// #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of signed 64-bit integer -// #define MAX_DOUBLE 1.7e+308 ///< max. value of double-type value +// #define MAX_UINT 0xFFFFFFFFU ///< max. value of unsigned +// 32-bit integer +// #define MAX_INT 2147483647 ///< max. value of signed +// 32-bit integer +// #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL ///< max. value of +// signed 64-bit integer +// #define MAX_DOUBLE 1.7e+308 ///< max. value of +// double-type value // ==================================================================================================================== // PlaYUVer definitions @@ -139,7 +143,8 @@ struct PlaYUVerFailure : public std::exception String m_class_name; String m_error_msg; PlaYUVerFailure( String error_msg ) throw() : m_error_msg( error_msg ) {} - PlaYUVerFailure( String class_name, String error_msg ) throw() : m_class_name( class_name ), m_error_msg( error_msg ) + PlaYUVerFailure( String class_name, String error_msg ) throw() + : m_class_name( class_name ), m_error_msg( error_msg ) { } ~PlaYUVerFailure() throw() {} diff --git a/lib/PlaYUVerFrame.cpp b/lib/PlaYUVerFrame.cpp index 2c1d7f9..3a1c13e 100644 --- a/lib/PlaYUVerFrame.cpp +++ b/lib/PlaYUVerFrame.cpp @@ -22,8 +22,8 @@ * \brief Video Frame handling */ -#include "config.h" #include "PlaYUVerFrame.h" +#include "config.h" #include #ifdef USE_OPENCV @@ -75,12 +75,18 @@ Int PlaYUVerFrame::findPixelFormat( const String& name ) return -1; } -static Int getImgMemory( Pel**** array3D, Int dim1, Int dim2, Int log2ChromaHeight, Int log2ChromaWidth ) +static Int getImgMemory( Pel**** array3D, + Int dim1, + Int dim2, + Int log2ChromaHeight, + Int log2ChromaWidth ) { Int dim0 = 3; Int i; UInt64 total_mem_size = 0; - UInt64 mem_size = ( dim1 * dim2 + CHROMASHIFT( dim1, log2ChromaHeight ) * CHROMASHIFT( dim2, log2ChromaWidth ) * 2 ); + UInt64 mem_size = + ( dim1 * dim2 + + CHROMASHIFT( dim1, log2ChromaHeight ) * CHROMASHIFT( dim2, log2ChromaWidth ) * 2 ); total_mem_size += getMem2D( array3D, dim0, dim1 ); @@ -130,7 +136,8 @@ struct PlaYUVerFramePrivate UInt m_uiWidth; //!< Width of the frame UInt m_uiHeight; //!< Height of the frame - Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported pixel formats) + Int m_iPixelFormat; //!< Pixel format number (it follows the list of supported + //! pixel formats) Int m_iNumberChannels; //!< Number of channels UInt m_uiBitsPel; //!< Bits per pixel/channel // Int m_iEndianness; //!< Endiannes of bytes @@ -215,7 +222,8 @@ struct PlaYUVerFramePrivate * \brief Constructors */ -PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) : d( new PlaYUVerFramePrivate ) +PlaYUVerFrame::PlaYUVerFrame( UInt width, UInt height, Int pelFormat, Int bitsPixel ) + : d( new PlaYUVerFramePrivate ) { d->init( width, height, pelFormat, bitsPixel ); } @@ -238,7 +246,8 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame* other ) : d( new PlaYUVerFram PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt width, UInt height ) : d( new PlaYUVerFramePrivate ) { - const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other.getPelFormat()] ); + const PlaYUVerPixFmtDescriptor* pcPelFormat = + &( g_PlaYUVerPixFmtDescriptorsList[other.getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) { if( x % ( 1 << pcPelFormat->log2ChromaWidth ) ) @@ -260,13 +269,18 @@ PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame& other, UInt x, UInt y, UInt w copyFrom( other, x, y ); } -PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame* other, UInt posX, UInt posY, UInt areaWidth, UInt areaHeight ) +PlaYUVerFrame::PlaYUVerFrame( const PlaYUVerFrame* other, + UInt posX, + UInt posY, + UInt areaWidth, + UInt areaHeight ) : d( new PlaYUVerFramePrivate ) { if( !other ) return; - const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); + const PlaYUVerPixFmtDescriptor* pcPelFormat = + &( g_PlaYUVerPixFmtDescriptorsList[other->getPelFormat()] ); if( pcPelFormat->log2ChromaWidth ) { if( posX % ( 1 << pcPelFormat->log2ChromaWidth ) ) @@ -320,7 +334,8 @@ Bool PlaYUVerFrame::haveSameFmt( const PlaYUVerFrame& other, UInt match ) const if( match & MATCH_BITS ) bRet &= ( getBitsPel() == other.getBitsPel() ); if( match & MATCH_COLOR_SPACE_IGNORE_GRAY ) - bRet &= ( getColorSpace() == PlaYUVerPixel::COLOR_GRAY || getColorSpace() == other.getColorSpace() ); + bRet &= ( getColorSpace() == PlaYUVerPixel::COLOR_GRAY || + getColorSpace() == other.getColorSpace() ); return bRet; } @@ -407,15 +422,18 @@ UInt64 PlaYUVerFrame::getBytesPerFrame() return getBytesPerFrame( d->m_uiWidth, d->m_uiHeight, d->m_iPixelFormat, d->m_uiBitsPel ); } -UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, UInt uiHeight, Int iPixelFormat, UInt bitsPixel ) +UInt64 PlaYUVerFrame::getBytesPerFrame( UInt uiWidth, + UInt uiHeight, + Int iPixelFormat, + UInt bitsPixel ) { const PlaYUVerPixFmtDescriptor* pcPelFormat = &( g_PlaYUVerPixFmtDescriptorsList[iPixelFormat] ); UInt bytesPerPixel = ( bitsPixel - 1 ) / 8 + 1; UInt64 numberBytes = uiWidth * uiHeight; if( pcPelFormat->numberChannels > 1 ) { - UInt64 numberBytesChroma = - CHROMASHIFT( uiWidth, pcPelFormat->log2ChromaWidth ) * CHROMASHIFT( uiHeight, pcPelFormat->log2ChromaHeight ); + UInt64 numberBytesChroma = CHROMASHIFT( uiWidth, pcPelFormat->log2ChromaWidth ) * + CHROMASHIFT( uiHeight, pcPelFormat->log2ChromaHeight ); numberBytes += ( pcPelFormat->numberChannels - 1 ) * numberBytesChroma; } return numberBytes * bytesPerPixel; @@ -432,7 +450,8 @@ Void PlaYUVerFrame::clear() ratioW = ch > 0 ? d->m_pcPelFormat->log2ChromaWidth : 0; ratioH = ch > 0 ? d->m_pcPelFormat->log2ChromaHeight : 0; pPel = d->m_pppcInputPel[ch][0]; - for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); + i++ ) { *pPel++ = uiValue; } @@ -480,7 +499,9 @@ PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos ) return PixelValue; } -PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, Int yPos, PlaYUVerPixel::ColorSpace eColorSpace ) +PlaYUVerPixel PlaYUVerFrame::getPixelValue( Int xPos, + Int yPos, + PlaYUVerPixel::ColorSpace eColorSpace ) { PlaYUVerPixel PixelValue( d->m_pcPelFormat->colorSpace ); for( UInt ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) @@ -511,7 +532,8 @@ Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame& other ) return; d->m_bHasRGBPel = false; d->m_bHasHistogram = false; - memcpy( *d->m_pppcInputPel[LUMA], other.getPelBufferYUV()[LUMA][0], getBytesPerFrame() * sizeof( Pel ) ); + memcpy( *d->m_pppcInputPel[LUMA], other.getPelBufferYUV()[LUMA][0], + getBytesPerFrame() * sizeof( Pel ) ); } Void PlaYUVerFrame::copyFrom( const PlaYUVerFrame* other ) @@ -579,7 +601,9 @@ Void PlaYUVerFrame::frameFromBuffer( Byte* Buff, Int iEndianness ) { ratioW = i > 1 ? d->m_pcPelFormat->log2ChromaWidth : 0; ratioH = i > 1 ? d->m_pcPelFormat->log2ChromaHeight : 0; - ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; + ppBuff[i] = + ppBuff[i - 1] + + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; } for( ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) @@ -589,16 +613,19 @@ Void PlaYUVerFrame::frameFromBuffer( Byte* Buff, Int iEndianness ) step = d->m_pcPelFormat->comp[ch].step_minus1; pPel = d->m_pppcInputPel[ch][0]; - pTmpBuff = ppBuff[d->m_pcPelFormat->comp[ch].plane] + ( d->m_pcPelFormat->comp[ch].offset_plus1 - 1 ); + pTmpBuff = + ppBuff[d->m_pcPelFormat->comp[ch].plane] + ( d->m_pcPelFormat->comp[ch].offset_plus1 - 1 ); - for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); + i++ ) { *pPel = 0; for( b = startByte; b != endByte; b += incByte ) { *pPel += *pTmpBuff << ( b * 8 ); pTmpBuff++; - // Check max value and bound it to "maxval" to prevent segfault when calculating histogram + // Check max value and bound it to "maxval" to prevent segfault when + // calculating histogram if( *pPel > maxval ) *pPel = 0; // ----- @@ -636,7 +663,9 @@ Void PlaYUVerFrame::frameToBuffer( Byte* output_buffer, Int iEndianness ) { ratioW = i > 1 ? d->m_pcPelFormat->log2ChromaWidth : 0; ratioH = i > 1 ? d->m_pcPelFormat->log2ChromaHeight : 0; - ppBuff[i] = ppBuff[i - 1] + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; + ppBuff[i] = + ppBuff[i - 1] + + CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ) * bytesPixel; } for( ch = 0; ch < d->m_pcPelFormat->numberChannels; ch++ ) @@ -648,7 +677,8 @@ Void PlaYUVerFrame::frameToBuffer( Byte* output_buffer, Int iEndianness ) pTmpPel = d->m_pppcInputPel[ch][0]; pTmpBuff = ppBuff[d->m_pcPelFormat->comp[ch].plane]; - for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); i++ ) + for( i = 0; i < CHROMASHIFT( d->m_uiHeight, ratioH ) * CHROMASHIFT( d->m_uiWidth, ratioW ); + i++ ) { for( b = startByte; b != endByte; b += incByte ) { @@ -810,7 +840,8 @@ Void PlaYUVerFrame::calcHistogram() } if( ( colorSpace == PlaYUVerPixel::COLOR_RGB || colorSpace == PlaYUVerPixel::COLOR_ARGB ) ) { - PlaYUVerPixel currPixel( colorSpace, *( data[COLOR_R] ), *( data[COLOR_G] ), *( data[COLOR_B] ) ); + PlaYUVerPixel currPixel( colorSpace, *( data[COLOR_R] ), *( data[COLOR_G] ), + *( data[COLOR_B] ) ); luma = currPixel.ConvertPixel( PlaYUVerPixel::COLOR_YUV ).Y(); d->m_puiHistogram[luma + j * d->m_uiHistoSegments]++; } @@ -858,7 +889,8 @@ Int getRealHistoChannel( Int colorSpace, Int channel ) } break; case PlaYUVerPixel::COLOR_ARGB: - if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != COLOR_A && channel != LUMA ) + if( channel != COLOR_R && channel != COLOR_G && channel != COLOR_B && channel != COLOR_A && + channel != LUMA ) { return -1; } @@ -1392,7 +1424,8 @@ float compute_ssim( Pel** refImg, cur_distortion /= (float)win_cnt; - if( cur_distortion >= 1.0 && cur_distortion < 1.01 ) // avoid float accuracy problem at very low QP(e.g.2) + if( cur_distortion >= 1.0 && + cur_distortion < 1.01 ) // avoid float accuracy problem at very low QP(e.g.2) cur_distortion = 1.0; return cur_distortion; @@ -1403,13 +1436,13 @@ Double PlaYUVerFrame::getSSIM( PlaYUVerFrame* Org, Int component ) Double dSSIM = 1; if( component == LUMA ) { - dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], d->m_uiWidth, d->m_uiHeight, - 8, 8, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], + d->m_uiWidth, d->m_uiHeight, 8, 8, 255, 8 ); } else { - dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], getChromaWidth(), - getChromaHeight(), 4, 4, 255, 8 ); + dSSIM = compute_ssim( d->m_pppcInputPel[component], Org->getPelBufferYUV()[component], + getChromaWidth(), getChromaHeight(), 4, 4, 255, 8 ); } return dSSIM; } diff --git a/lib/PlaYUVerFramePixelFormats.cpp b/lib/PlaYUVerFramePixelFormats.cpp index f0d2d6d..6e652f6 100644 --- a/lib/PlaYUVerFramePixelFormats.cpp +++ b/lib/PlaYUVerFramePixelFormats.cpp @@ -22,13 +22,13 @@ * \brief Handling the pixel formats definition */ -#include "config.h" #include "PlaYUVerFramePixelFormats.h" +#include "config.h" #ifdef USE_SSE #include -#include #include +#include #endif #include "LibMemory.h" @@ -199,112 +199,112 @@ Void fillARGB32bufferYUV420p( Pel*** in, UChar* out, UInt width, UInt height, UI } #endif -const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_PEL_FORMATS] = { - { - "YUV420p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 1, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), - { - {0, 0, 1}, /* Y */ - {1, 0, 1}, /* U */ - {2, 0, 1}, /* V */ - }, - }, - { - "YUV422p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), - { - {0, 0, 1}, /* Y */ - {1, 0, 1}, /* U */ - {2, 0, 1}, /* V */ - }, - }, - { - "YUV444p", - PlaYUVerPixel::COLOR_YUV, - 3, - 3, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), - { - {0, 0, 1}, /* Y */ - {1, 0, 1}, /* U */ - {2, 0, 1}, /* V */ - }, - }, - { - "YUYV422", - PlaYUVerPixel::COLOR_YUV, - 3, - 1, - 1, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), - { - {0, 1, 1}, /* Y */ - {0, 3, 2}, /* U */ - {0, 3, 4}, /* V */ - }, - }, - { - "GRAY", - PlaYUVerPixel::COLOR_GRAY, - 1, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), - {{0, 0, 1}}, /* Y */ - }, - { - "RGBp", - PlaYUVerPixel::COLOR_RGB, - 3, - 3, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), - { - {0, 0, 1}, /* R */ - {1, 0, 1}, /* G */ - {2, 0, 1}, /* B */ - }, - }, - { - "RGB", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), - { - {0, 2, 1}, /* R */ - {0, 2, 2}, /* G */ - {0, 2, 3}, /* B */ - }, - }, - { - "BGR", - PlaYUVerPixel::COLOR_RGB, - 3, - 1, - 0, - 0, - ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), - { - {0, 2, 3}, /* B */ - {0, 2, 2}, /* R */ - {0, 2, 1}, /* G */ - }, - }}; +const PlaYUVerPixFmtDescriptor g_PlaYUVerPixFmtDescriptorsList[PlaYUVerFrame::NUMBER_PEL_FORMATS] = + {{ + "YUV420p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 1, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV420P ), + { + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ + }, + }, + { + "YUV422p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV422P ), + { + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ + }, + }, + { + "YUV444p", + PlaYUVerPixel::COLOR_YUV, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUV444P ), + { + {0, 0, 1}, /* Y */ + {1, 0, 1}, /* U */ + {2, 0, 1}, /* V */ + }, + }, + { + "YUYV422", + PlaYUVerPixel::COLOR_YUV, + 3, + 1, + 1, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_YUYV422 ), + { + {0, 1, 1}, /* Y */ + {0, 3, 2}, /* U */ + {0, 3, 4}, /* V */ + }, + }, + { + "GRAY", + PlaYUVerPixel::COLOR_GRAY, + 1, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_GRAY8 ), + {{0, 0, 1}}, /* Y */ + }, + { + "RGBp", + PlaYUVerPixel::COLOR_RGB, + 3, + 3, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + { + {0, 0, 1}, /* R */ + {1, 0, 1}, /* G */ + {2, 0, 1}, /* B */ + }, + }, + { + "RGB", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_RGB24 ), + { + {0, 2, 1}, /* R */ + {0, 2, 2}, /* G */ + {0, 2, 3}, /* B */ + }, + }, + { + "BGR", + PlaYUVerPixel::COLOR_RGB, + 3, + 1, + 0, + 0, + ADD_FFMPEG_PEL_FMT( AV_PIX_FMT_BGR24 ), + { + {0, 2, 3}, /* B */ + {0, 2, 2}, /* R */ + {0, 2, 1}, /* G */ + }, + }}; diff --git a/lib/PlaYUVerFramePixelFormats.h b/lib/PlaYUVerFramePixelFormats.h index b8c6471..1a57ffa 100644 --- a/lib/PlaYUVerFramePixelFormats.h +++ b/lib/PlaYUVerFramePixelFormats.h @@ -26,14 +26,15 @@ #define __PLAYUVERFRAMEPIXELFORMATS_H__ #include "PlaYUVerDefs.h" -#include "PlaYUVerPixel.h" #include "PlaYUVerFrame.h" +#include "PlaYUVerPixel.h" #define CHROMA_RESAMPLING( X ) ( ( ( X + 1 ) >> 1 ) << 1 ) #define CHROMARATIO( SIZE, RATIO ) ( RATIO > 1 ? ( ( SIZE + 1 ) / RATIO ) : SIZE ) -#define PEL_RGB( r, g, b ) ( 0xffu << 24 ) | ( ( r & 0xff ) << 16 ) | ( ( g & 0xff ) << 8 ) | ( b & 0xff ) +#define PEL_RGB( r, g, b ) \ + ( 0xffu << 24 ) | ( ( r & 0xff ) << 16 ) | ( ( g & 0xff ) << 8 ) | ( b & 0xff ) typedef struct PlaYUVerComponentDescriptor { diff --git a/lib/PlaYUVerOptions.cpp b/lib/PlaYUVerOptions.cpp index f3d47f6..d5158dc 100644 --- a/lib/PlaYUVerOptions.cpp +++ b/lib/PlaYUVerOptions.cpp @@ -36,11 +36,11 @@ * \brief Options handler */ -#include "config.h" #include "PlaYUVerOptions.h" +#include "config.h" -#include #include +#include #include "lib/PlaYUVerModuleIf.h" #include "modules/PlaYUVerModuleFactory.h" @@ -60,7 +60,10 @@ struct ParseFailure : public std::exception class BoolOption : public OptionBase { public: - BoolOption( const String& name, const String& desc ) : OptionBase( name, desc ) { is_binary = true; } + BoolOption( const String& name, const String& desc ) : OptionBase( name, desc ) + { + is_binary = true; + } void parse( const String& arg ) { arg_count++; } }; @@ -101,7 +104,7 @@ inline void StandardOption::parse( const String& arg ) } template <> -inline void StandardOption >::parse( const String& arg ) +inline void StandardOption>::parse( const String& arg ) { UInt aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -119,7 +122,7 @@ inline void StandardOption >::parse( const String& arg ) } template <> -inline void StandardOption >::parse( const String& arg ) +inline void StandardOption>::parse( const String& arg ) { Int aux_opt_storage; std::istringstream arg_ss( arg, std::istringstream::in ); @@ -146,7 +149,7 @@ inline void StandardOption::parse( const String& arg ) /* string vector parsing is specialized */ template <> -inline void StandardOption >::parse( const String& arg ) +inline void StandardOption>::parse( const String& arg ) { opt_storage.push_back( arg ); arg_count++; @@ -201,11 +204,21 @@ PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, T& storage, co return *this; } -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Bool& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, UInt& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, Int64& storage, const String& desc ); -template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, String& storage, const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + Bool& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + UInt& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + Int& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + Int64& storage, + const String& desc ); +template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, + String& storage, + const String& desc ); template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, std::vector& storage, const String& desc ); @@ -223,7 +236,8 @@ template PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, * FunctionOption::Func is called. It is upto this function to correctly * handle evaluating the option's value. */ -// PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, FunctionOption::Func *func, const String& desc ) +// PlaYUVerOptions& PlaYUVerOptions::operator()( const String& name, +// FunctionOption::Func *func, const String& desc ) // { // addOption( new FunctionOption( name, parent, func, desc ) ); // return *this; @@ -335,7 +349,10 @@ static void setOptions( PlaYUVerOptions::OptionsList& opt_list, const string& va } } -Bool PlaYUVerOptions::storePair( Bool allow_long, Bool allow_short, const string& name, const string& value ) +Bool PlaYUVerOptions::storePair( Bool allow_long, + Bool allow_short, + const string& name, + const string& value ) { bool found = false; PlaYUVerOptions::OptionMap::iterator opt_it; @@ -646,7 +663,8 @@ Void PlaYUVerOptions::doHelp( ostream& out, UInt columns ) line << opt_desc.substr( cur_pos ); break; } - /* find a suitable point to split text (avoid spliting in middle of word) */ + /* find a suitable point to split text (avoid spliting in middle of word) + */ size_t split_pos = opt_desc.find_last_of( ' ', cur_pos + desc_width ); if( split_pos != string::npos ) { diff --git a/lib/PlaYUVerOptions.h b/lib/PlaYUVerOptions.h index ac7db10..a508e5a 100644 --- a/lib/PlaYUVerOptions.h +++ b/lib/PlaYUVerOptions.h @@ -51,7 +51,10 @@ class OptionBase { public: - OptionBase( const String& name, const String& desc ) : arg_count( 0 ), opt_string( name ), opt_desc( desc ) {} + OptionBase( const String& name, const String& desc ) + : arg_count( 0 ), opt_string( name ), opt_desc( desc ) + { + } virtual ~OptionBase() {} /* parse argument arg, to obtain a value for the option */ virtual void parse( const String& arg ) = 0; @@ -125,7 +128,8 @@ class PlaYUVerOptions * handle evaluating the option's value. */ // PlaYUVerOptions& - // operator()( const String& name, OptionFunc::Func *func, const String& desc ); + // operator()( const String& name, OptionFunc::Func *func, const String& + // desc ); Bool checkListingOpts(); Void listModules(); diff --git a/lib/PlaYUVerPixel.cpp b/lib/PlaYUVerPixel.cpp index aca4381..1599e6c 100644 --- a/lib/PlaYUVerPixel.cpp +++ b/lib/PlaYUVerPixel.cpp @@ -22,10 +22,10 @@ * \brief Pixel handling */ -#include -#include -#include "PlaYUVerFrame.h" #include "PlaYUVerPixel.h" +#include "PlaYUVerFrame.h" +#include +#include PlaYUVerPixel::PlaYUVerPixel() : m_iColorSpace( COLOR_INVALID ) { diff --git a/lib/PlaYUVerPixel.h b/lib/PlaYUVerPixel.h index 5e2200d..21fb00c 100644 --- a/lib/PlaYUVerPixel.h +++ b/lib/PlaYUVerPixel.h @@ -25,13 +25,18 @@ #ifndef __PLAYUVERPIXEL_H__ #define __PLAYUVERPIXEL_H__ -#include -#include -#include -#include #include "PlaYUVerDefs.h" +#include +#include +#include +#include -static inline Void YuvToRgb( const Int& iY, const Int& iU, const Int& iV, Int& iR, Int& iG, Int& iB ) +static inline Void YuvToRgb( const Int& iY, + const Int& iU, + const Int& iV, + Int& iR, + Int& iG, + Int& iB ) { iR = iY + ( ( 1436 * ( iV - 128 ) ) >> 10 ); iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ); @@ -41,7 +46,12 @@ static inline Void YuvToRgb( const Int& iY, const Int& iU, const Int& iV, Int& i iB = iB < 0 ? 0 : iB > 255 ? 255 : iB; } -static inline Void rgbToYuv( const Int& iR, const Int& iG, const Int& iB, Int& iY, Int& iU, Int& iV ) +static inline Void rgbToYuv( const Int& iR, + const Int& iG, + const Int& iB, + Int& iY, + Int& iU, + Int& iV ) { iY = ( 299 * iR + 587 * iG + 114 * iB + 500 ) / 1000; iU = ( 1000 * ( iB - iY ) + 226816 ) / 1772; diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index d233d1d..0e2109b 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -23,8 +23,8 @@ */ // Self -#include "config.h" #include "PlaYUVerStream.h" +#include "config.h" // System #include @@ -33,8 +33,8 @@ #include "LibMemory.h" #include "PlaYUVerFrame.h" #include "PlaYUVerStreamHandlerIf.h" -#include "StreamHandlerRaw.h" #include "StreamHandlerPortableMap.h" +#include "StreamHandlerRaw.h" #ifdef USE_FFMPEG #include "StreamHandlerLibav.h" #endif @@ -120,7 +120,8 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo { return supportedFmts[i].formatFct; } - // else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) + // else if( strFilename.find( supportedFmts[i].formatExt ) != + // String::npos ) // { // return supportedFmts[i].formatFct; // } @@ -182,7 +183,8 @@ Bool PlaYUVerStream::open( String filename, } for( UInt i = 0; i < PlaYUVerFrame::supportedPixelFormatListNames().size(); i++ ) { - if( lowercase( PlaYUVerFrame::supportedPixelFormatListNames()[i] ) == lowercase( input_format_name ) ) + if( lowercase( PlaYUVerFrame::supportedPixelFormatListNames()[i] ) == + lowercase( input_format_name ) ) { input_format = i; break; @@ -237,7 +239,8 @@ Bool PlaYUVerStream::open( String filename, return m_bInit; } - if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 ) + if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || + m_pcHandler->m_iPixelFormat < 0 ) { close(); throw PlaYUVerFailure( "PlaYUVerStream", "Incorrect configuration" ); @@ -251,8 +254,9 @@ Bool PlaYUVerStream::open( String filename, { try { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, - m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = + new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, + m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); } catch( PlaYUVerFailure& e ) { @@ -304,8 +308,9 @@ Bool PlaYUVerStream::reload() m_pcHandler->setBytesPerFrame( m_pcCurrFrame->getBytesPerFrame() ); m_uiTotalFrameNum = m_pcHandler->calculateFrameNumber(); - if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || m_pcHandler->m_iPixelFormat < 0 || - m_pcHandler->m_uiBitsPerPixel == 0 || m_uiTotalFrameNum < 1 ) + if( m_pcHandler->m_uiWidth <= 0 || m_pcHandler->m_uiHeight <= 0 || + m_pcHandler->m_iPixelFormat < 0 || m_pcHandler->m_uiBitsPerPixel == 0 || + m_uiTotalFrameNum < 1 ) { return false; } @@ -421,8 +426,9 @@ Void PlaYUVerStream::loadAll() getMem1D( &m_ppcFrameBuffer, m_uiFrameBufferSize ); for( UInt i = 0; i < m_uiFrameBufferSize; i++ ) { - m_ppcFrameBuffer[i] = new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, - m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); + m_ppcFrameBuffer[i] = + new PlaYUVerFrame( m_pcHandler->m_uiWidth, m_pcHandler->m_uiHeight, + m_pcHandler->m_iPixelFormat, m_pcHandler->m_uiBitsPerPixel ); if( !m_ppcFrameBuffer[i] ) { close(); @@ -518,8 +524,9 @@ Bool PlaYUVerStream::saveFrame( const String& filename ) Bool PlaYUVerStream::saveFrame( const String& filename, PlaYUVerFrame* saveFrame ) { PlaYUVerStream auxSaveStream; - if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), saveFrame->getPelFormat(), - saveFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ) ) + if( !auxSaveStream.open( filename, saveFrame->getWidth(), saveFrame->getHeight(), + saveFrame->getPelFormat(), saveFrame->getBitsPel(), + PLAYUVER_LITTLE_ENDIAN, 1, false ) ) { return false; } diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index aa373b3..b4929cd 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -22,25 +22,32 @@ * \brief Interface with libav libs */ -#include #include "StreamHandlerLibav.h" +#include "LibMemory.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" -#include "LibMemory.h" +#include std::vector StreamHandlerLibav::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Portable Network Graphics", "png" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", "jpg" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Joint Photographic Experts Group", + "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows Bitmap", "bmp" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Tagged Image File Format", "tiff" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video + // interleaved", "avi" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows + // media video", "wmv" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", + // "mp4" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska + // Multimedia Container", "mkv" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 + // streams", "h264" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC + // streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -113,10 +120,12 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) // av_dict_set( &format_opts, "video_size", aux_string, 0 ); // } - // Int ffmpeg_pel_format = g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; + // Int ffmpeg_pel_format = + // g_PlaYUVerPixFmtDescriptorsList[pixel_format].ffmpegPelFormat; // if( ffmpeg_pel_format >= 0 ) // { - // av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( AVPixelFormat( ffmpeg_pel_format ) ), 0 ); + // av_dict_set( &format_opts, "pixel_format", av_get_pix_fmt_name( + // AVPixelFormat( ffmpeg_pel_format ) ), 0 ); // } /* open input file, and allocate format context */ @@ -139,7 +148,8 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) m_cCodecCtx = m_cStream->codec; // /* allocate image where the decoded image will be put */ - // ret = av_image_alloc( video_dst_data, video_dst_linesize, m_cCodecCtx->width, m_cCodecCtx->height, + // ret = av_image_alloc( video_dst_data, video_dst_linesize, + // m_cCodecCtx->width, m_cCodecCtx->height, // m_cCodecCtx->pix_fmt, 1 ); // if( ret < 0 ) // { @@ -149,7 +159,8 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) // } // video_dst_bufsize = ret; - m_uiFrameBufferSize = av_image_get_buffer_size( m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); + m_uiFrameBufferSize = av_image_get_buffer_size( m_cCodecCtx->pix_fmt, m_cCodecCtx->width, + m_cCodecCtx->height, 1 ); getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); } @@ -224,7 +235,8 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) av_dump_format( m_cFmtCtx, 0, filename, 0 ); if( !m_cStream ) { - // qDebug( ) << " Could not find audio or video stream in the input, aborting !!!" << endl; + // qDebug( ) << " Could not find audio or video stream in the input, + // aborting !!!" << endl; closeHandler(); return false; } @@ -350,11 +362,13 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) if( bGotFrame ) { - // av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, + // av_image_copy_to_buffer( m_pchFrameBuffer, m_uiFrameBufferSize, + // m_cFrame->data, m_cFrame->linesize, // m_cCodecCtx->pix_fmt, m_cCodecCtx->width, // m_cCodecCtx->height, 1 ); - av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, - m_cCodecCtx->pix_fmt, m_cCodecCtx->width, m_cCodecCtx->height, 1 ); + av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, + m_cFrame->linesize, m_cCodecCtx->pix_fmt, m_cCodecCtx->width, + m_cCodecCtx->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); diff --git a/lib/StreamHandlerLibav.h b/lib/StreamHandlerLibav.h index 6e1934d..17b7df4 100644 --- a/lib/StreamHandlerLibav.h +++ b/lib/StreamHandlerLibav.h @@ -26,8 +26,8 @@ #define __LIBAVCONTEXTHANDLE_H__ #include -#include #include +#include #ifndef __PRI64_PREFIX #define __PRI64_PREFIX "l" @@ -38,10 +38,10 @@ #endif extern "C" { +#include #include #include #include -#include } #include "PlaYUVerDefs.h" diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index 011a6c1..e211e5a 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -30,9 +30,9 @@ #include // Own +#include "LibMemory.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" -#include "LibMemory.h" using cv::Mat; using cv::VideoCapture; @@ -40,7 +40,8 @@ using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); + // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", + // "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -49,7 +50,8 @@ std::vector StreamHandlerOpenCV::supportedWriteFormats( INI_REGIST_PLAYUVER_SUPPORTED_FMT; REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable PixMap ", "ppm" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Portable Network Graphics", "png" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", "jpg" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Joint Photographic Experts Group", + "jpg" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Windows Bitmap", "bmp" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -78,7 +80,8 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) } else { - m_strCodecName = m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); + m_strCodecName = m_strFormatName = + uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); Mat cvMat = cv::imread( m_cFilename ); m_uiWidth = cvMat.cols; m_uiHeight = cvMat.rows; diff --git a/lib/StreamHandlerPortableMap.cpp b/lib/StreamHandlerPortableMap.cpp index c9c8564..03dacc8 100644 --- a/lib/StreamHandlerPortableMap.cpp +++ b/lib/StreamHandlerPortableMap.cpp @@ -22,12 +22,12 @@ * \brief Handling portable pixmap formats */ -#include -#include #include "StreamHandlerPortableMap.h" +#include "LibMemory.h" #include "PlaYUVerFrame.h" #include "PlaYUVerFramePixelFormats.h" -#include "LibMemory.h" +#include +#include Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) { @@ -62,7 +62,8 @@ Bool StreamHandlerPortableMap::openHandler( String strFilename, Bool bInput ) ; sscanf( line, "%d", &m_iMaxValue ); m_uiBitsPerPixel = log( m_iMaxValue + 1 ) / log( 2 ); - m_iPixelFormat = m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; + m_iPixelFormat = + m_iMagicNumber == 2 || m_iMagicNumber == 5 ? PlaYUVerFrame::GRAY : PlaYUVerFrame::RGB24; } } else diff --git a/modules/AbsoluteFrameDifference.cpp b/modules/AbsoluteFrameDifference.cpp index 6d676d4..30d642d 100644 --- a/modules/AbsoluteFrameDifference.cpp +++ b/modules/AbsoluteFrameDifference.cpp @@ -27,17 +27,22 @@ AbsoluteFrameDifference::AbsoluteFrameDifference() { /* Module Definition */ - m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). - // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). + // See this example for details on the functions prototype + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to + // the whole sequence. m_pchModuleCategory = "Measurements"; // Category (sub-menu) m_pchModuleName = "AbsoluteFrameDifference"; // Name m_pchModuleTooltip = "Measure the absolute difference " // Description "between two images (Y plane), e. g., abs( Y1 - Y2 )"; - m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; // Number of Frames required + // (ONE_FRAME, TWO_FRAMES, + // THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements + // (check + // PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. m_pcFrameDifference = NULL; } @@ -51,8 +56,8 @@ Bool AbsoluteFrameDifference::create( std::vector apcFrameList ) PlaYUVerFrame::MATCH_BITS ) ) return false; - m_pcFrameDifference = - new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), + apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); return true; } diff --git a/modules/DisparityStereoBM.cpp b/modules/DisparityStereoBM.cpp index 378382d..e12d49a 100644 --- a/modules/DisparityStereoBM.cpp +++ b/modules/DisparityStereoBM.cpp @@ -19,7 +19,8 @@ /** * \file DisparityStereoBM.cpp - * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) + * \brief Measure the disparity between two images using the Stereo Var + * method (OpenCV) */ #include "DisparityStereoBM.h" @@ -31,9 +32,12 @@ DisparityStereoBM::DisparityStereoBM() m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "Stereo"; m_pchModuleName = "Disparity-BM"; - m_pchModuleTooltip = "Measure the disparity between two images using the Stereo BM method (OpenCV)"; + m_pchModuleTooltip = + "Measure the disparity between two images using the " + "Stereo BM method (OpenCV)"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + m_uiModuleRequirements = + MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_cModuleOptions.addOptions() /**/ ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [9]" ); @@ -45,8 +49,8 @@ DisparityStereoBM::DisparityStereoBM() Bool DisparityStereoBM::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = - new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY ); if( ( m_uiBlockSize % 2 ) == 0 ) { m_uiBlockSize++; diff --git a/modules/DisparityStereoBM.h b/modules/DisparityStereoBM.h index d222b1a..d92b275 100644 --- a/modules/DisparityStereoBM.h +++ b/modules/DisparityStereoBM.h @@ -19,7 +19,8 @@ /** * \file DisparityStereoBM.h - * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) + * \brief Measure the disparity between two images using the Stereo Var + * method (OpenCV) */ #ifndef __DISPARITYSTEREOBM_H__ diff --git a/modules/DisparityStereoSGBM.cpp b/modules/DisparityStereoSGBM.cpp index b4e0dca..6e98757 100644 --- a/modules/DisparityStereoSGBM.cpp +++ b/modules/DisparityStereoSGBM.cpp @@ -19,7 +19,8 @@ /** * \file DisparityStereoSGBM.cpp - * \brief Measure the disparity between two images using the SGBM method (OpenCV) + * \brief Measure the disparity between two images using the SGBM method + * (OpenCV) */ #include "DisparityStereoSGBM.h" @@ -31,13 +32,16 @@ DisparityStereoSGBM::DisparityStereoSGBM() m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "Stereo"; m_pchModuleName = "Disparity-SGBM"; - m_pchModuleTooltip = "Measure the disparity between two images using the Stereo SGBM method (OpenCV)"; + m_pchModuleTooltip = + "Measure the disparity between two images using the " + "Stereo SGBM method (OpenCV)"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + m_uiModuleRequirements = + MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_cModuleOptions.addOptions() /**/ - ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [3]" )( "HHAlgorithm", m_bUseHH, - "Use HH algorithm [false]" ); + ( "block_size", m_uiBlockSize, "Block Size (positive odd number) [3]" )( + "HHAlgorithm", m_bUseHH, "Use HH algorithm [false]" ); m_pcDisparityFrame = NULL; m_uiBlockSize = 3; @@ -47,8 +51,8 @@ DisparityStereoSGBM::DisparityStereoSGBM() Bool DisparityStereoSGBM::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = - new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY ); if( ( m_uiBlockSize % 2 ) == 0 ) { m_uiBlockSize++; @@ -67,7 +71,8 @@ Bool DisparityStereoSGBM::create( std::vector apcFrameList ) m_cStereoMatch->setSpeckleWindowSize( 100 ); m_cStereoMatch->setSpeckleRange( 32 ); m_cStereoMatch->setDisp12MaxDiff( 1 ); - // m_cStereoMatch->setMode( alg == STEREO_HH ? StereoSGBM::MODE_HH : StereoSGBM::MODE_SGBM ); + // m_cStereoMatch->setMode( alg == STEREO_HH ? StereoSGBM::MODE_HH : + // StereoSGBM::MODE_SGBM ); m_cStereoMatch->setMode( m_bUseHH ? cv::StereoSGBM::MODE_HH : cv::StereoSGBM::MODE_SGBM ); #else m_cStereoMatch.preFilterCap = 63; diff --git a/modules/DisparityStereoSGBM.h b/modules/DisparityStereoSGBM.h index a86b7aa..22f9b4b 100644 --- a/modules/DisparityStereoSGBM.h +++ b/modules/DisparityStereoSGBM.h @@ -19,18 +19,26 @@ /** * \file DisparityStereoSGBM.h - * \brief Measure the disparity between two images using the SGBM method (OpenCV) + * \brief Measure the disparity between two images using the SGBM method + * (OpenCV) * The class implements the modified H. Hirschmuller algorithm * that differs from the original one as follows: - * - By default, the algorithm is single-pass, which means that you consider only 5 directions - * instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the + * - By default, the algorithm is single-pass, which means that you consider + * only 5 directions + * instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the + * full variant of the * algorithm but beware that it may consume a lot of memory. - * - The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the + * - The algorithm matches blocks, not individual pixels. Though, setting + * blockSize=1 reduces the * blocks to single pixels. - * - Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi - * sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. - * - Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for - * example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness + * - Mutual information cost function is not implemented. Instead, a simpler + * Birchfield-Tomasi + * sub-pixel metric from @cite BT98 is used. Though, the color images are + * supported as well. + * - Some pre- and post- processing steps from K. Konolige algorithm StereoBM + * are included, for + * example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering + * (uniqueness * check, quadratic interpolation and speckle filtering). */ diff --git a/modules/DisparityStereoVar.cpp b/modules/DisparityStereoVar.cpp index ff1ea45..fc018f2 100644 --- a/modules/DisparityStereoVar.cpp +++ b/modules/DisparityStereoVar.cpp @@ -19,7 +19,8 @@ /** * \file DisparityStereoVar.cpp - * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) + * \brief Measure the disparity between two images using the Stereo Var + * method (OpenCV) */ #include "DisparityStereoVar.h" @@ -31,7 +32,9 @@ DisparityStereoVar::DisparityStereoVar() m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "Disparity"; m_pchModuleName = "StereoVar"; - m_pchModuleTooltip = "Measure the disparity between two images using the Stereo Var method (OpenCV)"; + m_pchModuleTooltip = + "Measure the disparity between two images using the " + "Stereo Var method (OpenCV)"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW; @@ -47,15 +50,15 @@ DisparityStereoVar::DisparityStereoVar() m_cStereoVar.lambda = 0.03f; m_cStereoVar.penalization = m_cStereoVar.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS m_cStereoVar.cycle = m_cStereoVar.CYCLE_V; // ignored with USE_AUTO_PARAMS - m_cStereoVar.flags = m_cStereoVar.USE_SMART_ID | m_cStereoVar.USE_AUTO_PARAMS | m_cStereoVar.USE_INITIAL_DISPARITY | - m_cStereoVar.USE_MEDIAN_FILTERING; + m_cStereoVar.flags = m_cStereoVar.USE_SMART_ID | m_cStereoVar.USE_AUTO_PARAMS | + m_cStereoVar.USE_INITIAL_DISPARITY | m_cStereoVar.USE_MEDIAN_FILTERING; } Bool DisparityStereoVar::create( std::vector apcFrameList ) { _BASIC_MODULE_API_2_CHECK_ - m_pcDisparityFrame = - new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcDisparityFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY ); m_cStereoVar.minDisp = -( ( ( apcFrameList[0]->getWidth() / 8 ) + 15 ) & -16 ); return true; } diff --git a/modules/DisparityStereoVar.h b/modules/DisparityStereoVar.h index 7e80bba..e34ba15 100644 --- a/modules/DisparityStereoVar.h +++ b/modules/DisparityStereoVar.h @@ -19,7 +19,8 @@ /** * \file DisparityStereoVar.h - * \brief Measure the disparity between two images using the Stereo Var method (OpenCV) + * \brief Measure the disparity between two images using the Stereo Var + * method (OpenCV) */ #ifndef __DISPARITYSTEREOVAR_H__ diff --git a/modules/EightBitsSampling.cpp b/modules/EightBitsSampling.cpp index 75cfa02..c59f995 100644 --- a/modules/EightBitsSampling.cpp +++ b/modules/EightBitsSampling.cpp @@ -43,8 +43,9 @@ Bool EightBitsSampling::create( std::vector apcFrameList ) if( apcFrameList[0]->getBitsPel() > 8 ) { m_pcSubSampledFrame = NULL; - m_pcSubSampledFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), - apcFrameList[0]->getPelFormat(), 8 ); + m_pcSubSampledFrame = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + apcFrameList[0]->getPelFormat(), 8 ); return true; } return false; diff --git a/modules/FilterComponent.cpp b/modules/FilterComponent.cpp index c4480d5..5048195 100644 --- a/modules/FilterComponent.cpp +++ b/modules/FilterComponent.cpp @@ -58,19 +58,25 @@ FilterComponentLuma::FilterComponentLuma() { /* Module Definition */ m_iModuleAPI = MODULE_API_2; - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to + // the whole sequence. // Currently only support for frame m_pchModuleCategory = "FilterComponent"; // Category (sub-menu) m_pchModuleName = "Luma"; // Name m_pchModuleTooltip = "Filter Y matrix of YUV frame"; // Description - m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required + // (ONE_FRAME, TWO_FRAMES, + // THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements + // (check + // PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. } Bool FilterComponentLuma::create( std::vector apcFrameList ) { - return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), apcFrameList[0]->getBitsPel() ); + return createFilter( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + apcFrameList[0]->getBitsPel() ); } PlaYUVerFrame* FilterComponentLuma::process( std::vector apcFrameList ) diff --git a/modules/FrameCrop.cpp b/modules/FrameCrop.cpp index a67b35d..3d64d4e 100644 --- a/modules/FrameCrop.cpp +++ b/modules/FrameCrop.cpp @@ -34,10 +34,12 @@ FrameCrop::FrameCrop() m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; m_uiModuleRequirements = MODULE_REQUIRES_OPTIONS; - m_cModuleOptions.addOptions() /**/ - ( "xPosition", m_uiXPosition, "X cordinate of the left-top corner of the crop region [0]" ) /**/ - ( "yPosition", m_uiYPosition, "Y cordinate of the left-top corner of the crop region [0]" ) /**/ - ( "width", m_iXSize, "Width of the crop region [-1]" ) /**/ + m_cModuleOptions.addOptions() /**/ + ( "xPosition", m_uiXPosition, + "X cordinate of the left-top corner of the crop region [0]" ) /**/ + ( "yPosition", m_uiYPosition, + "Y cordinate of the left-top corner of the crop region [0]" ) /**/ + ( "width", m_iXSize, "Width of the crop region [-1]" ) /**/ ( "height", m_iYSize, "Height of the crop region [-1]" ); m_pcCropedFrame = NULL; @@ -58,7 +60,8 @@ Void FrameCrop::create( PlaYUVerFrame* frame ) { m_iYSize = frame->getHeight() - m_uiYPosition; } - m_pcCropedFrame = new PlaYUVerFrame( m_iXSize, m_iYSize, frame->getPelFormat(), frame->getBitsPel() ); + m_pcCropedFrame = + new PlaYUVerFrame( m_iXSize, m_iYSize, frame->getPelFormat(), frame->getBitsPel() ); } PlaYUVerFrame* FrameCrop::process( PlaYUVerFrame* frame ) diff --git a/modules/FrameDifference.cpp b/modules/FrameDifference.cpp index eabcd08..c89546a 100644 --- a/modules/FrameDifference.cpp +++ b/modules/FrameDifference.cpp @@ -31,7 +31,9 @@ FrameDifference::FrameDifference() m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "Measurements"; m_pchModuleName = "FrameDifference"; - m_pchModuleTooltip = "Measure the difference between two images (Y plane), Y1 - Y2, with max absolute diff of 128"; + m_pchModuleTooltip = + "Measure the difference between two images (Y plane), " + "Y1 - Y2, with max absolute diff of 128"; m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; @@ -50,8 +52,8 @@ Bool FrameDifference::create( std::vector apcFrameList ) UInt uiMaxBitsPixel = 0; for( UInt i = 0; i < apcFrameList.size(); i++ ) { - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], - PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION ) ) + if( !apcFrameList[i]->haveSameFmt( + apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_RESOLUTION ) ) return false; if( apcFrameList[i]->getBitsPel() > uiMaxBitsPixel ) { @@ -67,8 +69,9 @@ Bool FrameDifference::create( std::vector apcFrameList ) m_iDiffBitShift = ( uiMaxBitsPixel + 1 ) - m_uiBitsPixel; m_iMaxDiffValue = ( 1 << ( m_uiBitsPixel - 1 ) ); - m_pcFrameDifference = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), - PlaYUVerFrame::GRAY, m_uiBitsPixel ); + m_pcFrameDifference = + new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY, m_uiBitsPixel ); return true; } diff --git a/modules/FrameMask.cpp b/modules/FrameMask.cpp index 144cefd..7b60963 100644 --- a/modules/FrameMask.cpp +++ b/modules/FrameMask.cpp @@ -49,9 +49,9 @@ Bool FrameMask::create( std::vector apcFrameList ) for( UInt i = 1; i < apcFrameList.size(); i++ ) { - if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE_IGNORE_GRAY | - PlaYUVerFrame::MATCH_RESOLUTION | - PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( + apcFrameList[0], PlaYUVerFrame::MATCH_COLOR_SPACE_IGNORE_GRAY | + PlaYUVerFrame::MATCH_RESOLUTION | PlaYUVerFrame::MATCH_BITS ) ) { return false; } @@ -79,8 +79,8 @@ Bool FrameMask::create( std::vector apcFrameList ) break; } - m_pcFrameProcessed = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), iPelFmt, - apcFrameList[0]->getBitsPel() ); + m_pcFrameProcessed = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + iPelFmt, apcFrameList[0]->getBitsPel() ); return true; } diff --git a/modules/FrameShift.cpp b/modules/FrameShift.cpp index 2fcd123..d7bce39 100644 --- a/modules/FrameShift.cpp +++ b/modules/FrameShift.cpp @@ -58,11 +58,13 @@ PlaYUVerFrame* FrameShift::process( std::vector apcFrameList ) UInt xStartOut = m_iShiftHor >= 0 ? m_iShiftHor : 0; UInt xStartIn = m_iShiftHor >= 0 ? 0 : -m_iShiftHor; - UInt xEndOut = m_iShiftHor >= 0 ? m_pcProcessedFrame->getWidth() : m_pcProcessedFrame->getWidth() + m_iShiftHor; + UInt xEndOut = m_iShiftHor >= 0 ? m_pcProcessedFrame->getWidth() + : m_pcProcessedFrame->getWidth() + m_iShiftHor; UInt yStartOut = m_iShiftVer >= 0 ? m_iShiftVer : 0; UInt yStartIn = m_iShiftVer >= 0 ? 0 : -m_iShiftVer; - UInt yEndOut = m_iShiftVer >= 0 ? m_pcProcessedFrame->getHeight() : m_pcProcessedFrame->getHeight() + m_iShiftVer; + UInt yEndOut = m_iShiftVer >= 0 ? m_pcProcessedFrame->getHeight() + : m_pcProcessedFrame->getHeight() + m_iShiftVer; m_pcProcessedFrame->clear(); diff --git a/modules/InterFrameVariance.cpp b/modules/InterFrameVariance.cpp index fb492ba..b3e839b 100644 --- a/modules/InterFrameVariance.cpp +++ b/modules/InterFrameVariance.cpp @@ -30,13 +30,16 @@ InterFrameVariance::InterFrameVariance() /* Module Definition */ m_iModuleAPI = MODULE_API_2; // Use API version 2 (recommended). // See this example for details on the functions prototype - m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence. + m_iModuleType = FRAME_PROCESSING_MODULE; // Apply module to the frames or to + // the whole sequence. m_pchModuleCategory = "Measurements"; // Category (sub-menu) m_pchModuleName = "InterFrameVariance"; // Name m_pchModuleTooltip = "Measure the variance across several frames"; - m_uiNumberOfFrames = - MODULE_REQUIRES_SEVERAL_FRAMES; // Number of Frames required (This module allows a variable number of inputs) - m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check PlaYUVerModulesIf.h). + m_uiNumberOfFrames = MODULE_REQUIRES_SEVERAL_FRAMES; // Number of Frames required (This module + // allows a variable number of inputs) + m_uiModuleRequirements = MODULE_REQUIRES_NEW_WINDOW; // Module requirements + // (check + // PlaYUVerModulesIf.h). // Several requirements should be "or" between each others. m_pcFrameVariance = NULL; } @@ -53,8 +56,8 @@ Bool InterFrameVariance::create( std::vector apcFrameList ) PlaYUVerFrame::MATCH_BITS ) ) return false; - m_pcFrameVariance = - new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY, 8 ); + m_pcFrameVariance = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY, 8 ); getMem2D( &m_pVariance, apcFrameList[0]->getHeight(), apcFrameList[0]->getWidth() ); return true; diff --git a/modules/LumaAverage.cpp b/modules/LumaAverage.cpp index d21661c..219747f 100644 --- a/modules/LumaAverage.cpp +++ b/modules/LumaAverage.cpp @@ -27,14 +27,19 @@ LumaAverage::LumaAverage() { /* Module Definition */ - m_iModuleType = FRAME_MEASUREMENT_MODULE; // Apply module to the frames or to the whole sequence. + m_iModuleType = FRAME_MEASUREMENT_MODULE; // Apply module to the frames or to + // the whole sequence. // Currently only support for frame m_pchModuleCategory = "Measurements"; // Category (sub-menu) m_pchModuleName = "LumaAverage"; // Name m_pchModuleTooltip = "Measure the average of luma component"; // Description - m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES) - m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements (check PlaYUVerModulesIf.h). - // Several requirements should be "or" between each others. + m_uiNumberOfFrames = MODULE_REQUIRES_ONE_FRAME; // Number of Frames required + // (ONE_FRAME, TWO_FRAMES, + // THREE_FRAMES) + m_uiModuleRequirements = MODULE_REQUIRES_NOTHING; // Module requirements + // (check + // PlaYUVerModulesIf.h). + // Several requirements should be "or" between each others. } Void LumaAverage::create( PlaYUVerFrame* frame ) diff --git a/modules/MeasureOpticalFlowDualTVL1.cpp b/modules/MeasureOpticalFlowDualTVL1.cpp index 562310a..ce65c80 100644 --- a/modules/MeasureOpticalFlowDualTVL1.cpp +++ b/modules/MeasureOpticalFlowDualTVL1.cpp @@ -40,10 +40,12 @@ MeasureOpticalFlowDualTVL1::MeasureOpticalFlowDualTVL1() m_pchModuleName = "MeasureOpticalFlowDualTVL1"; m_pchModuleTooltip = "Measure optical flow"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + m_uiModuleRequirements = + MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_cModuleOptions.addOptions() /**/ - ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + ( "Show reconstruction", m_bShowReconstruction, + "Show reconstructed frame instead of MVs [false]" ); m_bShowReconstruction = false; m_pcOutputFrame = NULL; @@ -61,7 +63,8 @@ Bool MeasureOpticalFlowDualTVL1::create( std::vector apcFrameLis m_iStep = 16; m_cTvl1 = cv::createOptFlow_DualTVL1(); - m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY ); return true; } diff --git a/modules/OpticalFlow.cpp b/modules/OpticalFlow.cpp index f89d068..c6803f8 100644 --- a/modules/OpticalFlow.cpp +++ b/modules/OpticalFlow.cpp @@ -45,10 +45,12 @@ OpticalFlowModule::OpticalFlowModule() m_iModuleType = FRAME_PROCESSING_MODULE; m_pchModuleCategory = "OpticalFlow"; m_uiNumberOfFrames = MODULE_REQUIRES_TWO_FRAMES; - m_uiModuleRequirements = MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; + m_uiModuleRequirements = + MODULE_REQUIRES_SKIP_WHILE_PLAY | MODULE_REQUIRES_NEW_WINDOW | MODULE_REQUIRES_OPTIONS; m_cModuleOptions.addOptions() /**/ - ( "Show reconstruction", m_bShowReconstruction, "Show reconstructed frame instead of MVs [false]" ); + ( "Show reconstruction", m_bShowReconstruction, + "Show reconstructed frame instead of MVs [false]" ); m_bShowReconstruction = false; m_pcOutputFrame = NULL; @@ -65,7 +67,8 @@ Bool OpticalFlowModule::commonCreate( std::vector apcFrameList ) return false; m_iStep = 16; - m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), PlaYUVerFrame::GRAY ); + m_pcOutputFrame = new PlaYUVerFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), + PlaYUVerFrame::GRAY ); return true; } diff --git a/modules/PlaYUVerModuleFactory.cpp b/modules/PlaYUVerModuleFactory.cpp index b22f4e4..198649e 100644 --- a/modules/PlaYUVerModuleFactory.cpp +++ b/modules/PlaYUVerModuleFactory.cpp @@ -22,11 +22,11 @@ * \brief PlaYUVer modules factory */ -#include "config.h" #include "PlaYUVerModuleFactory.h" +#include "config.h" -#include #include +#include #ifdef USE_DYNLOAD #include #endif diff --git a/modules/SetChromaHalfScale.cpp b/modules/SetChromaHalfScale.cpp index 2189ea9..4c0e24d 100644 --- a/modules/SetChromaHalfScale.cpp +++ b/modules/SetChromaHalfScale.cpp @@ -40,8 +40,8 @@ SetChromaHalfScale::SetChromaHalfScale() Void SetChromaHalfScale::create( PlaYUVerFrame* frame ) { m_pcProcessedFrame = NULL; - m_pcProcessedFrame = - new PlaYUVerFrame( frame->getWidth(), frame->getHeight(), frame->getPelFormat(), frame->getBitsPel() ); + m_pcProcessedFrame = new PlaYUVerFrame( frame->getWidth(), frame->getHeight(), + frame->getPelFormat(), frame->getBitsPel() ); } PlaYUVerFrame* SetChromaHalfScale::process( PlaYUVerFrame* frame ) diff --git a/modules/WeightedPSNR.cpp b/modules/WeightedPSNR.cpp index 70f1aa1..ad904e4 100644 --- a/modules/WeightedPSNR.cpp +++ b/modules/WeightedPSNR.cpp @@ -57,7 +57,8 @@ Bool WeightedPSNR::create( std::vector apcFrameList ) } for( UInt i = 1; i < apcFrameList.size(); i++ ) { - if( !apcFrameList[i]->haveSameFmt( apcFrameList[1], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_BITS ) ) + if( !apcFrameList[i]->haveSameFmt( + apcFrameList[1], PlaYUVerFrame::MATCH_COLOR_SPACE | PlaYUVerFrame::MATCH_BITS ) ) return false; } return true; diff --git a/tools/PlaYUVerTools.cpp b/tools/PlaYUVerTools.cpp index d122cce..ce2467b 100644 --- a/tools/PlaYUVerTools.cpp +++ b/tools/PlaYUVerTools.cpp @@ -22,16 +22,16 @@ * \brief Main definition of the PlaYUVerTools APp */ -#include "config.h" #include "PlaYUVerTools.h" +#include "config.h" -#include #include +#include -#include "lib/PlaYUVerPixel.h" #include "lib/PlaYUVerFrame.h" -#include "lib/PlaYUVerStream.h" #include "lib/PlaYUVerModuleIf.h" +#include "lib/PlaYUVerPixel.h" +#include "lib/PlaYUVerStream.h" #include "modules/PlaYUVerModuleFactory.h" PlaYUVerTools::PlaYUVerTools() @@ -102,7 +102,8 @@ Int PlaYUVerTools::openInputs() pcStream = new PlaYUVerStream; try { - if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, uiEndianness, 1, true ) ) + if( !pcStream->open( inputFileNames[i], resolutionString, fmtString, uiBitPerPixel, + uiEndianness, 1, true ) ) { log( LOG_ERROR, "Cannot open input stream %s! ", inputFileNames[i].c_str() ); return 2; @@ -111,8 +112,8 @@ Int PlaYUVerTools::openInputs() } catch( const char* msg ) { - log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", inputFileNames[i].c_str(), - msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error: \n%s\n", + inputFileNames[i].c_str(), msg ); return 2; } } @@ -128,8 +129,8 @@ Int PlaYUVerTools::openInputs() for( UInt i = 0; i < m_apcInputStreams.size(); i++ ) { m_uiNumberOfFrames = std::min( m_uiNumberOfFrames, m_apcInputStreams[i]->getFrameNum() ); - m_uiNumberOfComponents = - std::min( m_uiNumberOfComponents, m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() ); + m_uiNumberOfComponents = std::min( m_uiNumberOfComponents, + m_apcInputStreams[i]->getCurrFrame()->getNumberChannels() ); } return 0; @@ -174,7 +175,9 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) m_pcOutputFileNames.push_back( m_strOutput ); if( m_pcOutputFileNames.size() != m_apcInputStreams.size() ) { - log( LOG_ERROR, "Invalid number of outputs! Each input must have an output filename. " ); + log( LOG_ERROR, + "Invalid number of outputs! Each input must have an " + "output filename. " ); return 2; } @@ -211,14 +214,14 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) PlaYUVerStream* pcOutputStream = new PlaYUVerStream; try { - pcOutputStream->open( m_pcOutputFileNames[0], pcInputFrame->getWidth(), pcInputFrame->getHeight(), - pcInputFrame->getPelFormat(), pcInputFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, - false ); + pcOutputStream->open( m_pcOutputFileNames[0], pcInputFrame->getWidth(), + pcInputFrame->getHeight(), pcInputFrame->getPelFormat(), + pcInputFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ); } catch( const char* msg ) { - log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", m_pcOutputFileNames[0].c_str(), - msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", + m_pcOutputFileNames[0].c_str(), msg ); delete pcOutputStream; pcOutputStream = NULL; return 2; @@ -227,7 +230,9 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) if( m_apcOutputStreams.size() != m_apcInputStreams.size() ) { - log( LOG_ERROR, "Invalid number of outputs! Each input must have an output filename. " ); + log( LOG_ERROR, + "Invalid number of outputs! Each input must have an " + "output filename. " ); return 2; } @@ -249,7 +254,8 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) } for( UInt i = 0; i < PlaYUVerFrame::supportedQualityMetricsList().size(); i++ ) { - if( lowercase( PlaYUVerFrame::supportedQualityMetricsList()[i] ) == lowercase( qualityMetric ) ) + if( lowercase( PlaYUVerFrame::supportedQualityMetricsList()[i] ) == + lowercase( qualityMetric ) ) { m_uiQualityMetric = i; } @@ -339,12 +345,13 @@ Int PlaYUVerTools::Open( Int argc, Char* argv[] ) try { pcModStream->open( outputFileNames[0], pcModFrame->getWidth(), pcModFrame->getHeight(), - pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), PLAYUVER_LITTLE_ENDIAN, 1, false ); + pcModFrame->getPelFormat(), pcModFrame->getBitsPel(), + PLAYUVER_LITTLE_ENDIAN, 1, false ); } catch( const char* msg ) { - log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", outputFileNames[0].c_str(), - msg ); + log( LOG_ERROR, "Cannot open input stream %s with the following error %s!\n", + outputFileNames[0].c_str(), msg ); delete pcModStream; pcModStream = NULL; return 2; @@ -420,7 +427,8 @@ Int PlaYUVerTools::RateReductionOperation() Int PlaYUVerTools::QualityOperation() { - const char* pchQualityMetricName = PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); + const char* pchQualityMetricName = + PlaYUVerFrame::supportedQualityMetricsList()[m_uiQualityMetric].c_str(); PlaYUVerFrame* apcCurrFrame[MAX_NUMBER_INPUTS]; Bool abEOF[MAX_NUMBER_INPUTS]; Double adAverageQuality[MAX_NUMBER_INPUTS - 1][PlaYUVerPixel::MAX_NUMBER_COMPONENTS]; @@ -480,7 +488,8 @@ Int PlaYUVerTools::QualityOperation() for( UInt c = 0; c < m_uiNumberOfComponents; c++ ) { dQuality = apcCurrFrame[s]->getQuality( m_uiQualityMetric, apcCurrFrame[0], c ); - adAverageQuality[s - 1][c] = ( adAverageQuality[s - 1][c] * Double( frame ) + dQuality ) / Double( frame + 1 ); + adAverageQuality[s - 1][c] = + ( adAverageQuality[s - 1][c] * Double( frame ) + dQuality ) / Double( frame + 1 ); log( LOG_RESULT, metric_fmt.c_str(), dQuality ); } log( LOG_RESULT, " " ); @@ -566,7 +575,8 @@ Int PlaYUVerTools::ModuleOperation() log( LOG_INFO, " %3d", frame ); log( LOG_RESULT, " %8.3f \n", dMeasurementResult ); dAveragedMeasurementResult = - ( dAveragedMeasurementResult * Double( frame ) + dMeasurementResult ) / Double( frame + 1 ); + ( dAveragedMeasurementResult * Double( frame ) + dMeasurementResult ) / + Double( frame + 1 ); } for( UInt s = 0; s < m_apcInputStreams.size(); s++ ) diff --git a/tools/PlaYUVerToolsCmdParser.cpp b/tools/PlaYUVerToolsCmdParser.cpp index a893787..7c3aa60 100644 --- a/tools/PlaYUVerToolsCmdParser.cpp +++ b/tools/PlaYUVerToolsCmdParser.cpp @@ -24,12 +24,12 @@ #include "PlaYUVerToolsCmdParser.h" -#include #include +#include #include "lib/PlaYUVerFrame.h" -#include "lib/PlaYUVerStream.h" #include "lib/PlaYUVerModuleIf.h" +#include "lib/PlaYUVerStream.h" #include "modules/PlaYUVerModuleFactory.h" PlaYUVerToolsCmdParser::PlaYUVerToolsCmdParser() @@ -90,7 +90,10 @@ Int PlaYUVerToolsCmdParser::parseToolsArgs( Int argc, Char* argv[] ) } else if( m_cOptions.hasOpt( "help" ) ) { - printf( "Usage: %s modules/quality/save [options] -input=input_file [--output=output_file]\n", argv[0] ); + printf( + "Usage: %s modules/quality/save [options] -input=input_file " + "[--output=output_file]\n", + argv[0] ); m_cOptions.doHelp( std::cout ); iRet = 1; } From 8684a01a10d25802d87020a04cc8363b4af08d4f Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 04:32:52 +0000 Subject: [PATCH 125/127] Format code --- lib/StreamHandlerLibav.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/StreamHandlerLibav.cpp b/lib/StreamHandlerLibav.cpp index acaa31b..8b8aaf4 100644 --- a/lib/StreamHandlerLibav.cpp +++ b/lib/StreamHandlerLibav.cpp @@ -39,7 +39,8 @@ std::vector StreamHandlerLibav::supportedReadFormats() REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Audio video interleaved", "avi" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Windows media video", "wmv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "MPEG4", "mp4" ); - REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", "mkv" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "Matroska Multimedia Container", + "mkv" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "H.264 streams", "h264" ); REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerLibav::Create, "HEVC streams", "hevc" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; @@ -129,7 +130,8 @@ Bool StreamHandlerLibav::openHandler( String strFilename, Bool bInput ) return false; } - m_uiFrameBufferSize = av_image_get_buffer_size( AVPixelFormat( codec_param->format ), codec_param->width, codec_param->height, 1 ); + m_uiFrameBufferSize = av_image_get_buffer_size( AVPixelFormat( codec_param->format ), + codec_param->width, codec_param->height, 1 ); getMem1D( &m_pchFrameBuffer, m_uiFrameBufferSize ); m_strFormatName = uppercase( strFilename.substr( strFilename.find_last_of( "." ) + 1 ) ); @@ -331,7 +333,8 @@ Bool StreamHandlerLibav::read( PlaYUVerFrame* pcFrame ) if( bGotFrame ) { AVCodecParameters* codec_param = m_cStream->codecpar; - av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, m_cFrame->linesize, AVPixelFormat( codec_param->format ), + av_image_copy_to_buffer( m_pStreamBuffer, m_uiFrameBufferSize, m_cFrame->data, + m_cFrame->linesize, AVPixelFormat( codec_param->format ), codec_param->width, codec_param->height, 1 ); if( orig_pkt.size ) av_free_packet( &orig_pkt ); From f6f3cf15abfa90e225a81c9d8a35ea09f06e0c4e Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 20:26:28 +0000 Subject: [PATCH 126/127] Add support for device opening --- app/ModulesHandle.cpp | 2 +- app/PlaYUVerApp.cpp | 21 ++++++++------------- app/PlaYUVerApp.h | 4 +--- lib/PlaYUVerStream.cpp | 9 ++++----- lib/PlaYUVerStreamHandlerIf.h | 2 ++ lib/StreamHandlerOpenCV.cpp | 13 +++++++++---- 6 files changed, 25 insertions(+), 26 deletions(-) diff --git a/app/ModulesHandle.cpp b/app/ModulesHandle.cpp index 6aa9773..0c13f68 100644 --- a/app/ModulesHandle.cpp +++ b/app/ModulesHandle.cpp @@ -449,7 +449,7 @@ Void ModulesHandle::activateModule() if( pcCurrAppModuleIf->m_pcModule->m_iModuleAPI == MODULE_API_2 ) { std::vector apcFrameList; - for( UInt i = 0; i < videoSubWindowList.size(); i++ ) + for( Int i = 0; i < videoSubWindowList.size(); i++ ) { apcFrameList.push_back( pcCurrAppModuleIf->m_pcSubWindow[i]->getCurrFrame() ); } diff --git a/app/PlaYUVerApp.cpp b/app/PlaYUVerApp.cpp index 37ada00..c1ef172 100644 --- a/app/PlaYUVerApp.cpp +++ b/app/PlaYUVerApp.cpp @@ -189,11 +189,6 @@ Void PlaYUVerApp::loadFile( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) printMessage( "File " + fileName + " do not exist!", LOG_ERROR ); return; } - load( fileName, pStreamInfo ); -} - -Void PlaYUVerApp::load( QString fileName, PlaYUVerStreamInfo* pStreamInfo ) -{ VideoSubWindow* videoSubWindow = PlaYUVerApp::findVideoStreamSubWindow( m_pcWindowHandle, fileName ); if( videoSubWindow ) @@ -293,10 +288,10 @@ Void PlaYUVerApp::open() } } -Void PlaYUVerApp::openDevice() -{ - load( "/dev/video0", NULL ); -} +// Void PlaYUVerApp::openDevice() +//{ +// loadFile( "/dev/video0", NULL ); +//} Void PlaYUVerApp::openRecent() { @@ -620,9 +615,9 @@ Void PlaYUVerApp::createActions() m_arrayActions[OPEN_ACT]->setStatusTip( tr( "Open stream" ) ); connect( m_arrayActions[OPEN_ACT], SIGNAL( triggered() ), this, SLOT( open() ) ); - m_arrayActions[OPEN_DEVICE_ACT] = new QAction( tr( "&Open Capture Device" ), this ); - m_arrayActions[OPEN_DEVICE_ACT]->setStatusTip( tr( "Open capture device (webcam)" ) ); - connect( m_arrayActions[OPEN_DEVICE_ACT], SIGNAL( triggered() ), this, SLOT( openDevice() ) ); + // m_arrayActions[OPEN_DEVICE_ACT] = new QAction( tr( "&Open Capture Device" ), this ); + // m_arrayActions[OPEN_DEVICE_ACT]->setStatusTip( tr( "Open capture device (webcam)" ) ); + // connect( m_arrayActions[OPEN_DEVICE_ACT], SIGNAL( triggered() ), this, SLOT( openDevice() ) ); m_arrayRecentFilesActions.resize( MAX_RECENT_FILES ); for( Int i = 0; i < MAX_RECENT_FILES; i++ ) @@ -747,7 +742,7 @@ Void PlaYUVerApp::createMenus() m_arrayMenu[FILE_MENU] = menuBar()->addMenu( tr( "&File" ) ); m_arrayMenu[FILE_MENU]->addAction( m_arrayActions[OPEN_ACT] ); - m_arrayMenu[FILE_MENU]->addAction( m_arrayActions[OPEN_DEVICE_ACT] ); + // m_arrayMenu[FILE_MENU]->addAction( m_arrayActions[OPEN_DEVICE_ACT] ); m_arrayMenu[RECENT_MENU] = m_arrayMenu[FILE_MENU]->addMenu( tr( "Open Recent" ) ); for( Int i = 0; i < MAX_RECENT_FILES; ++i ) { diff --git a/app/PlaYUVerApp.h b/app/PlaYUVerApp.h index c757d1b..0e041b0 100644 --- a/app/PlaYUVerApp.h +++ b/app/PlaYUVerApp.h @@ -89,7 +89,7 @@ class PlaYUVerApp : public QMainWindow * File functions slots */ void open(); - void openDevice(); + // void openDevice(); void openRecent(); void save(); void format(); @@ -129,8 +129,6 @@ class PlaYUVerApp : public QMainWindow static VideoSubWindow* findVideoStreamSubWindow( const PlaYUVerSubWindowHandle* windowManager, const QString& fileName ); - Void load( QString fileName, PlaYUVerStreamInfo* pStreamInfo ); - Void updateMenus(); Void createActions(); diff --git a/lib/PlaYUVerStream.cpp b/lib/PlaYUVerStream.cpp index 0e2109b..ac8b795 100644 --- a/lib/PlaYUVerStream.cpp +++ b/lib/PlaYUVerStream.cpp @@ -120,11 +120,10 @@ CreateStreamHandlerFn PlaYUVerStream::findStreamHandler( String strFilename, boo { return supportedFmts[i].formatFct; } - // else if( strFilename.find( supportedFmts[i].formatExt ) != - // String::npos ) - // { - // return supportedFmts[i].formatFct; - // } + else if( strFilename.find( supportedFmts[i].formatExt ) != String::npos ) + { + return supportedFmts[i].formatFct; + } } return &StreamHandlerRaw::Create; } diff --git a/lib/PlaYUVerStreamHandlerIf.h b/lib/PlaYUVerStreamHandlerIf.h index 3d73c2c..cff5531 100644 --- a/lib/PlaYUVerStreamHandlerIf.h +++ b/lib/PlaYUVerStreamHandlerIf.h @@ -34,6 +34,8 @@ class PlaYUVerFrame; public: \ static PlaYUVerStreamHandlerIf* Create() { return new X(); } \ void Delete() { delete this; } + + /** * \class PlaYUVerStreamHandlerIf * \ingroup PlaYUVerLib_Stream diff --git a/lib/StreamHandlerOpenCV.cpp b/lib/StreamHandlerOpenCV.cpp index e211e5a..63abd02 100644 --- a/lib/StreamHandlerOpenCV.cpp +++ b/lib/StreamHandlerOpenCV.cpp @@ -40,8 +40,7 @@ using cv::VideoCapture; std::vector StreamHandlerOpenCV::supportedReadFormats() { INI_REGIST_PLAYUVER_SUPPORTED_FMT; - // REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", - // "/dev/" ); + REGIST_PLAYUVER_SUPPORTED_FMT( &StreamHandlerOpenCV::Create, "Device", "/dev/" ); END_REGIST_PLAYUVER_SUPPORTED_FMT; } @@ -71,9 +70,15 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) */ if( m_cFilename.find( "/dev/video" ) != String::npos ) { + Int iDeviceId = 0; + if( m_cFilename.find( "/dev/video0" ) != String::npos ) + iDeviceId = 0; + else if( m_cFilename.find( "/dev/video1" ) != String::npos ) + iDeviceId = 1; + m_strFormatName = "DEV"; m_strCodecName = "Raw Video"; - pcVideoCapture = new VideoCapture( 0 ); + pcVideoCapture = new VideoCapture( iDeviceId ); m_uiWidth = pcVideoCapture->get( CV_CAP_PROP_FRAME_WIDTH ); m_uiHeight = pcVideoCapture->get( CV_CAP_PROP_FRAME_HEIGHT ); m_dFrameRate = 25; @@ -88,7 +93,7 @@ Bool StreamHandlerOpenCV::openHandler( String strFilename, Bool bInput ) m_dFrameRate = 1; } m_uiBitsPerPixel = 8; - m_iPixelFormat = PlaYUVerFrame::findPixelFormat( "BGR24" ); + m_iPixelFormat = PlaYUVerFrame::findPixelFormat( "BGR" ); } return true; From 3692c9f4575c9aa423e98614400ba72bbf0b68cd Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Thu, 23 Mar 2017 21:20:51 +0000 Subject: [PATCH 127/127] Change CMakelists to include some header files --- lib/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 21d32b0..32af0ea 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -5,6 +5,8 @@ INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ) set(PlaYUVer_Lib_SRCS + LibMemory.h + PlaYUVerLib.h # Frame PlaYUVerPixel.cpp PlaYUVerFrame.cpp @@ -15,6 +17,8 @@ set(PlaYUVer_Lib_SRCS StreamHandlerPortableMap.cpp # Options Parser PlaYUVerOptions.cpp + # Modules + PlaYUVerModuleIf.h ) IF( USE_FFMPEG )