#4683 clang-format on all files in ApplicationCode

This commit is contained in:
Magne Sjaastad
2019-09-06 10:40:57 +02:00
parent 3a317504bb
commit fe9e567825
2092 changed files with 117952 additions and 111846 deletions

View File

@@ -1,26 +1,24 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
// Company and Application name
// These two together will become the registry key
const char RI_COMPANY_NAME[] = "Ceetron";
const char RI_APPLICATION_NAME[] = "ResInsight";
const char RI_COMPANY_NAME[] = "Ceetron";
const char RI_APPLICATION_NAME[] = "ResInsight";

File diff suppressed because it is too large Load Diff

View File

@@ -97,16 +97,16 @@ public:
EXIT_COMPLETED,
EXIT_WITH_ERROR
};
public:
static RiaApplication* instance();
static RiaApplication* instance();
RiaApplication();
virtual ~RiaApplication();
static const char* getVersionStringApp(bool includeCrtInfo);
static const char* getVersionStringApp( bool includeCrtInfo );
static bool enableDevelopmentFeatures();
void setActiveReservoirView(Rim3dView*);
void setActiveReservoirView( Rim3dView* );
Rim3dView* activeReservoirView();
const Rim3dView* activeReservoirView() const;
RimGridView* activeGridView();
@@ -119,76 +119,81 @@ public:
void createMockModelCustomized();
void createInputMockModel();
bool openFile(const QString& fileName);
bool openFile( const QString& fileName );
bool isProjectSavedToDisc() const;
QString currentProjectPath() const;
QString createAbsolutePathFromProjectRelativePath(QString projectRelativePath);
bool loadProject(const QString& projectFileName);
bool loadProject(const QString& projectFileName, ProjectLoadAction loadAction, RiaProjectModifier* projectModifier);
bool saveProjectAs(const QString& fileName, QString* errorMessage);
static bool hasValidProjectFileExtension(const QString& fileName);
bool isProjectSavedToDisc() const;
QString currentProjectPath() const;
QString createAbsolutePathFromProjectRelativePath( QString projectRelativePath );
bool loadProject( const QString& projectFileName );
bool loadProject( const QString& projectFileName, ProjectLoadAction loadAction, RiaProjectModifier* projectModifier );
bool saveProjectAs( const QString& fileName, QString* errorMessage );
static bool hasValidProjectFileExtension( const QString& fileName );
void closeProject();
QString lastUsedDialogDirectory(const QString& dialogName);
QString lastUsedDialogDirectoryWithFallbackToProjectFolder(const QString& dialogName);
QString lastUsedDialogDirectoryWithFallback(const QString& dialogName, const QString& fallbackDirectory);
void setLastUsedDialogDirectory(const QString& dialogName, const QString& directory);
QString lastUsedDialogDirectory( const QString& dialogName );
QString lastUsedDialogDirectoryWithFallbackToProjectFolder( const QString& dialogName );
QString lastUsedDialogDirectoryWithFallback( const QString& dialogName, const QString& fallbackDirectory );
void setLastUsedDialogDirectory( const QString& dialogName, const QString& directory );
bool openOdbCaseFromFile(const QString& fileName, bool applyTimeStepFilter = false);
bool openOdbCaseFromFile( const QString& fileName, bool applyTimeStepFilter = false );
void addWellPathsToModel(QList<QString> wellPathFilePaths);
void addWellPathFormationsToModel(QList<QString> wellPathFilePaths);
void addWellLogsToModel(const QList<QString>& wellLogFilePaths);
void addWellPathsToModel( QList<QString> wellPathFilePaths );
void addWellPathFormationsToModel( QList<QString> wellPathFilePaths );
void addWellLogsToModel( const QList<QString>& wellLogFilePaths );
QString scriptDirectories() const;
QString scriptEditorPath() const;
QString octavePath() const;
QStringList octaveArguments() const;
QString octavePath() const;
QStringList octaveArguments() const;
QProcessEnvironment octaveProcessEnvironment() const;
QString pythonPath() const;
QProcessEnvironment pythonProcessEnvironment() const;
bool launchProcess(const QString& program, const QStringList& arguments, const QProcessEnvironment& processEnvironment);
bool launchProcessForMultipleCases(const QString& program, const QStringList& arguments, const std::vector<int>& caseIds, const QProcessEnvironment& processEnvironment);
bool launchProcess( const QString& program,
const QStringList& arguments,
const QProcessEnvironment& processEnvironment );
bool launchProcessForMultipleCases( const QString& program,
const QStringList& arguments,
const std::vector<int>& caseIds,
const QProcessEnvironment& processEnvironment );
void terminateProcess();
void waitForProcess() const;
RiaPreferences* preferences();
void applyPreferences(const RiaPreferences* oldPreferences = nullptr);
void applyPreferences( const RiaPreferences* oldPreferences = nullptr );
QString commandLineParameterHelp();
void setCommandLineHelpText(const QString& commandLineHelpText);
void setCommandLineHelpText( const QString& commandLineHelpText );
void setCacheDataObject(const QString& key, const QVariant& dataObject);
QVariant cacheDataObject(const QString& key) const;
void setCacheDataObject( const QString& key, const QVariant& dataObject );
QVariant cacheDataObject( const QString& key ) const;
void executeCommandFile(const QString& commandFile);
void addCommandObject(RimCommandObject* commandObject);
void executeCommandFile( const QString& commandFile );
void addCommandObject( RimCommandObject* commandObject );
void executeCommandObjects();
void waitUntilCommandObjectsHasBeenProcessed();
int launchUnitTests();
const QString startDir() const;
void setStartDir(const QString& startDir);
void setStartDir( const QString& startDir );
static std::vector<QString> readFileListFromTextFile(QString listFileName);
static std::vector<QString> readFileListFromTextFile( QString listFileName );
cvf::Font* defaultSceneFont();
cvf::Font* defaultAnnotationFont();
cvf::Font* defaultWellLabelFont();
bool initializeGrpcServer(const cvf::ProgramOptions& progOpt);
bool initializeGrpcServer( const cvf::ProgramOptions& progOpt );
// Public implementation specific overrides
virtual void initialize();
virtual ApplicationStatus handleArguments(cvf::ProgramOptions* progOpt) = 0;
virtual int launchUnitTestsWithConsole();
virtual void addToRecentFiles(const QString& fileName) {}
virtual void showFormattedTextInMessageBoxOrConsole(const QString& errMsg) = 0;
virtual void initialize();
virtual ApplicationStatus handleArguments( cvf::ProgramOptions* progOpt ) = 0;
virtual int launchUnitTestsWithConsole();
virtual void addToRecentFiles( const QString& fileName ) {}
virtual void showFormattedTextInMessageBoxOrConsole( const QString& errMsg ) = 0;
virtual void launchGrpcServer() = 0;
@@ -197,14 +202,14 @@ public:
#endif
protected:
// Protected implementation specific overrides
virtual void invokeProcessEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents) = 0;
virtual void onFileSuccessfullyLoaded(const QString& fileName, RiaDefines::ImportFileType fileType) {}
virtual void invokeProcessEvents( QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents ) = 0;
virtual void onFileSuccessfullyLoaded( const QString& fileName, RiaDefines::ImportFileType fileType ) {}
virtual void onProjectBeingOpened() {}
virtual void onProjectOpened() = 0;
virtual void onProjectOpeningError(const QString& errMsg) = 0;
virtual void onProjectOpened() = 0;
virtual void onProjectOpeningError( const QString& errMsg ) = 0;
virtual void onProjectBeingClosed() {}
virtual void onProjectClosed() = 0;
virtual void startMonitoringWorkProgress(caf::UiProcess* uiProcess) {}
virtual void startMonitoringWorkProgress( caf::UiProcess* uiProcess ) {}
virtual void stopMonitoringWorkProgress() {}
protected:
@@ -223,15 +228,15 @@ protected:
#endif
// Execute for all settings
std::list<int> m_currentCaseIds;
QString m_currentProgram;
QStringList m_currentArguments;
std::list<int> m_currentCaseIds;
QString m_currentProgram;
QStringList m_currentArguments;
RiaPreferences* m_preferences;
std::map<QString, QString> m_fileDialogDefaultDirectories;
QString m_startupDefaultDirectory;
QString m_commandLineHelpText;
QMap<QString, QVariant> m_sessionCache; // Session cache used to store username/passwords per session
QMap<QString, QVariant> m_sessionCache; // Session cache used to store username/passwords per session
std::list<RimCommandObject*> m_commandQueue;
QMutex m_commandQueueLock;
@@ -241,6 +246,3 @@ protected:
private:
static RiaApplication* s_riaApplication;
};

View File

@@ -20,8 +20,8 @@
#include "RiaApplication.h"
#include "RigEclipseCaseData.h"
#include "RigCaseCellResultsData.h"
#include "RigEclipseCaseData.h"
#include "RimEclipseCase.h"
#include "RimEclipseCaseCollection.h"
@@ -37,8 +37,8 @@
#include <QTimer>
#include <QTreeView>
#include <set>
#include "cafProgressState.h"
#include <set>
//--------------------------------------------------------------------------------------------------
///
@@ -58,39 +58,41 @@ void RiaCompletionTypeCalculationScheduler::scheduleRecalculateCompletionTypeAnd
std::vector<RimEclipseCase*> eclipseCases =
RiaApplication::instance()->project()->activeOilField()->analysisModels->cases().childObjects();
scheduleRecalculateCompletionTypeAndRedrawAllViews(eclipseCases);
scheduleRecalculateCompletionTypeAndRedrawAllViews( eclipseCases );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaCompletionTypeCalculationScheduler::scheduleRecalculateCompletionTypeAndRedrawAllViews(RimEclipseCase* eclipseCase)
void RiaCompletionTypeCalculationScheduler::scheduleRecalculateCompletionTypeAndRedrawAllViews( RimEclipseCase* eclipseCase )
{
std::vector<RimEclipseCase*> eclipseCases;
eclipseCases.push_back(eclipseCase);
eclipseCases.push_back( eclipseCase );
scheduleRecalculateCompletionTypeAndRedrawAllViews(eclipseCases);
scheduleRecalculateCompletionTypeAndRedrawAllViews( eclipseCases );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaCompletionTypeCalculationScheduler::scheduleRecalculateCompletionTypeAndRedrawAllViews(
const std::vector<RimEclipseCase*>& eclipseCases)
const std::vector<RimEclipseCase*>& eclipseCases )
{
for (RimEclipseCase* eclipseCase : eclipseCases)
for ( RimEclipseCase* eclipseCase : eclipseCases )
{
CVF_ASSERT(eclipseCase);
CVF_ASSERT( eclipseCase );
if (eclipseCase->eclipseCaseData())
if ( eclipseCase->eclipseCaseData() )
{
eclipseCase->eclipseCaseData()->results(RiaDefines::MATRIX_MODEL)->clearScalarResult(RiaDefines::DYNAMIC_NATIVE, RiaDefines::completionTypeResultName());
eclipseCase->eclipseCaseData()
->results( RiaDefines::MATRIX_MODEL )
->clearScalarResult( RiaDefines::DYNAMIC_NATIVE, RiaDefines::completionTypeResultName() );
// Delete virtual perforation transmissibilities, as these are the basis for the computation of completion type
eclipseCase->eclipseCaseData()->setVirtualPerforationTransmissibilities(nullptr);
eclipseCase->eclipseCaseData()->setVirtualPerforationTransmissibilities( nullptr );
}
m_eclipseCasesToRecalculate.push_back(eclipseCase);
m_eclipseCasesToRecalculate.push_back( eclipseCase );
}
startTimer();
@@ -107,19 +109,19 @@ void RiaCompletionTypeCalculationScheduler::slotRecalculateCompletionType()
return;
}
std::set<RimEclipseCase*> uniqueCases(m_eclipseCasesToRecalculate.begin(), m_eclipseCasesToRecalculate.end());
std::set<RimEclipseCase*> uniqueCases( m_eclipseCasesToRecalculate.begin(), m_eclipseCasesToRecalculate.end() );
Rim3dView* activeView = RiaApplication::instance()->activeReservoirView();
QModelIndex mi = RiuMainWindow::instance()->projectTreeView()->treeView()->currentIndex();
for (RimEclipseCase* eclipseCase : uniqueCases)
for ( RimEclipseCase* eclipseCase : uniqueCases )
{
if (eclipseCase)
if ( eclipseCase )
{
for (const auto& w : eclipseCase->views())
for ( const auto& w : eclipseCase->views() )
{
RimEclipseView* eclView = dynamic_cast<RimEclipseView*>(w);
if (eclView)
RimEclipseView* eclView = dynamic_cast<RimEclipseView*>( w );
if ( eclView )
{
eclView->calculateCompletionTypeAndRedrawIfRequired();
}
@@ -132,15 +134,15 @@ void RiaCompletionTypeCalculationScheduler::slotRecalculateCompletionType()
// Recalculation of completion type causes active view to be set to potentially a different view
// Also current index in project tree is changed. Restore both to initial state.
if (activeView && activeView->viewer())
if ( activeView && activeView->viewer() )
{
RiaApplication::instance()->setActiveReservoirView(activeView);
RiuMainWindow::instance()->setActiveViewer(activeView->viewer()->layoutWidget());
RiaApplication::instance()->setActiveReservoirView( activeView );
RiuMainWindow::instance()->setActiveViewer( activeView->viewer()->layoutWidget() );
}
if (mi.isValid())
if ( mi.isValid() )
{
RiuMainWindow::instance()->projectTreeView()->treeView()->setCurrentIndex(mi);
RiuMainWindow::instance()->projectTreeView()->treeView()->setCurrentIndex( mi );
}
}
@@ -157,12 +159,12 @@ RiaCompletionTypeCalculationScheduler::~RiaCompletionTypeCalculationScheduler()
//--------------------------------------------------------------------------------------------------
void RiaCompletionTypeCalculationScheduler::startTimer()
{
if (!m_recalculateCompletionTypeTimer)
if ( !m_recalculateCompletionTypeTimer )
{
m_recalculateCompletionTypeTimer = new QTimer(this);
m_recalculateCompletionTypeTimer->setSingleShot(true);
connect(m_recalculateCompletionTypeTimer, SIGNAL(timeout()), this, SLOT(slotRecalculateCompletionType()));
m_recalculateCompletionTypeTimer = new QTimer( this );
m_recalculateCompletionTypeTimer->setSingleShot( true );
connect( m_recalculateCompletionTypeTimer, SIGNAL( timeout() ), this, SLOT( slotRecalculateCompletionType() ) );
}
m_recalculateCompletionTypeTimer->start(1500);
m_recalculateCompletionTypeTimer->start( 1500 );
}

View File

@@ -30,28 +30,30 @@ class RimEclipseCase;
class RiaCompletionTypeCalculationScheduler : public QObject
{
Q_OBJECT;
public:
static RiaCompletionTypeCalculationScheduler* instance();
void scheduleRecalculateCompletionTypeAndRedrawAllViews();
void scheduleRecalculateCompletionTypeAndRedrawAllViews(RimEclipseCase* eclipseCase);
void scheduleRecalculateCompletionTypeAndRedrawAllViews();
void scheduleRecalculateCompletionTypeAndRedrawAllViews( RimEclipseCase* eclipseCase );
private slots:
void slotRecalculateCompletionType();
void slotRecalculateCompletionType();
private:
RiaCompletionTypeCalculationScheduler() : m_recalculateCompletionTypeTimer(nullptr) {}
RiaCompletionTypeCalculationScheduler()
: m_recalculateCompletionTypeTimer( nullptr )
{
}
~RiaCompletionTypeCalculationScheduler() override;
RiaCompletionTypeCalculationScheduler(const RiaCompletionTypeCalculationScheduler& o) = delete;
void operator=(const RiaCompletionTypeCalculationScheduler& o) = delete;
RiaCompletionTypeCalculationScheduler( const RiaCompletionTypeCalculationScheduler& o ) = delete;
void operator=( const RiaCompletionTypeCalculationScheduler& o ) = delete;
void scheduleRecalculateCompletionTypeAndRedrawAllViews(const std::vector<RimEclipseCase*>& eclipseCases);
void scheduleRecalculateCompletionTypeAndRedrawAllViews( const std::vector<RimEclipseCase*>& eclipseCases );
void startTimer();
private:
std::vector<caf::PdmPointer<RimEclipseCase> > m_eclipseCasesToRecalculate;
QTimer* m_recalculateCompletionTypeTimer;
std::vector<caf::PdmPointer<RimEclipseCase>> m_eclipseCasesToRecalculate;
QTimer* m_recalculateCompletionTypeTimer;
};

View File

@@ -39,19 +39,19 @@
//--------------------------------------------------------------------------------------------------
RiaConsoleApplication* RiaConsoleApplication::instance()
{
RiaConsoleApplication* currentConsoleApp = dynamic_cast<RiaConsoleApplication*>(RiaApplication::instance());
CAF_ASSERT(currentConsoleApp && "Should never be called from a method that isn't within the Console context");
RiaConsoleApplication* currentConsoleApp = dynamic_cast<RiaConsoleApplication*>( RiaApplication::instance() );
CAF_ASSERT( currentConsoleApp && "Should never be called from a method that isn't within the Console context" );
return currentConsoleApp;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaConsoleApplication::RiaConsoleApplication(int& argc, char** argv)
: QCoreApplication(argc, argv)
RiaConsoleApplication::RiaConsoleApplication( int& argc, char** argv )
: QCoreApplication( argc, argv )
, RiaApplication()
{
installEventFilter(this);
installEventFilter( this );
}
//--------------------------------------------------------------------------------------------------
@@ -68,20 +68,20 @@ RiaConsoleApplication::~RiaConsoleApplication()
void RiaConsoleApplication::initialize()
{
#ifdef _WIN32
#pragma warning(push) // Saves the current warning state.
#pragma warning(disable : 4996) // Temporarily disables warning 4996.
#pragma warning( push ) // Saves the current warning state.
#pragma warning( disable : 4996 ) // Temporarily disables warning 4996.
bool isReOpenStdToConsoleNeeded = false;
if ( AttachConsole(ATTACH_PARENT_PROCESS) )
if ( AttachConsole( ATTACH_PARENT_PROCESS ) )
{
int fileType = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
// FILE_TYPE_CHAR indicates a windows console buffer.
int fileType = GetFileType( GetStdHandle( STD_OUTPUT_HANDLE ) );
// FILE_TYPE_CHAR indicates a windows console buffer.
// FILE_TYPE_PIPE indicates redirection imposed by the starting shell (eg migw shell)
// If we are dealing with a pipe, we do not want to do the reopen, and destroy the connection.
if (fileType == FILE_TYPE_CHAR )
if ( fileType == FILE_TYPE_CHAR )
{
isReOpenStdToConsoleNeeded = true;
}
@@ -91,135 +91,136 @@ void RiaConsoleApplication::initialize()
isReOpenStdToConsoleNeeded = true;
}
if (isReOpenStdToConsoleNeeded)
if ( isReOpenStdToConsoleNeeded )
{
freopen("conout$", "w", stdout);
freopen("conout$", "w", stderr);
freopen("conin$", "r", stdin);
freopen( "conout$", "w", stdout );
freopen( "conout$", "w", stderr );
freopen( "conin$", "r", stdin );
}
#pragma warning(pop)
#pragma warning( pop )
#endif
RiaApplication::initialize();
RiaLogging::setLoggerInstance(new RiaStdOutLogger);
RiaLogging::loggerInstance()->setLevel(RI_LL_DEBUG);
RiaLogging::setLoggerInstance( new RiaStdOutLogger );
RiaLogging::loggerInstance()->setLevel( RI_LL_DEBUG );
m_socketServer = new RiaSocketServer(this);
m_socketServer = new RiaSocketServer( this );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments(cvf::ProgramOptions* progOpt)
RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments( cvf::ProgramOptions* progOpt )
{
CVF_ASSERT(progOpt);
CVF_ASSERT( progOpt );
// Handling of the actual command line options
// --------------------------------------------------------
if (cvf::Option o = progOpt->option("ignoreArgs"))
if ( cvf::Option o = progOpt->option( "ignoreArgs" ) )
{
return KEEP_GOING;
}
if (progOpt->option("help") || progOpt->option("?"))
if ( progOpt->option( "help" ) || progOpt->option( "?" ) )
{
this->showFormattedTextInMessageBoxOrConsole("\nThe current command line options in ResInsight are:\n"
+ this->commandLineParameterHelp());
this->showFormattedTextInMessageBoxOrConsole( "\nThe current command line options in ResInsight are:\n" +
this->commandLineParameterHelp() );
return RiaApplication::EXIT_COMPLETED;
}
// Unit testing
// --------------------------------------------------------
if (cvf::Option o = progOpt->option("unittest"))
if ( cvf::Option o = progOpt->option( "unittest" ) )
{
int testReturnValue = launchUnitTestsWithConsole();
if (testReturnValue == 0)
if ( testReturnValue == 0 )
{
return RiaApplication::EXIT_COMPLETED;
}
else
{
RiaLogging::error("Error running unit tests");
RiaLogging::error( "Error running unit tests" );
return RiaApplication::EXIT_WITH_ERROR;
}
}
if (cvf::Option o = progOpt->option("startdir"))
if ( cvf::Option o = progOpt->option( "startdir" ) )
{
CVF_ASSERT(o.valueCount() == 1);
setStartDir(cvfqt::Utils::toQString(o.value(0)));
CVF_ASSERT( o.valueCount() == 1 );
setStartDir( cvfqt::Utils::toQString( o.value( 0 ) ) );
}
QString projectFileName;
if (progOpt->hasOption("last"))
if ( progOpt->hasOption( "last" ) )
{
projectFileName = preferences()->lastUsedProjectFileName;
}
if (cvf::Option o = progOpt->option("project"))
if ( cvf::Option o = progOpt->option( "project" ) )
{
CVF_ASSERT(o.valueCount() == 1);
projectFileName = cvfqt::Utils::toQString(o.value(0));
CVF_ASSERT( o.valueCount() == 1 );
projectFileName = cvfqt::Utils::toQString( o.value( 0 ) );
}
if (!projectFileName.isEmpty())
if ( !projectFileName.isEmpty() )
{
cvf::ref<RiaProjectModifier> projectModifier;
RiaApplication::ProjectLoadAction projectLoadAction = RiaApplication::PLA_NONE;
if (cvf::Option o = progOpt->option("replaceCase"))
if ( cvf::Option o = progOpt->option( "replaceCase" ) )
{
if (projectModifier.isNull()) projectModifier = new RiaProjectModifier;
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if (o.valueCount() == 1)
if ( o.valueCount() == 1 )
{
// One argument is available, use replace case for first occurrence in the project
QString gridFileName = cvfqt::Utils::toQString(o.safeValue(0));
projectModifier->setReplaceCaseFirstOccurrence(gridFileName);
QString gridFileName = cvfqt::Utils::toQString( o.safeValue( 0 ) );
projectModifier->setReplaceCaseFirstOccurrence( gridFileName );
}
else
{
size_t optionIdx = 0;
while (optionIdx < o.valueCount())
while ( optionIdx < o.valueCount() )
{
const int caseId = o.safeValue(optionIdx++).toInt(-1);
QString gridFileName = cvfqt::Utils::toQString(o.safeValue(optionIdx++));
const int caseId = o.safeValue( optionIdx++ ).toInt( -1 );
QString gridFileName = cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) );
if (caseId != -1 && !gridFileName.isEmpty())
if ( caseId != -1 && !gridFileName.isEmpty() )
{
projectModifier->setReplaceCase(caseId, gridFileName);
projectModifier->setReplaceCase( caseId, gridFileName );
}
}
}
}
if (cvf::Option o = progOpt->option("replaceSourceCases"))
if ( cvf::Option o = progOpt->option( "replaceSourceCases" ) )
{
if (projectModifier.isNull()) projectModifier = new RiaProjectModifier;
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if (o.valueCount() == 1)
if ( o.valueCount() == 1 )
{
// One argument is available, use replace case for first occurrence in the project
std::vector<QString> gridFileNames = readFileListFromTextFile(cvfqt::Utils::toQString(o.safeValue(0)));
projectModifier->setReplaceSourceCasesFirstOccurrence(gridFileNames);
std::vector<QString> gridFileNames = readFileListFromTextFile(
cvfqt::Utils::toQString( o.safeValue( 0 ) ) );
projectModifier->setReplaceSourceCasesFirstOccurrence( gridFileNames );
}
else
{
size_t optionIdx = 0;
while (optionIdx < o.valueCount())
while ( optionIdx < o.valueCount() )
{
const int groupId = o.safeValue(optionIdx++).toInt(-1);
std::vector<QString> gridFileNames =
readFileListFromTextFile(cvfqt::Utils::toQString(o.safeValue(optionIdx++)));
const int groupId = o.safeValue( optionIdx++ ).toInt( -1 );
std::vector<QString> gridFileNames = readFileListFromTextFile(
cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) ) );
if (groupId != -1 && !gridFileNames.empty())
if ( groupId != -1 && !gridFileNames.empty() )
{
projectModifier->setReplaceSourceCasesById(groupId, gridFileNames);
projectModifier->setReplaceSourceCasesById( groupId, gridFileNames );
}
}
}
@@ -227,125 +228,126 @@ RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments(cvf::Pr
projectLoadAction = RiaApplication::PLA_CALCULATE_STATISTICS;
}
if (cvf::Option o = progOpt->option("replacePropertiesFolder"))
if ( cvf::Option o = progOpt->option( "replacePropertiesFolder" ) )
{
if (projectModifier.isNull()) projectModifier = new RiaProjectModifier;
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if (o.valueCount() == 1)
if ( o.valueCount() == 1 )
{
QString propertiesFolder = cvfqt::Utils::toQString(o.safeValue(0));
projectModifier->setReplacePropertiesFolderFirstOccurrence(propertiesFolder);
QString propertiesFolder = cvfqt::Utils::toQString( o.safeValue( 0 ) );
projectModifier->setReplacePropertiesFolderFirstOccurrence( propertiesFolder );
}
else
{
size_t optionIdx = 0;
while (optionIdx < o.valueCount())
while ( optionIdx < o.valueCount() )
{
const int caseId = o.safeValue(optionIdx++).toInt(-1);
QString propertiesFolder = cvfqt::Utils::toQString(o.safeValue(optionIdx++));
const int caseId = o.safeValue( optionIdx++ ).toInt( -1 );
QString propertiesFolder = cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) );
if (caseId != -1 && !propertiesFolder.isEmpty())
if ( caseId != -1 && !propertiesFolder.isEmpty() )
{
projectModifier->setReplacePropertiesFolder(caseId, propertiesFolder);
projectModifier->setReplacePropertiesFolder( caseId, propertiesFolder );
}
}
}
}
loadProject(projectFileName, projectLoadAction, projectModifier.p());
loadProject( projectFileName, projectLoadAction, projectModifier.p() );
}
if (cvf::Option o = progOpt->option("case"))
if ( cvf::Option o = progOpt->option( "case" ) )
{
QStringList fileNames = RicImportGeneralDataFeature::fileNamesFromCaseNames(cvfqt::Utils::toQStringList(o.values()));
QStringList fileNames = RicImportGeneralDataFeature::fileNamesFromCaseNames(
cvfqt::Utils::toQStringList( o.values() ) );
RicImportGeneralDataFeature::OpenCaseResults results =
RicImportGeneralDataFeature::openEclipseFilesFromFileNames(fileNames, true);
RicImportGeneralDataFeature::openEclipseFilesFromFileNames( fileNames, true );
}
if (cvf::Option o = progOpt->option("commandFile"))
if ( cvf::Option o = progOpt->option( "commandFile" ) )
{
QString commandFile = cvfqt::Utils::toQString(o.safeValue(0));
if (!progOpt->hasOption("startdir"))
QString commandFile = cvfqt::Utils::toQString( o.safeValue( 0 ) );
if ( !progOpt->hasOption( "startdir" ) )
{
QFileInfo commandFileInfo(commandFile);
QString commandDir = commandFileInfo.absolutePath();
setStartDir(commandDir);
QFileInfo commandFileInfo( commandFile );
QString commandDir = commandFileInfo.absolutePath();
setStartDir( commandDir );
}
cvf::Option projectOption = progOpt->option("commandFileProject");
cvf::Option caseOption = progOpt->option("commandFileReplaceCases");
if (projectOption && caseOption)
cvf::Option projectOption = progOpt->option( "commandFileProject" );
cvf::Option caseOption = progOpt->option( "commandFileReplaceCases" );
if ( projectOption && caseOption )
{
projectFileName = cvfqt::Utils::toQString(projectOption.value(0));
projectFileName = cvfqt::Utils::toQString( projectOption.value( 0 ) );
std::vector<int> caseIds;
std::vector<QString> caseListFiles;
if (caseOption.valueCount() == 1)
if ( caseOption.valueCount() == 1 )
{
caseListFiles.push_back(cvfqt::Utils::toQString(caseOption.safeValue(0)));
caseListFiles.push_back( cvfqt::Utils::toQString( caseOption.safeValue( 0 ) ) );
}
else
{
size_t optionIdx = 0;
while (optionIdx < caseOption.valueCount())
while ( optionIdx < caseOption.valueCount() )
{
const int caseId = caseOption.safeValue(optionIdx++).toInt(-1);
QString caseListFile = cvfqt::Utils::toQString(caseOption.safeValue(optionIdx++));
const int caseId = caseOption.safeValue( optionIdx++ ).toInt( -1 );
QString caseListFile = cvfqt::Utils::toQString( caseOption.safeValue( optionIdx++ ) );
if (caseId != -1 && !caseListFile.isEmpty())
if ( caseId != -1 && !caseListFile.isEmpty() )
{
caseIds.push_back(caseId);
caseListFiles.push_back(caseListFile);
caseIds.push_back( caseId );
caseListFiles.push_back( caseListFile );
}
}
}
if (caseIds.empty() && !caseListFiles.empty())
if ( caseIds.empty() && !caseListFiles.empty() )
{
QString caseListFile = caseListFiles[0];
std::vector<QString> caseFiles = readFileListFromTextFile(caseListFile);
for (const QString& caseFile : caseFiles)
std::vector<QString> caseFiles = readFileListFromTextFile( caseListFile );
for ( const QString& caseFile : caseFiles )
{
RiaProjectModifier projectModifier;
projectModifier.setReplaceCaseFirstOccurrence(caseFile);
loadProject(projectFileName, RiaApplication::PLA_NONE, &projectModifier);
executeCommandFile(commandFile);
projectModifier.setReplaceCaseFirstOccurrence( caseFile );
loadProject( projectFileName, RiaApplication::PLA_NONE, &projectModifier );
executeCommandFile( commandFile );
}
}
else
{
CVF_ASSERT(caseIds.size() == caseListFiles.size());
CVF_ASSERT( caseIds.size() == caseListFiles.size() );
std::vector<std::vector<QString>> allCaseFiles;
size_t maxFiles = 0;
for (size_t i = 0; i < caseIds.size(); ++i)
for ( size_t i = 0; i < caseIds.size(); ++i )
{
std::vector<QString> caseFiles = readFileListFromTextFile(caseListFiles[i]);
allCaseFiles.push_back(caseFiles);
maxFiles = std::max(caseFiles.size(), maxFiles);
std::vector<QString> caseFiles = readFileListFromTextFile( caseListFiles[i] );
allCaseFiles.push_back( caseFiles );
maxFiles = std::max( caseFiles.size(), maxFiles );
}
for (size_t i = 0; i < caseIds.size(); ++i)
for ( size_t i = 0; i < caseIds.size(); ++i )
{
RiaProjectModifier projectModifier;
for (size_t j = 0; j < maxFiles; ++j)
for ( size_t j = 0; j < maxFiles; ++j )
{
if (allCaseFiles[i].size() > j)
if ( allCaseFiles[i].size() > j )
{
projectModifier.setReplaceCase(caseIds[i], allCaseFiles[i][j]);
projectModifier.setReplaceCase( caseIds[i], allCaseFiles[i][j] );
}
}
loadProject(projectFileName, RiaApplication::PLA_NONE, &projectModifier);
executeCommandFile(commandFile);
loadProject( projectFileName, RiaApplication::PLA_NONE, &projectModifier );
executeCommandFile( commandFile );
}
}
}
else
{
executeCommandFile(commandFile);
executeCommandFile( commandFile );
}
return EXIT_COMPLETED;
}
@@ -354,9 +356,9 @@ RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments(cvf::Pr
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::showFormattedTextInMessageBoxOrConsole(const QString& errMsg)
void RiaConsoleApplication::showFormattedTextInMessageBoxOrConsole( const QString& errMsg )
{
std::cout << errMsg.toStdString();
}
@@ -368,9 +370,9 @@ void RiaConsoleApplication::launchGrpcServer()
{
#ifdef ENABLE_GRPC
m_grpcServer->runInThread();
m_idleTimer = new QTimer(this);
connect(m_idleTimer, SIGNAL(timeout()), this, SLOT(runIdleProcessing()));
m_idleTimer->start(0);
m_idleTimer = new QTimer( this );
connect( m_idleTimer, SIGNAL( timeout() ), this, SLOT( runIdleProcessing() ) );
m_idleTimer->start( 0 );
#endif
}
@@ -387,17 +389,17 @@ RiaGrpcServer* RiaConsoleApplication::grpcServer() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::invokeProcessEvents(QEventLoop::ProcessEventsFlags flags /*= QEventLoop::AllEvents*/)
void RiaConsoleApplication::invokeProcessEvents( QEventLoop::ProcessEventsFlags flags /*= QEventLoop::AllEvents*/ )
{
processEvents(flags);
processEvents( flags );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::onProjectOpeningError(const QString& errMsg)
void RiaConsoleApplication::onProjectOpeningError( const QString& errMsg )
{
RiaLogging::error(errMsg);
RiaLogging::error( errMsg );
}
//--------------------------------------------------------------------------------------------------
@@ -416,14 +418,13 @@ void RiaConsoleApplication::onProjectClosed()
processEvents();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::runIdleProcessing()
{
#ifdef ENABLE_GRPC
if (RiaGrpcServer::receivedExitRequest())
if ( RiaGrpcServer::receivedExitRequest() )
{
m_grpcServer->quit();
QCoreApplication::quit();

View File

@@ -36,22 +36,22 @@ class RiaConsoleApplication : public QCoreApplication, public RiaApplication
public:
static RiaConsoleApplication* instance();
RiaConsoleApplication(int& argc, char** argv);
RiaConsoleApplication( int& argc, char** argv );
~RiaConsoleApplication() override;
// Public RiaApplication overrides
void initialize() override;
ApplicationStatus handleArguments(cvf::ProgramOptions* progOpt) override;
void showFormattedTextInMessageBoxOrConsole(const QString& errMsg) override;
void launchGrpcServer() override;
void initialize() override;
ApplicationStatus handleArguments( cvf::ProgramOptions* progOpt ) override;
void showFormattedTextInMessageBoxOrConsole( const QString& errMsg ) override;
void launchGrpcServer() override;
#ifdef ENABLE_GRPC
RiaGrpcServer* grpcServer() const override;
#endif
protected:
// Protected implementation specific overrides
void invokeProcessEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents) override;
void onProjectOpeningError(const QString& errMsg) override;
void invokeProcessEvents( QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents ) override;
void onProjectOpeningError( const QString& errMsg ) override;
void onProjectOpened();
void onProjectClosed();
@@ -63,4 +63,3 @@ private:
QPointer<QTimer> m_idleTimer;
#endif
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -21,28 +21,26 @@
#include "RifSummaryReaderInterface.h"
#include "RimSummaryCaseCollection.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaCurveSetDefinition::RiaCurveSetDefinition() :
m_ensemble(nullptr)
RiaCurveSetDefinition::RiaCurveSetDefinition()
: m_ensemble( nullptr )
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaCurveSetDefinition::RiaCurveSetDefinition(RimSummaryCaseCollection* ensemble, const RifEclipseSummaryAddress& summaryAddress) :
m_ensemble(ensemble),
m_summaryAddress(summaryAddress)
RiaCurveSetDefinition::RiaCurveSetDefinition( RimSummaryCaseCollection* ensemble,
const RifEclipseSummaryAddress& summaryAddress )
: m_ensemble( ensemble )
, m_summaryAddress( summaryAddress )
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryCaseCollection* RiaCurveSetDefinition::ensemble() const
{
@@ -50,7 +48,7 @@ RimSummaryCaseCollection* RiaCurveSetDefinition::ensemble() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const RifEclipseSummaryAddress& RiaCurveSetDefinition::summaryAddress() const
{
@@ -58,14 +56,14 @@ const RifEclipseSummaryAddress& RiaCurveSetDefinition::summaryAddress() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaCurveSetDefinition::operator<(const RiaCurveSetDefinition& other) const
bool RiaCurveSetDefinition::operator<( const RiaCurveSetDefinition& other ) const
{
if (m_ensemble != other.ensemble())
if ( m_ensemble != other.ensemble() )
{
return (m_ensemble < other.ensemble());
return ( m_ensemble < other.ensemble() );
}
return (m_summaryAddress < other.summaryAddress());
return ( m_summaryAddress < other.summaryAddress() );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -28,21 +28,20 @@
class RimSummaryCaseCollection;
//==================================================================================================
///
///
//==================================================================================================
class RiaCurveSetDefinition
{
public:
RiaCurveSetDefinition();
explicit RiaCurveSetDefinition(RimSummaryCaseCollection* emsemble,
const RifEclipseSummaryAddress& summaryAddress);
explicit RiaCurveSetDefinition( RimSummaryCaseCollection* emsemble, const RifEclipseSummaryAddress& summaryAddress );
RimSummaryCaseCollection* ensemble() const;
const RifEclipseSummaryAddress& summaryAddress() const;
bool operator < (const RiaCurveSetDefinition& other) const;
bool operator<( const RiaCurveSetDefinition& other ) const;
private:
RimSummaryCaseCollection * m_ensemble;
RifEclipseSummaryAddress m_summaryAddress;
RimSummaryCaseCollection* m_ensemble;
RifEclipseSummaryAddress m_summaryAddress;
};

View File

@@ -24,108 +24,108 @@
namespace caf
{
template<>
template <>
void caf::AppEnum<RiaDefines::ResultCatType>::setUp()
{
addItem(RiaDefines::DYNAMIC_NATIVE, "DYNAMIC_NATIVE", "Dynamic");
addItem(RiaDefines::STATIC_NATIVE, "STATIC_NATIVE", "Static");
addItem(RiaDefines::SOURSIMRL, "SOURSIMRL", "SourSimRL");
addItem(RiaDefines::GENERATED, "GENERATED", "Generated");
addItem(RiaDefines::INPUT_PROPERTY, "INPUT_PROPERTY", "Input Property");
addItem(RiaDefines::FORMATION_NAMES, "FORMATION_NAMES", "Formation Names");
addItem(RiaDefines::FLOW_DIAGNOSTICS, "FLOW_DIAGNOSTICS", "Flow Diagnostics");
addItem(RiaDefines::INJECTION_FLOODING, "INJECTION_FLOODING", "Injection Flooding");
setDefault(RiaDefines::DYNAMIC_NATIVE);
addItem( RiaDefines::DYNAMIC_NATIVE, "DYNAMIC_NATIVE", "Dynamic" );
addItem( RiaDefines::STATIC_NATIVE, "STATIC_NATIVE", "Static" );
addItem( RiaDefines::SOURSIMRL, "SOURSIMRL", "SourSimRL" );
addItem( RiaDefines::GENERATED, "GENERATED", "Generated" );
addItem( RiaDefines::INPUT_PROPERTY, "INPUT_PROPERTY", "Input Property" );
addItem( RiaDefines::FORMATION_NAMES, "FORMATION_NAMES", "Formation Names" );
addItem( RiaDefines::FLOW_DIAGNOSTICS, "FLOW_DIAGNOSTICS", "Flow Diagnostics" );
addItem( RiaDefines::INJECTION_FLOODING, "INJECTION_FLOODING", "Injection Flooding" );
setDefault( RiaDefines::DYNAMIC_NATIVE );
}
template<>
template <>
void caf::AppEnum<RiaDefines::DepthUnitType>::setUp()
{
addItem(RiaDefines::UNIT_METER, "UNIT_METER", "Meter");
addItem(RiaDefines::UNIT_FEET, "UNIT_FEET", "Feet");
addItem(RiaDefines::UNIT_NONE, "UNIT_NONE", "None");
addItem( RiaDefines::UNIT_METER, "UNIT_METER", "Meter" );
addItem( RiaDefines::UNIT_FEET, "UNIT_FEET", "Feet" );
addItem( RiaDefines::UNIT_NONE, "UNIT_NONE", "None" );
setDefault(RiaDefines::UNIT_METER);
setDefault( RiaDefines::UNIT_METER );
}
template<>
template <>
void caf::AppEnum<RiaDefines::PlotAxis>::setUp()
{
addItem(RiaDefines::PLOT_AXIS_LEFT, "PLOT_AXIS_LEFT", "Left");
addItem(RiaDefines::PLOT_AXIS_RIGHT, "PLOT_AXIS_RIGHT", "Right");
addItem( RiaDefines::PLOT_AXIS_LEFT, "PLOT_AXIS_LEFT", "Left" );
addItem( RiaDefines::PLOT_AXIS_RIGHT, "PLOT_AXIS_RIGHT", "Right" );
setDefault(RiaDefines::PLOT_AXIS_LEFT);
setDefault( RiaDefines::PLOT_AXIS_LEFT );
}
template<>
template <>
void caf::AppEnum<RiaDefines::WellPathComponentType>::setUp()
{
addItem(RiaDefines::WELL_PATH, "WELL_PATH", "Well Path");
addItem(RiaDefines::PERFORATION_INTERVAL, "PERFORATION_INTERVAL", "Perforation Interval");
addItem(RiaDefines::FISHBONES, "FISHBONES", "Fishbones");
addItem(RiaDefines::FRACTURE, "FRACTURE", "Fracture");
addItem(RiaDefines::ICD, "ICD", "ICD");
addItem(RiaDefines::AICD, "AICD", "AICD");
addItem(RiaDefines::ICV, "ICV", "ICV");
addItem(RiaDefines::CASING, "CASING", "Casing");
addItem(RiaDefines::LINER, "LINER", "Liner");
addItem(RiaDefines::PACKER, "PACKER", "Packer");
addItem(RiaDefines::UNDEFINED_COMPONENT, "UNDEFINED", "Undefined Component");
setDefault(RiaDefines::WELL_PATH);
addItem( RiaDefines::WELL_PATH, "WELL_PATH", "Well Path" );
addItem( RiaDefines::PERFORATION_INTERVAL, "PERFORATION_INTERVAL", "Perforation Interval" );
addItem( RiaDefines::FISHBONES, "FISHBONES", "Fishbones" );
addItem( RiaDefines::FRACTURE, "FRACTURE", "Fracture" );
addItem( RiaDefines::ICD, "ICD", "ICD" );
addItem( RiaDefines::AICD, "AICD", "AICD" );
addItem( RiaDefines::ICV, "ICV", "ICV" );
addItem( RiaDefines::CASING, "CASING", "Casing" );
addItem( RiaDefines::LINER, "LINER", "Liner" );
addItem( RiaDefines::PACKER, "PACKER", "Packer" );
addItem( RiaDefines::UNDEFINED_COMPONENT, "UNDEFINED", "Undefined Component" );
setDefault( RiaDefines::WELL_PATH );
}
template<>
template <>
void caf::AppEnum<RiaDefines::MeshModeType>::setUp()
{
addItem(RiaDefines::FULL_MESH, "FULL_MESH", "All");
addItem(RiaDefines::FAULTS_MESH, "FAULTS_MESH", "Faults only");
addItem(RiaDefines::NO_MESH, "NO_MESH", "None");
setDefault(RiaDefines::FULL_MESH);
addItem( RiaDefines::FULL_MESH, "FULL_MESH", "All" );
addItem( RiaDefines::FAULTS_MESH, "FAULTS_MESH", "Faults only" );
addItem( RiaDefines::NO_MESH, "NO_MESH", "None" );
setDefault( RiaDefines::FULL_MESH );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaDefines::isPerCellFaceResult(const QString& resultName)
bool RiaDefines::isPerCellFaceResult( const QString& resultName )
{
if (resultName.compare(RiaDefines::combinedTransmissibilityResultName(), Qt::CaseInsensitive) == 0)
if ( resultName.compare( RiaDefines::combinedTransmissibilityResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedMultResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedMultResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::ternarySaturationResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::ternarySaturationResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedRiTranResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedRiTranResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedRiMultResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedRiMultResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedRiAreaNormTranResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedRiAreaNormTranResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedWaterFluxResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedWaterFluxResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedOilFluxResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedOilFluxResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.compare(RiaDefines::combinedGasFluxResultName(), Qt::CaseInsensitive) == 0)
else if ( resultName.compare( RiaDefines::combinedGasFluxResultName(), Qt::CaseInsensitive ) == 0 )
{
return true;
}
else if (resultName.endsWith("IJK"))
else if ( resultName.endsWith( "IJK" ) )
{
return true;
}
@@ -136,9 +136,9 @@ bool RiaDefines::isPerCellFaceResult(const QString& resultName)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaDefines::isNativeCategoryResult(const QString& resultName)
bool RiaDefines::isNativeCategoryResult( const QString& resultName )
{
return resultName.endsWith("NUM");
return resultName.endsWith( "NUM" );
}
//--------------------------------------------------------------------------------------------------
@@ -500,29 +500,29 @@ double RiaDefines::maximumDefaultValuePlot()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaDefines::ImportFileType RiaDefines::obtainFileTypeFromFileName(const QString& fileName)
RiaDefines::ImportFileType RiaDefines::obtainFileTypeFromFileName( const QString& fileName )
{
if (fileName.endsWith("EGRID", Qt::CaseInsensitive))
if ( fileName.endsWith( "EGRID", Qt::CaseInsensitive ) )
{
return ECLIPSE_EGRID_FILE;
}
else if (fileName.endsWith("GRID", Qt::CaseInsensitive))
else if ( fileName.endsWith( "GRID", Qt::CaseInsensitive ) )
{
return ECLIPSE_GRID_FILE;
}
else if (fileName.endsWith("GRDECL", Qt::CaseInsensitive))
else if ( fileName.endsWith( "GRDECL", Qt::CaseInsensitive ) )
{
return ECLIPSE_INPUT_FILE;
}
else if (fileName.endsWith("SMSPEC", Qt::CaseInsensitive))
else if ( fileName.endsWith( "SMSPEC", Qt::CaseInsensitive ) )
{
return ECLIPSE_SUMMARY_FILE;
}
else if (fileName.endsWith("ODB", Qt::CaseInsensitive))
else if ( fileName.endsWith( "ODB", Qt::CaseInsensitive ) )
{
return GEOMECH_ODB_FILE;
}
else if (fileName.endsWith(".rsp", Qt::CaseInsensitive) || fileName.endsWith(".rip", Qt::CaseInsensitive))
else if ( fileName.endsWith( ".rsp", Qt::CaseInsensitive ) || fileName.endsWith( ".rip", Qt::CaseInsensitive ) )
{
return RESINSIGHT_PROJECT_FILE;
}
@@ -532,29 +532,29 @@ RiaDefines::ImportFileType RiaDefines::obtainFileTypeFromFileName(const QString&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaDefines::defaultDirectoryLabel(RiaDefines::ImportFileType fileType)
QString RiaDefines::defaultDirectoryLabel( RiaDefines::ImportFileType fileType )
{
QString defaultDirLabel;
if (fileType == ANY_ECLIPSE_FILE)
if ( fileType == ANY_ECLIPSE_FILE )
{
defaultDirLabel = "GENERAL_DATA";
}
else if (fileType & ECLIPSE_RESULT_GRID)
else if ( fileType & ECLIPSE_RESULT_GRID )
{
defaultDirLabel = "BINARY_GRID";
}
else if (fileType & ECLIPSE_INPUT_FILE)
else if ( fileType & ECLIPSE_INPUT_FILE )
{
defaultDirLabel = "INPUT_FILES";
}
else if (fileType & ECLIPSE_SUMMARY_FILE)
else if ( fileType & ECLIPSE_SUMMARY_FILE )
{
// TODO: Summary files used "INPUT_FILES" as last used directory.
// Check if this is correct.
defaultDirLabel = "INPUT_FILES";
}
else if (fileType & GEOMECH_ODB_FILE)
else if ( fileType & GEOMECH_ODB_FILE )
{
defaultDirLabel = "GEOMECH_MODEL";
}

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,167 +25,166 @@
namespace RiaDefines
{
enum ResultCatType
{
DYNAMIC_NATIVE,
STATIC_NATIVE,
SOURSIMRL,
GENERATED,
INPUT_PROPERTY,
FORMATION_NAMES,
FLOW_DIAGNOSTICS,
INJECTION_FLOODING,
REMOVED,
UNDEFINED = 999
};
// WARNING: DO NOT CHANGE THE ORDER WITHOUT KNOWING WHAT YOU ARE DOING!
// You may well change the behaviour of property filters.
enum WellPathComponentType {
// Production Tube
WELL_PATH,
// Well path flow completions
PERFORATION_INTERVAL,
FISHBONES,
FRACTURE,
ICD,
AICD,
ICV,
// Well path construction features
CASING,
LINER,
PACKER,
UNDEFINED_COMPONENT
};
enum MeshModeType
{
FULL_MESH,
FAULTS_MESH,
NO_MESH
};
bool isPerCellFaceResult(const QString& resultName);
bool isNativeCategoryResult(const QString& resultName);
QString undefinedResultName();
QString undefinedGridFaultName();
QString undefinedGridFaultWithInactiveName();
QString combinedTransmissibilityResultName();
QString combinedWaterFluxResultName();
QString combinedOilFluxResultName();
QString combinedGasFluxResultName();
QString ternarySaturationResultName();
QString combinedMultResultName();
QString eqlnumResultName();
QString riTranXResultName();
QString riTranYResultName();
QString riTranZResultName();
QString combinedRiTranResultName();
QString riMultXResultName();
QString riMultYResultName();
QString riMultZResultName();
QString combinedRiMultResultName();
QString riAreaNormTranXResultName();
QString riAreaNormTranYResultName();
QString riAreaNormTranZResultName();
QString combinedRiAreaNormTranResultName();
QString riCellVolumeResultName();
QString riOilVolumeResultName();
QString mobilePoreVolumeName();
QString completionTypeResultName();
// Mock model text identifiers
QString mockModelBasic();
QString mockModelBasicWithResults();
QString mockModelLargeWithResults();
QString mockModelCustomized();
QString mockModelBasicInputCase();
QString activeFormationNamesResultName();
// Well path derived results
QString wellPathAzimuthResultName();
QString wellPathInclinationResultName();
QString wellPathPPResultName();
QString wellPathSHResultName();
QString wellPathOBGResultName();
QString wellPathFGResultName();
QString wellPathSFGResultName();
// List of well path derived results
std::vector<QString> wellPathAngleResultNames();
std::vector<QString> wellPathStabilityResultNames();
//Units and conversions
enum DepthUnitType
{
UNIT_METER,
UNIT_FEET,
UNIT_NONE
};
// Defines relate to plotting
enum PlotAxis
{
PLOT_AXIS_LEFT,
PLOT_AXIS_RIGHT,
PLOT_AXIS_BOTTOM
};
double minimumDefaultValuePlot();
double minimumDefaultLogValuePlot();
double maximumDefaultValuePlot();
enum PhaseType {
OIL_PHASE,
GAS_PHASE,
WATER_PHASE
};
enum ImportFileType
{
NOT_A_VALID_IMPORT_FILE = 0x00,
ECLIPSE_GRID_FILE = 0x01,
ECLIPSE_EGRID_FILE = 0x02,
ECLIPSE_INPUT_FILE = 0x04,
ECLIPSE_SUMMARY_FILE = 0x08,
GEOMECH_ODB_FILE = 0x10,
RESINSIGHT_PROJECT_FILE = 0x20,
ECLIPSE_RESULT_GRID = ECLIPSE_GRID_FILE | ECLIPSE_EGRID_FILE,
ANY_ECLIPSE_FILE = ECLIPSE_RESULT_GRID | ECLIPSE_INPUT_FILE | ECLIPSE_SUMMARY_FILE,
ANY_IMPORT_FILE = 0xFF
};
ImportFileType obtainFileTypeFromFileName(const QString& fileName);
QString defaultDirectoryLabel(ImportFileType fileTypes);
enum CaseType
{
ECLIPSE_RESULT_CASE = 1,
ECLIPSE_INPUT_CASE = 2,
ECLIPSE_STAT_CASE = 3,
ECLIPSE_SOURCE_CASE = 4,
GEOMECH_ODB_CASE = 5
};
enum FontSettingType
{
SCENE_FONT,
ANNOTATION_FONT,
WELL_LABEL_FONT,
PLOT_FONT
};
enum ResultCatType
{
DYNAMIC_NATIVE,
STATIC_NATIVE,
SOURSIMRL,
GENERATED,
INPUT_PROPERTY,
FORMATION_NAMES,
FLOW_DIAGNOSTICS,
INJECTION_FLOODING,
REMOVED,
UNDEFINED = 999
};
// WARNING: DO NOT CHANGE THE ORDER WITHOUT KNOWING WHAT YOU ARE DOING!
// You may well change the behaviour of property filters.
enum WellPathComponentType
{
// Production Tube
WELL_PATH,
// Well path flow completions
PERFORATION_INTERVAL,
FISHBONES,
FRACTURE,
ICD,
AICD,
ICV,
// Well path construction features
CASING,
LINER,
PACKER,
UNDEFINED_COMPONENT
};
enum MeshModeType
{
FULL_MESH,
FAULTS_MESH,
NO_MESH
};
bool isPerCellFaceResult( const QString& resultName );
bool isNativeCategoryResult( const QString& resultName );
QString undefinedResultName();
QString undefinedGridFaultName();
QString undefinedGridFaultWithInactiveName();
QString combinedTransmissibilityResultName();
QString combinedWaterFluxResultName();
QString combinedOilFluxResultName();
QString combinedGasFluxResultName();
QString ternarySaturationResultName();
QString combinedMultResultName();
QString eqlnumResultName();
QString riTranXResultName();
QString riTranYResultName();
QString riTranZResultName();
QString combinedRiTranResultName();
QString riMultXResultName();
QString riMultYResultName();
QString riMultZResultName();
QString combinedRiMultResultName();
QString riAreaNormTranXResultName();
QString riAreaNormTranYResultName();
QString riAreaNormTranZResultName();
QString combinedRiAreaNormTranResultName();
QString riCellVolumeResultName();
QString riOilVolumeResultName();
QString mobilePoreVolumeName();
QString completionTypeResultName();
// Mock model text identifiers
QString mockModelBasic();
QString mockModelBasicWithResults();
QString mockModelLargeWithResults();
QString mockModelCustomized();
QString mockModelBasicInputCase();
QString activeFormationNamesResultName();
// Well path derived results
QString wellPathAzimuthResultName();
QString wellPathInclinationResultName();
QString wellPathPPResultName();
QString wellPathSHResultName();
QString wellPathOBGResultName();
QString wellPathFGResultName();
QString wellPathSFGResultName();
// List of well path derived results
std::vector<QString> wellPathAngleResultNames();
std::vector<QString> wellPathStabilityResultNames();
// Units and conversions
enum DepthUnitType
{
UNIT_METER,
UNIT_FEET,
UNIT_NONE
};
// Defines relate to plotting
enum PlotAxis
{
PLOT_AXIS_LEFT,
PLOT_AXIS_RIGHT,
PLOT_AXIS_BOTTOM
};
double minimumDefaultValuePlot();
double minimumDefaultLogValuePlot();
double maximumDefaultValuePlot();
enum PhaseType
{
OIL_PHASE,
GAS_PHASE,
WATER_PHASE
};
enum ImportFileType
{
NOT_A_VALID_IMPORT_FILE = 0x00,
ECLIPSE_GRID_FILE = 0x01,
ECLIPSE_EGRID_FILE = 0x02,
ECLIPSE_INPUT_FILE = 0x04,
ECLIPSE_SUMMARY_FILE = 0x08,
GEOMECH_ODB_FILE = 0x10,
RESINSIGHT_PROJECT_FILE = 0x20,
ECLIPSE_RESULT_GRID = ECLIPSE_GRID_FILE | ECLIPSE_EGRID_FILE,
ANY_ECLIPSE_FILE = ECLIPSE_RESULT_GRID | ECLIPSE_INPUT_FILE | ECLIPSE_SUMMARY_FILE,
ANY_IMPORT_FILE = 0xFF
};
ImportFileType obtainFileTypeFromFileName( const QString& fileName );
QString defaultDirectoryLabel( ImportFileType fileTypes );
enum CaseType
{
ECLIPSE_RESULT_CASE = 1,
ECLIPSE_INPUT_CASE = 2,
ECLIPSE_STAT_CASE = 3,
ECLIPSE_SOURCE_CASE = 4,
GEOMECH_ODB_CASE = 5
};
enum FontSettingType
{
SCENE_FONT,
ANNOTATION_FONT,
WELL_LABEL_FONT,
PLOT_FONT
};
}; // namespace RiaDefines

View File

@@ -22,17 +22,17 @@
namespace caf
{
template<>
template <>
void caf::AppEnum<RiaEclipseFileNameTools::EclipseFileType>::setUp()
{
addItem(RiaEclipseFileNameTools::ECLIPSE_DATA, "DATA", "Data Deck");
addItem(RiaEclipseFileNameTools::ECLIPSE_GRID, "GRID", "Grid");
addItem(RiaEclipseFileNameTools::ECLIPSE_EGRID, "EGRID", "Grid");
addItem(RiaEclipseFileNameTools::ECLIPSE_UNRST, "UNRST", "Unified Restart");
addItem(RiaEclipseFileNameTools::ECLIPSE_SMSPEC, "SMSPEC", "Summary Specification");
addItem(RiaEclipseFileNameTools::ECLIPSE_UNSMRY, "UNSMR", "Summary Vectors");
addItem( RiaEclipseFileNameTools::ECLIPSE_DATA, "DATA", "Data Deck" );
addItem( RiaEclipseFileNameTools::ECLIPSE_GRID, "GRID", "Grid" );
addItem( RiaEclipseFileNameTools::ECLIPSE_EGRID, "EGRID", "Grid" );
addItem( RiaEclipseFileNameTools::ECLIPSE_UNRST, "UNRST", "Unified Restart" );
addItem( RiaEclipseFileNameTools::ECLIPSE_SMSPEC, "SMSPEC", "Summary Specification" );
addItem( RiaEclipseFileNameTools::ECLIPSE_UNSMRY, "UNSMR", "Summary Vectors" );
addItem(RiaEclipseFileNameTools::RESINSIGHT_PROJECT, "rsp", "ResInsight Project");
addItem( RiaEclipseFileNameTools::RESINSIGHT_PROJECT, "rsp", "ResInsight Project" );
}
} // End namespace caf
@@ -40,9 +40,9 @@ void caf::AppEnum<RiaEclipseFileNameTools::EclipseFileType>::setUp()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaEclipseFileNameTools::RiaEclipseFileNameTools(const QString& inputFilePath)
RiaEclipseFileNameTools::RiaEclipseFileNameTools( const QString& inputFilePath )
{
QFileInfo fi(inputFilePath);
QFileInfo fi( inputFilePath );
m_baseName = fi.absolutePath() + "/" + fi.baseName();
}
@@ -52,7 +52,7 @@ RiaEclipseFileNameTools::RiaEclipseFileNameTools(const QString& inputFilePath)
//--------------------------------------------------------------------------------------------------
QString RiaEclipseFileNameTools::findRelatedSummarySpecFile()
{
return relatedFilePath(ECLIPSE_SMSPEC);
return relatedFilePath( ECLIPSE_SMSPEC );
}
//--------------------------------------------------------------------------------------------------
@@ -60,13 +60,13 @@ QString RiaEclipseFileNameTools::findRelatedSummarySpecFile()
//--------------------------------------------------------------------------------------------------
QString RiaEclipseFileNameTools::findRelatedGridFile()
{
QString candidate = relatedFilePath(ECLIPSE_EGRID);
if (!candidate.isEmpty())
QString candidate = relatedFilePath( ECLIPSE_EGRID );
if ( !candidate.isEmpty() )
{
return candidate;
}
return relatedFilePath(ECLIPSE_GRID);
return relatedFilePath( ECLIPSE_GRID );
}
//--------------------------------------------------------------------------------------------------
@@ -74,44 +74,44 @@ QString RiaEclipseFileNameTools::findRelatedGridFile()
//--------------------------------------------------------------------------------------------------
QString RiaEclipseFileNameTools::findRelatedDataFile()
{
return relatedFilePath(ECLIPSE_DATA);
return relatedFilePath( ECLIPSE_DATA );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaEclipseFileNameTools::isProjectFile(const QString& fileName)
bool RiaEclipseFileNameTools::isProjectFile( const QString& fileName )
{
return hasMatchingSuffix(fileName, RESINSIGHT_PROJECT);
return hasMatchingSuffix( fileName, RESINSIGHT_PROJECT );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaEclipseFileNameTools::isGridFile(const QString& fileName)
bool RiaEclipseFileNameTools::isGridFile( const QString& fileName )
{
if (hasMatchingSuffix(fileName, ECLIPSE_EGRID))
if ( hasMatchingSuffix( fileName, ECLIPSE_EGRID ) )
{
return true;
}
return hasMatchingSuffix(fileName, ECLIPSE_GRID);
return hasMatchingSuffix( fileName, ECLIPSE_GRID );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaEclipseFileNameTools::isSummarySpecFile(const QString& fileName)
bool RiaEclipseFileNameTools::isSummarySpecFile( const QString& fileName )
{
return hasMatchingSuffix(fileName, ECLIPSE_SMSPEC);
return hasMatchingSuffix( fileName, ECLIPSE_SMSPEC );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaEclipseFileNameTools::findBaseName(const QString& inputFilePath) const
QString RiaEclipseFileNameTools::findBaseName( const QString& inputFilePath ) const
{
QFileInfo fi(inputFilePath);
QFileInfo fi( inputFilePath );
return fi.baseName();
}
@@ -119,13 +119,13 @@ QString RiaEclipseFileNameTools::findBaseName(const QString& inputFilePath) cons
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaEclipseFileNameTools::relatedFilePath(EclipseFileType fileType) const
QString RiaEclipseFileNameTools::relatedFilePath( EclipseFileType fileType ) const
{
const QString extension = caf::AppEnum<EclipseFileType>::text(fileType);
const QString extension = caf::AppEnum<EclipseFileType>::text( fileType );
const QString completeFilePath = m_baseName + "." + extension;
QFileInfo fi(completeFilePath);
if (fi.exists())
QFileInfo fi( completeFilePath );
if ( fi.exists() )
{
return fi.absoluteFilePath();
}
@@ -136,13 +136,13 @@ QString RiaEclipseFileNameTools::relatedFilePath(EclipseFileType fileType) const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaEclipseFileNameTools::hasMatchingSuffix(const QString& fileName, EclipseFileType fileType)
bool RiaEclipseFileNameTools::hasMatchingSuffix( const QString& fileName, EclipseFileType fileType )
{
QFileInfo fi(fileName);
QFileInfo fi( fileName );
QString suffix = fi.completeSuffix();
if (suffix.compare(caf::AppEnum<EclipseFileType>::text(fileType), Qt::CaseInsensitive) == 0)
if ( suffix.compare( caf::AppEnum<EclipseFileType>::text( fileType ), Qt::CaseInsensitive ) == 0 )
{
return true;
}

View File

@@ -43,21 +43,21 @@ public:
};
public:
explicit RiaEclipseFileNameTools(const QString& fileName);
explicit RiaEclipseFileNameTools( const QString& fileName );
QString findRelatedGridFile();
QString findRelatedSummarySpecFile();
QString findRelatedDataFile();
static bool isProjectFile(const QString& fileName);
static bool isGridFile(const QString& fileName);
static bool isSummarySpecFile(const QString& fileName);
static bool isProjectFile( const QString& fileName );
static bool isGridFile( const QString& fileName );
static bool isSummarySpecFile( const QString& fileName );
private:
QString findBaseName(const QString& inputFilePath) const;
QString relatedFilePath(EclipseFileType fileType) const;
QString findBaseName( const QString& inputFilePath ) const;
QString relatedFilePath( EclipseFileType fileType ) const;
static bool hasMatchingSuffix(const QString& fileName, EclipseFileType fileType);
static bool hasMatchingSuffix( const QString& fileName, EclipseFileType fileType );
private:
QString m_baseName;

View File

@@ -33,7 +33,7 @@ RiaFeatureCommandContext::~RiaFeatureCommandContext() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaFeatureCommandContext::setObject(QObject* object)
void RiaFeatureCommandContext::setObject( QObject* object )
{
m_pointerToQObject = object;
}
@@ -51,9 +51,9 @@ QObject* RiaFeatureCommandContext::object() const
//--------------------------------------------------------------------------------------------------
QString RiaFeatureCommandContext::titleString() const
{
if (m_pointerToQObject)
if ( m_pointerToQObject )
{
QVariant variant = m_pointerToQObject->property(titleStringIdentifier().data());
QVariant variant = m_pointerToQObject->property( titleStringIdentifier().data() );
return variant.toString();
}
@@ -66,9 +66,9 @@ QString RiaFeatureCommandContext::titleString() const
//--------------------------------------------------------------------------------------------------
QString RiaFeatureCommandContext::contentString() const
{
if (m_pointerToQObject)
if ( m_pointerToQObject )
{
QVariant variant = m_pointerToQObject->property(contentStringIdentifier().data());
QVariant variant = m_pointerToQObject->property( contentStringIdentifier().data() );
return variant.toString();
}
@@ -104,9 +104,9 @@ RiaFeatureCommandContext* RiaFeatureCommandContext::instance()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaFeatureCommandContextHelper::RiaFeatureCommandContextHelper(QObject* externalObject)
RiaFeatureCommandContextHelper::RiaFeatureCommandContextHelper( QObject* externalObject )
{
RiaFeatureCommandContext::instance()->setObject(externalObject);
RiaFeatureCommandContext::instance()->setObject( externalObject );
}
//--------------------------------------------------------------------------------------------------
@@ -114,20 +114,20 @@ RiaFeatureCommandContextHelper::RiaFeatureCommandContextHelper(QObject* external
//--------------------------------------------------------------------------------------------------
RiaFeatureCommandContextHelper::~RiaFeatureCommandContextHelper()
{
RiaFeatureCommandContext::instance()->setObject(nullptr);
RiaFeatureCommandContext::instance()->setObject( nullptr );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaFeatureCommandContextTextHelper::RiaFeatureCommandContextTextHelper(const QString& title, const QString& text)
RiaFeatureCommandContextTextHelper::RiaFeatureCommandContextTextHelper( const QString& title, const QString& text )
{
m_object = new QObject;
m_object->setProperty(RiaFeatureCommandContext::titleStringIdentifier().data(), title);
m_object->setProperty(RiaFeatureCommandContext::contentStringIdentifier().data(), text);
m_object->setProperty( RiaFeatureCommandContext::titleStringIdentifier().data(), title );
m_object->setProperty( RiaFeatureCommandContext::contentStringIdentifier().data(), text );
RiaFeatureCommandContext::instance()->setObject(m_object);
RiaFeatureCommandContext::instance()->setObject( m_object );
}
//--------------------------------------------------------------------------------------------------
@@ -135,7 +135,7 @@ RiaFeatureCommandContextTextHelper::RiaFeatureCommandContextTextHelper(const QSt
//--------------------------------------------------------------------------------------------------
RiaFeatureCommandContextTextHelper::~RiaFeatureCommandContextTextHelper()
{
if (m_object)
if ( m_object )
{
m_object->deleteLater();
m_object = nullptr;

View File

@@ -32,7 +32,7 @@ public:
static RiaFeatureCommandContext* instance();
QObject* object() const;
void setObject(QObject* object);
void setObject( QObject* object );
QString titleString() const;
QString contentString() const;
@@ -54,7 +54,7 @@ private:
class RiaFeatureCommandContextHelper
{
public:
RiaFeatureCommandContextHelper(QObject* externalObject);
RiaFeatureCommandContextHelper( QObject* externalObject );
~RiaFeatureCommandContextHelper();
};
@@ -64,7 +64,7 @@ public:
class RiaFeatureCommandContextTextHelper
{
public:
RiaFeatureCommandContextTextHelper(const QString& title, const QString& text);
RiaFeatureCommandContextTextHelper( const QString& title, const QString& text );
~RiaFeatureCommandContextTextHelper();
private:

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,27 +23,27 @@
namespace caf
{
template<>
template <>
void RiaFontCache::FontSizeType::setUp()
{
addItem(RiaFontCache::FONT_SIZE_8, "8", "8");
addItem(RiaFontCache::FONT_SIZE_10, "10", "10");
addItem(RiaFontCache::FONT_SIZE_12, "12", "12");
addItem(RiaFontCache::FONT_SIZE_14, "14", "14");
addItem(RiaFontCache::FONT_SIZE_16, "16", "16");
addItem(RiaFontCache::FONT_SIZE_24, "24", "24");
addItem(RiaFontCache::FONT_SIZE_32, "32", "32");
addItem( RiaFontCache::FONT_SIZE_8, "8", "8" );
addItem( RiaFontCache::FONT_SIZE_10, "10", "10" );
addItem( RiaFontCache::FONT_SIZE_12, "12", "12" );
addItem( RiaFontCache::FONT_SIZE_14, "14", "14" );
addItem( RiaFontCache::FONT_SIZE_16, "16", "16" );
addItem( RiaFontCache::FONT_SIZE_24, "24", "24" );
addItem( RiaFontCache::FONT_SIZE_32, "32", "32" );
setDefault(RiaFontCache::FONT_SIZE_8);
}
setDefault( RiaFontCache::FONT_SIZE_8 );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::FixedAtlasFont::FontSize mapToAtlasFontSize(RiaFontCache::FontSize fontSize)
caf::FixedAtlasFont::FontSize mapToAtlasFontSize( RiaFontCache::FontSize fontSize )
{
switch (fontSize)
switch ( fontSize )
{
case RiaFontCache::FONT_SIZE_8:
return caf::FixedAtlasFont::POINT_SIZE_8;
@@ -72,12 +72,12 @@ std::map<RiaFontCache::FontSize, cvf::ref<caf::FixedAtlasFont>> RiaFontCache::ms
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::ref<caf::FixedAtlasFont> RiaFontCache::getFont(FontSize size)
cvf::ref<caf::FixedAtlasFont> RiaFontCache::getFont( FontSize size )
{
if (ms_fonts.count(size) == 0)
if ( ms_fonts.count( size ) == 0 )
{
auto newFont = new caf::FixedAtlasFont(mapToAtlasFontSize(size));
ms_fonts.insert(std::make_pair(size, newFont));
auto newFont = new caf::FixedAtlasFont( mapToAtlasFontSize( size ) );
ms_fonts.insert( std::make_pair( size, newFont ) );
}
return ms_fonts[size];
}
@@ -85,9 +85,9 @@ cvf::ref<caf::FixedAtlasFont> RiaFontCache::getFont(FontSize size)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int RiaFontCache::pointSizeFromFontSizeEnum(FontSize fontSize)
int RiaFontCache::pointSizeFromFontSizeEnum( FontSize fontSize )
{
switch (fontSize)
switch ( fontSize )
{
case RiaFontCache::FONT_SIZE_8:
return 8;
@@ -111,17 +111,17 @@ int RiaFontCache::pointSizeFromFontSizeEnum(FontSize fontSize)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaFontCache::FontSize RiaFontCache::fontSizeEnumFromPointSize(int pointSize)
RiaFontCache::FontSize RiaFontCache::fontSizeEnumFromPointSize( int pointSize )
{
std::vector<FontSize> allValues =
{ FONT_SIZE_8, FONT_SIZE_10, FONT_SIZE_12, FONT_SIZE_14, FONT_SIZE_16, FONT_SIZE_24, FONT_SIZE_32 };
{FONT_SIZE_8, FONT_SIZE_10, FONT_SIZE_12, FONT_SIZE_14, FONT_SIZE_16, FONT_SIZE_24, FONT_SIZE_32};
FontSize closestEnumValue = FONT_SIZE_8;
int closestDiff = std::numeric_limits<int>::max();
for (FontSize enumValue : allValues)
for ( FontSize enumValue : allValues )
{
int diff = std::abs(pointSizeFromFontSizeEnum(enumValue) - pointSize);
if (diff < closestDiff)
int diff = std::abs( pointSizeFromFontSizeEnum( enumValue ) - pointSize );
if ( diff < closestDiff )
{
closestEnumValue = enumValue;
closestDiff = diff;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,13 +26,14 @@
namespace caf
{
template<typename T> class AppEnum;
template <typename T>
class AppEnum;
}
class RimSummaryCaseCollection;
//==================================================================================================
///
///
//==================================================================================================
class RiaFontCache
{
@@ -51,9 +52,9 @@ public:
typedef caf::AppEnum<FontSize> FontSizeType;
static cvf::ref<caf::FixedAtlasFont> getFont(FontSize fontSize);
static int pointSizeFromFontSizeEnum(FontSize fontSize);
static FontSize fontSizeEnumFromPointSize(int pointSize);
static cvf::ref<caf::FixedAtlasFont> getFont( FontSize fontSize );
static int pointSizeFromFontSizeEnum( FontSize fontSize );
static FontSize fontSizeEnumFromPointSize( int pointSize );
private:
static std::map<FontSize, cvf::ref<caf::FixedAtlasFont>> ms_fonts;

View File

@@ -29,9 +29,9 @@ QString RiaDefines::conductivityResultName()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaDefines::unitStringConductivity(RiaEclipseUnitTools::UnitSystem unitSystem)
QString RiaDefines::unitStringConductivity( RiaEclipseUnitTools::UnitSystem unitSystem )
{
switch (unitSystem)
switch ( unitSystem )
{
case RiaEclipseUnitTools::UNITS_METRIC:
return "md-m";
@@ -45,9 +45,9 @@ QString RiaDefines::unitStringConductivity(RiaEclipseUnitTools::UnitSystem unitS
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaDefines::nonDarcyFlowAlpha(RiaEclipseUnitTools::UnitSystem unitSystem)
double RiaDefines::nonDarcyFlowAlpha( RiaEclipseUnitTools::UnitSystem unitSystem )
{
switch (unitSystem)
switch ( unitSystem )
{
case RiaEclipseUnitTools::UNITS_METRIC:
return 2.24460e-10;

View File

@@ -25,7 +25,7 @@
namespace RiaDefines
{
QString conductivityResultName();
QString unitStringConductivity(RiaEclipseUnitTools::UnitSystem unitSystem);
QString unitStringConductivity( RiaEclipseUnitTools::UnitSystem unitSystem );
double nonDarcyFlowAlpha(RiaEclipseUnitTools::UnitSystem unitSystem);
double nonDarcyFlowAlpha( RiaEclipseUnitTools::UnitSystem unitSystem );
}; // namespace RiaDefines

File diff suppressed because it is too large Load Diff

View File

@@ -21,8 +21,8 @@
#include "RiaApplication.h"
#include "RiaDefines.h"
#include "cafPdmObject.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
#include "cvfObject.h"
@@ -68,7 +68,7 @@ class RiaArgumentParser;
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaGuiApplication : public QApplication, public RiaApplication
@@ -88,90 +88,92 @@ public:
static bool isRunning();
static RiaGuiApplication* instance();
RiaGuiApplication(int& argc, char** argv);
RiaGuiApplication( int& argc, char** argv );
~RiaGuiApplication() override;
bool saveProject();
bool saveProjectPromptForFileName();
bool askUserToSaveModifiedProject();
bool saveProjectAs(const QString& fileName);
void runMultiCaseSnapshots(const QString& templateProjectFileName, std::vector<QString> gridFileNames, const QString& snapshotFolderName);
bool useShaders() const;
bool showPerformanceInfo() const;
bool saveProject();
bool saveProjectPromptForFileName();
bool askUserToSaveModifiedProject();
bool saveProjectAs( const QString& fileName );
RINavigationPolicy navigationPolicy() const;
void runMultiCaseSnapshots( const QString& templateProjectFileName,
std::vector<QString> gridFileNames,
const QString& snapshotFolderName );
bool useShaders() const;
bool showPerformanceInfo() const;
RiuMainWindow* getOrCreateAndShowMainWindow();
RiuMainWindow* mainWindow();
RimViewWindow* activePlotWindow() const;
RINavigationPolicy navigationPolicy() const;
RiuPlotMainWindow* getOrCreateMainPlotWindow();
RiuPlotMainWindow* getOrCreateAndShowMainPlotWindow();
RiuPlotMainWindow* mainPlotWindow();
RiuMainWindowBase* mainWindowByID(int mainWindowID);
RiuMainWindow* getOrCreateAndShowMainWindow();
RiuMainWindow* mainWindow();
RimViewWindow* activePlotWindow() const;
RiuPlotMainWindow* getOrCreateMainPlotWindow();
RiuPlotMainWindow* getOrCreateAndShowMainPlotWindow();
RiuPlotMainWindow* mainPlotWindow();
RiuMainWindowBase* mainWindowByID( int mainWindowID );
static RimViewWindow* activeViewWindow();
bool isMain3dWindowVisible() const;
bool isMainPlotWindowVisible() const;
bool isMain3dWindowVisible() const;
bool isMainPlotWindowVisible() const;
void closeMainWindowIfOpenButHidden();
void closeMainPlotWindowIfOpenButHidden();
void closeMainWindowIfOpenButHidden();
void closeMainPlotWindowIfOpenButHidden();
std::vector<QAction*> recentFileActions() const;
static void clearAllSelections();
void applyGuiPreferences(const RiaPreferences* oldPreferences = nullptr);
void updateGrpcServer();
static void clearAllSelections();
void applyGuiPreferences( const RiaPreferences* oldPreferences = nullptr );
void updateGrpcServer();
// Public RiaApplication overrides
void initialize() override;
ApplicationStatus handleArguments(cvf::ProgramOptions* progOpt) override;
int launchUnitTestsWithConsole() override;
void addToRecentFiles(const QString& fileName) override;
void showFormattedTextInMessageBoxOrConsole(const QString& errMsg) override;
void launchGrpcServer() override;
void initialize() override;
ApplicationStatus handleArguments( cvf::ProgramOptions* progOpt ) override;
int launchUnitTestsWithConsole() override;
void addToRecentFiles( const QString& fileName ) override;
void showFormattedTextInMessageBoxOrConsole( const QString& errMsg ) override;
void launchGrpcServer() override;
#ifdef ENABLE_GRPC
RiaGrpcServer* grpcServer() const override;
RiaGrpcServer* grpcServer() const override;
#endif
protected:
// Protected RiaApplication overrides
void invokeProcessEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents) override;
void onFileSuccessfullyLoaded(const QString& fileName, RiaDefines::ImportFileType fileType) override;
void onProjectBeingOpened() override;
void onProjectOpeningError(const QString& errMsg);
void onProjectOpened() override;
void onProjectBeingClosed() override;
void onProjectClosed() override;
void startMonitoringWorkProgress(caf::UiProcess* uiProcess) override;
void stopMonitoringWorkProgress() override;
private:
void setWindowCaptionFromAppState();
void createMainWindow();
void deleteMainWindow();
void createMainPlotWindow();
void deleteMainPlotWindow();
void loadAndUpdatePlotData();
void storeTreeViewState();
bool notify(QObject *, QEvent *) override;
private slots:
void slotWorkerProcessFinished(int exitCode, QProcess::ExitStatus exitStatus);
void runIdleProcessing();
void onProgramExit();
void invokeProcessEvents( QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents ) override;
void onFileSuccessfullyLoaded( const QString& fileName, RiaDefines::ImportFileType fileType ) override;
void onProjectBeingOpened() override;
void onProjectOpeningError( const QString& errMsg );
void onProjectOpened() override;
void onProjectBeingClosed() override;
void onProjectClosed() override;
void startMonitoringWorkProgress( caf::UiProcess* uiProcess ) override;
void stopMonitoringWorkProgress() override;
private:
RiuMainWindow* m_mainWindow;
RiuPlotMainWindow* m_mainPlotWindow;
void setWindowCaptionFromAppState();
void createMainWindow();
void deleteMainWindow();
void createMainPlotWindow();
void deleteMainPlotWindow();
void loadAndUpdatePlotData();
void storeTreeViewState();
bool notify( QObject*, QEvent* ) override;
private slots:
void slotWorkerProcessFinished( int exitCode, QProcess::ExitStatus exitStatus );
void runIdleProcessing();
void onProgramExit();
private:
RiuMainWindow* m_mainWindow;
RiuPlotMainWindow* m_mainPlotWindow;
#ifdef ENABLE_GRPC
QPointer<QTimer> m_idleTimer;
QPointer<QTimer> m_idleTimer;
#endif
std::unique_ptr<RiuRecentFileActionProvider> m_recentFileActionProvider;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,94 +25,94 @@
#include "cvfqtUtils.h"
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#endif
RiaApplication* createApplication(int &argc, char *argv[])
RiaApplication* createApplication( int& argc, char* argv[] )
{
for (int i = 1; i < argc; ++i)
for ( int i = 1; i < argc; ++i )
{
if (!qstrcmp(argv[i], "--console") || !qstrcmp(argv[i], "--unittest"))
if ( !qstrcmp( argv[i], "--console" ) || !qstrcmp( argv[i], "--unittest" ) )
{
return new RiaConsoleApplication(argc, argv);
return new RiaConsoleApplication( argc, argv );
}
}
return new RiaGuiApplication(argc, argv);
return new RiaGuiApplication( argc, argv );
}
int main(int argc, char *argv[])
int main( int argc, char* argv[] )
{
#ifndef WIN32
// From Qt 5.3 and onwards Qt has a mechanism for checking this automatically
// But it only checks user id not group id, so better to do it ourselves.
if (getuid() != geteuid() || getgid() != getegid())
if ( getuid() != geteuid() || getgid() != getegid() )
{
std::cerr << "FATAL: The application binary appears to be running setuid or setgid, this is a security hole." << std::endl;
std::cerr << "FATAL: The application binary appears to be running setuid or setgid, this is a security hole."
<< std::endl;
return 1;
}
#endif
RiaLogging::loggerInstance()->setLevel(RI_LL_DEBUG);
RiaLogging::loggerInstance()->setLevel( RI_LL_DEBUG );
std::unique_ptr<RiaApplication> app (createApplication(argc, argv));
std::unique_ptr<RiaApplication> app( createApplication( argc, argv ) );
cvf::ProgramOptions progOpt;
bool result = RiaArgumentParser::parseArguments(&progOpt);
bool result = RiaArgumentParser::parseArguments( &progOpt );
const cvf::String usageText = progOpt.usageText(110, 30);
const cvf::String usageText = progOpt.usageText( 110, 30 );
app->initialize();
app->setCommandLineHelpText( cvfqt::Utils::toQString(usageText) );
app->setCommandLineHelpText( cvfqt::Utils::toQString( usageText ) );
if (!result)
if ( !result )
{
std::vector<cvf::String> unknownOptions = progOpt.unknownOptions();
QString unknownOptionsText;
for (cvf::String option : unknownOptions)
QString unknownOptionsText;
for ( cvf::String option : unknownOptions )
{
unknownOptionsText += QString("\tUnknown option: %1\n").arg(cvfqt::Utils::toQString(option));
unknownOptionsText += QString( "\tUnknown option: %1\n" ).arg( cvfqt::Utils::toQString( option ) );
}
app->showFormattedTextInMessageBoxOrConsole("ERROR: Unknown command line options detected ! \n"
+ unknownOptionsText
+ "\n\n"
+ "The current command line options in ResInsight are:\n"
+ app->commandLineParameterHelp());
app->showFormattedTextInMessageBoxOrConsole(
"ERROR: Unknown command line options detected ! \n" + unknownOptionsText + "\n\n" +
"The current command line options in ResInsight are:\n" + app->commandLineParameterHelp() );
if (dynamic_cast<RiaGuiApplication*>(app.get()) == nullptr)
if ( dynamic_cast<RiaGuiApplication*>( app.get() ) == nullptr )
{
return 1;
}
}
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
setlocale(LC_NUMERIC,"C");
RiaApplication::ApplicationStatus status = app->handleArguments(&progOpt);
if (status == RiaApplication::EXIT_COMPLETED)
QLocale::setDefault( QLocale( QLocale::English, QLocale::UnitedStates ) );
setlocale( LC_NUMERIC, "C" );
RiaApplication::ApplicationStatus status = app->handleArguments( &progOpt );
if ( status == RiaApplication::EXIT_COMPLETED )
{
return 0;
}
else if (status == RiaApplication::EXIT_WITH_ERROR)
else if ( status == RiaApplication::EXIT_WITH_ERROR )
{
return 2;
}
else if (status == RiaApplication::KEEP_GOING)
else if ( status == RiaApplication::KEEP_GOING )
{
int exitCode = 0;
try
{
if (app->initializeGrpcServer(progOpt))
if ( app->initializeGrpcServer( progOpt ) )
{
app->launchGrpcServer();
}
exitCode = QCoreApplication::instance()->exec();
}
catch (std::exception& exep )
catch ( std::exception& exep )
{
std::cout << "A standard c++ exception that terminated ResInsight caught in RiaMain.cpp: " << exep.what() << std::endl;
std::cout << "A standard c++ exception that terminated ResInsight caught in RiaMain.cpp: " << exep.what()
<< std::endl;
throw;
}
catch(...)
catch ( ... )
{
std::cout << "An unknown exception that terminated ResInsight caught in RiaMain.cpp. " << std::endl;
throw;
@@ -121,7 +121,6 @@ int main(int argc, char *argv[])
return exitCode;
}
CVF_ASSERT(false && "Unknown ApplicationStatus");
CVF_ASSERT( false && "Unknown ApplicationStatus" );
return -1;
}

View File

@@ -30,17 +30,17 @@
#include "RimGeoMechResultDefinition.h"
#include "RimProject.h"
#include "RigEclipseResultInfo.h"
#include "cafPdmUiListEditor.h"
#include "cafPdmUiPushButtonEditor.h"
#include "cafPdmUiTreeSelectionEditor.h"
#include "RigEclipseResultInfo.h"
//==================================================================================================
///
///
//==================================================================================================
CAF_PDM_SOURCE_INIT(RiaMemoryCleanup, "RiaMemoryCleanup");
CAF_PDM_SOURCE_INIT( RiaMemoryCleanup, "RiaMemoryCleanup" );
//--------------------------------------------------------------------------------------------------
///
@@ -63,9 +63,9 @@ RiaMemoryCleanup::RiaMemoryCleanup()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaMemoryCleanup::setPropertiesFromView(Rim3dView* view)
void RiaMemoryCleanup::setPropertiesFromView( Rim3dView* view )
{
if (!view) return;
if ( !view ) return;
m_case = view->ownerCase();
}
@@ -75,32 +75,32 @@ void RiaMemoryCleanup::setPropertiesFromView(Rim3dView* view)
//--------------------------------------------------------------------------------------------------
void RiaMemoryCleanup::clearSelectedResultsFromMemory()
{
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(m_case());
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>(m_case());
if (eclipseCase)
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>( m_case() );
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>( m_case() );
if ( eclipseCase )
{
RigCaseCellResultsData* caseData = eclipseCase->results(RiaDefines::MATRIX_MODEL);
if (caseData)
RigCaseCellResultsData* caseData = eclipseCase->results( RiaDefines::MATRIX_MODEL );
if ( caseData )
{
std::vector<RigEclipseResultAddress> resultsToDelete = selectedEclipseResults();
for (const RigEclipseResultAddress& resultAddr : resultsToDelete)
for ( const RigEclipseResultAddress& resultAddr : resultsToDelete )
{
caseData->clearScalarResult(resultAddr);
caseData->clearScalarResult( resultAddr );
}
}
}
else if (geoMechCase)
else if ( geoMechCase )
{
RigGeoMechCaseData* data = geoMechCase->geoMechData();
if (data)
if ( data )
{
RigFemPartResultsCollection* resultsCollection = data->femPartResults();
if (resultsCollection)
if ( resultsCollection )
{
std::vector<RigFemResultAddress> resultsToDelete = selectedGeoMechResults();
for (RigFemResultAddress result : resultsToDelete)
for ( RigFemResultAddress result : resultsToDelete )
{
resultsCollection->deleteResult(result);
resultsCollection->deleteResult( result );
}
}
}
@@ -116,12 +116,12 @@ void RiaMemoryCleanup::clearSelectedResultsFromMemory()
std::vector<RigFemResultAddress> RiaMemoryCleanup::selectedGeoMechResults() const
{
std::vector<RigFemResultAddress> results;
if (dynamic_cast<const RimGeoMechCase*>(m_case()))
if ( dynamic_cast<const RimGeoMechCase*>( m_case() ) )
{
for (size_t index : m_resultsToDelete())
for ( size_t index : m_resultsToDelete() )
{
CVF_ASSERT(index < m_geomResultAddresses.size());
results.push_back(m_geomResultAddresses[index]);
CVF_ASSERT( index < m_geomResultAddresses.size() );
results.push_back( m_geomResultAddresses[index] );
}
}
return results;
@@ -133,12 +133,12 @@ std::vector<RigFemResultAddress> RiaMemoryCleanup::selectedGeoMechResults() cons
std::vector<RigEclipseResultAddress> RiaMemoryCleanup::selectedEclipseResults() const
{
std::vector<RigEclipseResultAddress> results;
if (dynamic_cast<const RimEclipseCase*>(m_case()))
if ( dynamic_cast<const RimEclipseCase*>( m_case() ) )
{
for (size_t index : m_resultsToDelete())
for ( size_t index : m_resultsToDelete() )
{
CVF_ASSERT(index < m_eclipseResultAddresses.size());
results.push_back(m_eclipseResultAddresses[index]);
CVF_ASSERT( index < m_eclipseResultAddresses.size() );
results.push_back( m_eclipseResultAddresses[index] );
}
}
return results;
@@ -150,18 +150,18 @@ std::vector<RigEclipseResultAddress> RiaMemoryCleanup::selectedEclipseResults()
std::set<RigFemResultAddress> RiaMemoryCleanup::findGeoMechCaseResultsInUse() const
{
std::set<RigFemResultAddress> resultsInUse;
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>(m_case());
if (geoMechCase)
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>( m_case() );
if ( geoMechCase )
{
std::vector<RimFemResultObserver*> geoMechResults;
geoMechCase->descendantsIncludingThisOfType(geoMechResults);
for (RimFemResultObserver* resultDef : geoMechResults)
geoMechCase->descendantsIncludingThisOfType( geoMechResults );
for ( RimFemResultObserver* resultDef : geoMechResults )
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>(resultDef->objectToggleField());
if (!field || (*field)())
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>( resultDef->objectToggleField() );
if ( !field || ( *field )() )
{
std::vector<RigFemResultAddress> required = resultDef->observedResults();
resultsInUse.insert(required.begin(), required.end());
resultsInUse.insert( required.begin(), required.end() );
}
}
}
@@ -174,15 +174,15 @@ std::set<RigFemResultAddress> RiaMemoryCleanup::findGeoMechCaseResultsInUse() co
std::set<RigEclipseResultAddress> RiaMemoryCleanup::findEclipseResultsInUse() const
{
std::set<RigEclipseResultAddress> resultsInUse;
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(m_case());
if (eclipseCase)
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>( m_case() );
if ( eclipseCase )
{
std::vector<RimEclipseResultDefinition*> eclipseResultDefs;
eclipseCase->descendantsIncludingThisOfType(eclipseResultDefs);
for (RimEclipseResultDefinition* resultDef : eclipseResultDefs)
eclipseCase->descendantsIncludingThisOfType( eclipseResultDefs );
for ( RimEclipseResultDefinition* resultDef : eclipseResultDefs )
{
RigEclipseResultAddress resultAddr(resultDef->resultType(), resultDef->resultVariable());
resultsInUse.insert(resultAddr);
RigEclipseResultAddress resultAddr( resultDef->resultType(), resultDef->resultVariable() );
resultsInUse.insert( resultAddr );
}
}
@@ -192,15 +192,15 @@ std::set<RigEclipseResultAddress> RiaMemoryCleanup::findEclipseResultsInUse() co
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaMemoryCleanup::fieldChangedByUi(const caf::PdmFieldHandle* changedField,
const QVariant& oldValue,
const QVariant& newValue)
void RiaMemoryCleanup::fieldChangedByUi( const caf::PdmFieldHandle* changedField,
const QVariant& oldValue,
const QVariant& newValue )
{
if (changedField == &m_case)
if ( changedField == &m_case )
{
m_resultsToDelete.uiCapability()->updateConnectedEditors();
}
else if (changedField == &m_performDelete)
else if ( changedField == &m_performDelete )
{
clearSelectedResultsFromMemory();
m_resultsToDelete.uiCapability()->updateConnectedEditors();
@@ -211,85 +211,85 @@ void RiaMemoryCleanup::fieldChangedByUi(const caf::PdmFieldHandle* changedField,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo> RiaMemoryCleanup::calculateValueOptions(const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly)
QList<caf::PdmOptionItemInfo> RiaMemoryCleanup::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly )
{
QList<caf::PdmOptionItemInfo> options;
if (fieldNeedingOptions == &m_case)
if ( fieldNeedingOptions == &m_case )
{
RimProject* proj = RiaApplication::instance()->project();
if (proj)
if ( proj )
{
std::vector<RimEclipseCase*> eclipseCases = proj->eclipseCases();
for (RimEclipseCase* c : eclipseCases)
for ( RimEclipseCase* c : eclipseCases )
{
options.push_back(caf::PdmOptionItemInfo(c->caseUserDescription(), c, false, c->uiIconProvider()));
options.push_back( caf::PdmOptionItemInfo( c->caseUserDescription(), c, false, c->uiIconProvider() ) );
}
std::vector<RimGeoMechCase*> geoMechCases = proj->geoMechCases();
for (RimGeoMechCase* c : geoMechCases)
for ( RimGeoMechCase* c : geoMechCases )
{
options.push_back(caf::PdmOptionItemInfo(c->caseUserDescription(), c, false, c->uiIconProvider()));
options.push_back( caf::PdmOptionItemInfo( c->caseUserDescription(), c, false, c->uiIconProvider() ) );
}
}
}
else if (fieldNeedingOptions == &m_resultsToDelete)
else if ( fieldNeedingOptions == &m_resultsToDelete )
{
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(m_case());
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>(m_case());
if (eclipseCase)
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>( m_case() );
RimGeoMechCase* geoMechCase = dynamic_cast<RimGeoMechCase*>( m_case() );
if ( eclipseCase )
{
std::set<RigEclipseResultAddress> resultsInUse = findEclipseResultsInUse();
RigCaseCellResultsData* caseData = eclipseCase->results(RiaDefines::MATRIX_MODEL);
if (caseData)
RigCaseCellResultsData* caseData = eclipseCase->results( RiaDefines::MATRIX_MODEL );
if ( caseData )
{
m_eclipseResultAddresses = caseData->existingResults();
for (size_t i = 0; i < m_eclipseResultAddresses.size(); ++i)
for ( size_t i = 0; i < m_eclipseResultAddresses.size(); ++i )
{
const RigEclipseResultAddress& resultAddr = m_eclipseResultAddresses[i];
if (caseData->isResultLoaded(resultAddr))
if ( caseData->isResultLoaded( resultAddr ) )
{
bool inUse = resultsInUse.count(resultAddr);
bool inUse = resultsInUse.count( resultAddr );
const RigEclipseResultInfo* resInfo = caseData->resultInfo(resultAddr);
const RigEclipseResultInfo* resInfo = caseData->resultInfo( resultAddr );
QString posText = caf::AppEnum<RiaDefines::ResultCatType>::uiTextFromIndex(resInfo->resultType());
QString resultsText = QString("%1, %2").arg(posText).arg(resInfo->resultName());
if (inUse)
QString posText = caf::AppEnum<RiaDefines::ResultCatType>::uiTextFromIndex(
resInfo->resultType() );
QString resultsText = QString( "%1, %2" ).arg( posText ).arg( resInfo->resultName() );
if ( inUse )
{
resultsText += QString(" [used in view]");
resultsText += QString( " [used in view]" );
}
options.push_back(caf::PdmOptionItemInfo(resultsText, (qulonglong)i, inUse));
options.push_back( caf::PdmOptionItemInfo( resultsText, (qulonglong)i, inUse ) );
}
}
}
}
else if (geoMechCase)
else if ( geoMechCase )
{
std::set<RigFemResultAddress> resultsInUse = findGeoMechCaseResultsInUse();
RigGeoMechCaseData* caseData = geoMechCase->geoMechData();
if (caseData)
if ( caseData )
{
RigFemPartResultsCollection* results = caseData->femPartResults();
m_geomResultAddresses = results->loadedResults();
for (size_t i = 0; i < m_geomResultAddresses.size(); ++i)
for ( size_t i = 0; i < m_geomResultAddresses.size(); ++i )
{
const RigFemResultAddress& result = m_geomResultAddresses[i];
bool inUse = resultsInUse.count(result);
QString posText = caf::AppEnum<RigFemResultPosEnum>::uiTextFromIndex(result.resultPosType);
QString resultsText = QString("%1, %2").arg(posText).arg(QString::fromStdString(result.fieldName));
if (!result.componentName.empty())
const RigFemResultAddress& result = m_geomResultAddresses[i];
bool inUse = resultsInUse.count( result );
QString posText = caf::AppEnum<RigFemResultPosEnum>::uiTextFromIndex( result.resultPosType );
QString resultsText = QString( "%1, %2" ).arg( posText ).arg( QString::fromStdString( result.fieldName ) );
if ( !result.componentName.empty() )
{
resultsText += QString(", %1").arg(QString::fromStdString(result.componentName));
resultsText += QString( ", %1" ).arg( QString::fromStdString( result.componentName ) );
}
if (inUse)
if ( inUse )
{
resultsText += QString(" [used in view]");
resultsText += QString( " [used in view]" );
}
options.push_back(caf::PdmOptionItemInfo(resultsText, (qulonglong) i, inUse));
options.push_back( caf::PdmOptionItemInfo( resultsText, (qulonglong)i, inUse ) );
}
}
}
@@ -300,22 +300,24 @@ QList<caf::PdmOptionItemInfo> RiaMemoryCleanup::calculateValueOptions(const caf:
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaMemoryCleanup::defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering)
void RiaMemoryCleanup::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering )
{
uiOrdering.add(&m_case);
uiOrdering.add(&m_resultsToDelete);
uiOrdering.add(&m_performDelete);
uiOrdering.add( &m_case );
uiOrdering.add( &m_resultsToDelete );
uiOrdering.add( &m_performDelete );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaMemoryCleanup::defineEditorAttribute(const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute)
void RiaMemoryCleanup::defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute )
{
if (field == &m_performDelete)
if ( field == &m_performDelete )
{
caf::PdmUiPushButtonEditorAttribute* attrib = dynamic_cast<caf::PdmUiPushButtonEditorAttribute*>(attribute);
if (attrib)
caf::PdmUiPushButtonEditorAttribute* attrib = dynamic_cast<caf::PdmUiPushButtonEditorAttribute*>( attribute );
if ( attrib )
{
attrib->m_buttonText = "Clear Checked Data From Memory";
}

View File

@@ -18,11 +18,10 @@
#pragma once
#include "cafPdmField.h"
#include "cafPdmChildArrayField.h"
#include "cafPdmPtrField.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
#include "cafPdmPtrField.h"
#include "cafPdmUiItem.h"
class RimCase;
@@ -33,27 +32,35 @@ class RigEclipseResultAddress;
class RiaMemoryCleanup : public caf::PdmObject
{
CAF_PDM_HEADER_INIT;
public:
RiaMemoryCleanup();
void setPropertiesFromView(Rim3dView* view);
void clearSelectedResultsFromMemory();
protected:
void fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue) override;
private:
std::vector<RigFemResultAddress> selectedGeoMechResults() const;
std::vector<RigEclipseResultAddress> selectedEclipseResults() const;
std::set<RigFemResultAddress> findGeoMechCaseResultsInUse() const;
std::set<RigEclipseResultAddress> findEclipseResultsInUse() const;
void setPropertiesFromView( Rim3dView* view );
void clearSelectedResultsFromMemory();
protected:
void fieldChangedByUi( const caf::PdmFieldHandle* changedField,
const QVariant& oldValue,
const QVariant& newValue ) override;
QList<caf::PdmOptionItemInfo> calculateValueOptions(const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly) override;
void defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering) override;
void defineEditorAttribute(const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute) override;
private:
caf::PdmPtrField<RimCase*> m_case;
caf::PdmField<std::vector<size_t>> m_resultsToDelete;
std::vector<RigFemResultAddress> m_geomResultAddresses;
std::vector<RigEclipseResultAddress> m_eclipseResultAddresses;
caf::PdmField<bool> m_performDelete;
std::vector<RigFemResultAddress> selectedGeoMechResults() const;
std::vector<RigEclipseResultAddress> selectedEclipseResults() const;
std::set<RigFemResultAddress> findGeoMechCaseResultsInUse() const;
std::set<RigEclipseResultAddress> findEclipseResultsInUse() const;
QList<caf::PdmOptionItemInfo> calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly ) override;
void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override;
void defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute ) override;
private:
caf::PdmPtrField<RimCase*> m_case;
caf::PdmField<std::vector<size_t>> m_resultsToDelete;
std::vector<RigFemResultAddress> m_geomResultAddresses;
std::vector<RigEclipseResultAddress> m_eclipseResultAddresses;
caf::PdmField<bool> m_performDelete;
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -20,15 +20,14 @@
#include "cafAppEnum.h"
namespace caf
{
template<>
void caf::AppEnum< RiaDefines::PorosityModelType >::setUp()
{
addItem(RiaDefines::MATRIX_MODEL, "MATRIX_MODEL", "Matrix");
addItem(RiaDefines::FRACTURE_MODEL, "FRACTURE_MODEL", "Fracture");
template <>
void caf::AppEnum<RiaDefines::PorosityModelType>::setUp()
{
addItem( RiaDefines::MATRIX_MODEL, "MATRIX_MODEL", "Matrix" );
addItem( RiaDefines::FRACTURE_MODEL, "FRACTURE_MODEL", "Fracture" );
setDefault(RiaDefines::MATRIX_MODEL);
}
setDefault( RiaDefines::MATRIX_MODEL );
}
} // namespace caf

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,13 +19,13 @@
#pragma once
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
namespace RiaDefines
{
enum PorosityModelType
{
MATRIX_MODEL,
FRACTURE_MODEL
};
enum PorosityModelType
{
MATRIX_MODEL,
FRACTURE_MODEL
};
};

View File

@@ -4,17 +4,17 @@
// Copyright (C) 2011-2018 Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,8 +26,8 @@
#include "RifReaderSettings.h"
#include "cafPdmFieldCvfColor.h"
#include "cafPdmUiComboBoxEditor.h"
#include "cafPdmUiCheckBoxEditor.h"
#include "cafPdmUiComboBoxEditor.h"
#include "cafPdmUiFieldHandle.h"
#include "cafPdmUiFilePathEditor.h"
@@ -35,365 +35,479 @@
#include <QDir>
#include <QLocale>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
#include <QStandardPaths>
#endif
namespace caf
namespace caf
{
template<>
void RiaPreferences::SummaryRestartFilesImportModeType::setUp()
{
addItem(RiaPreferences::IMPORT, "IMPORT", "Unified");
addItem(RiaPreferences::SEPARATE_CASES, "SEPARATE_CASES", "Separate Cases");
addItem(RiaPreferences::NOT_IMPORT, "NOT_IMPORT", "Skip");
setDefault(RiaPreferences::IMPORT);
}
template<>
void RiaPreferences::SummaryHistoryCurveStyleModeType::setUp()
{
addItem(RiaPreferences::SYMBOLS, "SYMBOLS", "Symbols");
addItem(RiaPreferences::LINES, "LINES", "Lines");
addItem(RiaPreferences::SYMBOLS_AND_LINES, "SYMBOLS_AND_LINES", "Symbols and Lines");
setDefault(RiaPreferences::SYMBOLS);
}
}
CAF_PDM_SOURCE_INIT(RiaPreferences, "RiaPreferences");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaPreferences::RiaPreferences(void)
template <>
void RiaPreferences::SummaryRestartFilesImportModeType::setUp()
{
CAF_PDM_InitField(&navigationPolicy, "navigationPolicy", caf::AppEnum<RiaGuiApplication::RINavigationPolicy>(RiaGuiApplication::NAVIGATION_POLICY_RMS), "Navigation Mode", "", "", "");
addItem( RiaPreferences::IMPORT, "IMPORT", "Unified" );
addItem( RiaPreferences::SEPARATE_CASES, "SEPARATE_CASES", "Separate Cases" );
addItem( RiaPreferences::NOT_IMPORT, "NOT_IMPORT", "Skip" );
setDefault( RiaPreferences::IMPORT );
}
CAF_PDM_InitField(&enableGrpcServer, "enableGrpcServer", true, "Enable Python Script Server", "", "Remote Procedure Call Scripting Engine", "");
CAF_PDM_InitField(&defaultGrpcPortNumber, "defaultGrpcPort", 50051, "Default Python Script Server Port", "", "", "");
template <>
void RiaPreferences::SummaryHistoryCurveStyleModeType::setUp()
{
addItem( RiaPreferences::SYMBOLS, "SYMBOLS", "Symbols" );
addItem( RiaPreferences::LINES, "LINES", "Lines" );
addItem( RiaPreferences::SYMBOLS_AND_LINES, "SYMBOLS_AND_LINES", "Symbols and Lines" );
setDefault( RiaPreferences::SYMBOLS );
}
} // namespace caf
CAF_PDM_InitFieldNoDefault(&scriptDirectories, "scriptDirectory", "Shared Script Folder(s)", "", "", "");
scriptDirectories.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
// TODO: This only currently works for installed ResInsight.
scriptDirectories = QCoreApplication::applicationDirPath() + "/Python/rips/PythonExamples";
CAF_PDM_SOURCE_INIT( RiaPreferences, "RiaPreferences" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaPreferences::RiaPreferences( void )
{
CAF_PDM_InitField( &navigationPolicy,
"navigationPolicy",
caf::AppEnum<RiaGuiApplication::RINavigationPolicy>( RiaGuiApplication::NAVIGATION_POLICY_RMS ),
"Navigation Mode",
"",
"",
"" );
QString defaultTextEditor;
CAF_PDM_InitField( &enableGrpcServer,
"enableGrpcServer",
true,
"Enable Python Script Server",
"",
"Remote Procedure Call Scripting Engine",
"" );
CAF_PDM_InitField( &defaultGrpcPortNumber, "defaultGrpcPort", 50051, "Default Python Script Server Port", "", "", "" );
CAF_PDM_InitFieldNoDefault( &scriptDirectories, "scriptDirectory", "Shared Script Folder(s)", "", "", "" );
scriptDirectories.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
// TODO: This only currently works for installed ResInsight.
scriptDirectories = QCoreApplication::applicationDirPath() + "/Python/rips/PythonExamples";
QString defaultTextEditor;
#ifdef WIN32
defaultTextEditor = QString("notepad.exe");
defaultTextEditor = QString( "notepad.exe" );
#else
defaultTextEditor = QString("kate");
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
defaultTextEditor = QStandardPaths::findExecutable("kate");
if (defaultTextEditor.isEmpty())
defaultTextEditor = QString( "kate" );
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
defaultTextEditor = QStandardPaths::findExecutable( "kate" );
if ( defaultTextEditor.isEmpty() )
{
defaultTextEditor = QStandardPaths::findExecutable("gedit");
defaultTextEditor = QStandardPaths::findExecutable( "gedit" );
}
#endif
#endif
CAF_PDM_InitField(&scriptEditorExecutable, "scriptEditorExecutable", defaultTextEditor, "Script Editor", "", "", "");
scriptEditorExecutable.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitField(&octaveExecutable, "octaveExecutable", QString("octave"), "Octave Executable Location", "", "", "");
octaveExecutable.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
octaveExecutable.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::TOP);
CAF_PDM_InitField( &scriptEditorExecutable, "scriptEditorExecutable", defaultTextEditor, "Script Editor", "", "", "" );
scriptEditorExecutable.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitField(&octaveShowHeaderInfoWhenExecutingScripts, "octaveShowHeaderInfoWhenExecutingScripts", false, "Show Text Header When Executing Scripts", "", "", "");
octaveShowHeaderInfoWhenExecutingScripts.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField( &octaveExecutable, "octaveExecutable", QString( "octave" ), "Octave Executable Location", "", "", "" );
octaveExecutable.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
octaveExecutable.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP );
CAF_PDM_InitField(&pythonExecutable, "pythonExecutable", QString("python"), "Python Executable Location", "", "", "");
pythonExecutable.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
pythonExecutable.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::TOP);
CAF_PDM_InitField(&showPythonDebugInfo, "pythonDebugInfo", false, "Show Python Debug Info", "", "", "");
CAF_PDM_InitField( &octaveShowHeaderInfoWhenExecutingScripts,
"octaveShowHeaderInfoWhenExecutingScripts",
false,
"Show Text Header When Executing Scripts",
"",
"",
"" );
octaveShowHeaderInfoWhenExecutingScripts.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField(&ssihubAddress, "ssihubAddress", QString("http://"), "SSIHUB Address", "", "", "");
ssihubAddress.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::TOP);
CAF_PDM_InitField( &pythonExecutable, "pythonExecutable", QString( "python" ), "Python Executable Location", "", "", "" );
pythonExecutable.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
pythonExecutable.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP );
CAF_PDM_InitField( &showPythonDebugInfo, "pythonDebugInfo", false, "Show Python Debug Info", "", "", "" );
CAF_PDM_InitFieldNoDefault(&defaultMeshModeType, "defaultMeshModeType", "Show Grid Lines", "", "", "");
CAF_PDM_InitField(&defaultGridLineColors, "defaultGridLineColors", RiaColorTables::defaultGridLineColor(), "Mesh Color", "", "", "");
CAF_PDM_InitField(&defaultFaultGridLineColors, "defaultFaultGridLineColors", RiaColorTables::defaultFaultLineColor(), "Mesh Color Along Faults", "", "", "");
CAF_PDM_InitField(&defaultWellLabelColor, "defaultWellLableColor", RiaColorTables::defaultWellLabelColor(), "Well Label Color", "", "The default well label color in new views", "");
CAF_PDM_InitField( &ssihubAddress, "ssihubAddress", QString( "http://" ), "SSIHUB Address", "", "", "" );
ssihubAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP );
CAF_PDM_InitField(&defaultViewerBackgroundColor, "defaultViewerBackgroundColor", RiaColorTables::defaultViewerBackgroundColor(), "Viewer Background", "", "The viewer background color for new views", "");
CAF_PDM_InitFieldNoDefault( &defaultMeshModeType, "defaultMeshModeType", "Show Grid Lines", "", "", "" );
CAF_PDM_InitField( &defaultGridLineColors,
"defaultGridLineColors",
RiaColorTables::defaultGridLineColor(),
"Mesh Color",
"",
"",
"" );
CAF_PDM_InitField( &defaultFaultGridLineColors,
"defaultFaultGridLineColors",
RiaColorTables::defaultFaultLineColor(),
"Mesh Color Along Faults",
"",
"",
"" );
CAF_PDM_InitField( &defaultWellLabelColor,
"defaultWellLableColor",
RiaColorTables::defaultWellLabelColor(),
"Well Label Color",
"",
"The default well label color in new views",
"" );
CAF_PDM_InitField(&defaultScaleFactorZ, "defaultScaleFactorZ", 5, "Default Z Scale Factor", "", "", "");
CAF_PDM_InitField( &defaultViewerBackgroundColor,
"defaultViewerBackgroundColor",
RiaColorTables::defaultViewerBackgroundColor(),
"Viewer Background",
"",
"The viewer background color for new views",
"" );
caf::AppEnum<RiaFontCache::FontSize> fontSize = RiaFontCache::FONT_SIZE_8;
caf::AppEnum<RiaFontCache::FontSize> plotFontSize = RiaFontCache::FONT_SIZE_10;
CAF_PDM_InitField(&defaultSceneFontSize, "fontSizeInScene", fontSize, "Viewer Font Size", "", "", "");
CAF_PDM_InitField(&defaultAnnotationFontSize, "defaultAnnotationFontSize", fontSize, "Annotation Font Size", "", "", "");
CAF_PDM_InitField(&defaultWellLabelFontSize, "wellLabelFontSize", fontSize, "Well Label Font Size", "", "", "");
CAF_PDM_InitField(&defaultPlotFontSize, "defaultPlotFontSize", plotFontSize, "Plot Font Size", "", "", "");
CAF_PDM_InitField( &defaultScaleFactorZ, "defaultScaleFactorZ", 5, "Default Z Scale Factor", "", "", "" );
CAF_PDM_InitField(&showLasCurveWithoutTvdWarning, "showLasCurveWithoutTvdWarning", true, "Show LAS Curve Without TVD Warning", "", "", "");
showLasCurveWithoutTvdWarning.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
caf::AppEnum<RiaFontCache::FontSize> fontSize = RiaFontCache::FONT_SIZE_8;
caf::AppEnum<RiaFontCache::FontSize> plotFontSize = RiaFontCache::FONT_SIZE_10;
CAF_PDM_InitField( &defaultSceneFontSize, "fontSizeInScene", fontSize, "Viewer Font Size", "", "", "" );
CAF_PDM_InitField( &defaultAnnotationFontSize, "defaultAnnotationFontSize", fontSize, "Annotation Font Size", "", "", "" );
CAF_PDM_InitField( &defaultWellLabelFontSize, "wellLabelFontSize", fontSize, "Well Label Font Size", "", "", "" );
CAF_PDM_InitField( &defaultPlotFontSize, "defaultPlotFontSize", plotFontSize, "Plot Font Size", "", "", "" );
CAF_PDM_InitField(&useShaders, "useShaders", true, "Use Shaders", "", "", "");
useShaders.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&showHud, "showHud", false, "Show 3D Information", "", "", "");
showHud.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&m_appendClassNameToUiText, "appendClassNameToUiText", false, "Show Class Names", "", "", "");
m_appendClassNameToUiText.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&m_appendFieldKeywordToToolTipText, "appendFieldKeywordToToolTipText", false, "Show Field Keyword in ToolTip", "", "", "");
m_appendFieldKeywordToToolTipText.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&m_showTestToolbar, "showTestToolbar", false, "Enable Test Toolbar", "", "", "");
m_showTestToolbar.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&m_includeFractureDebugInfoFile, "includeFractureDebugInfoFile", false, "Include Fracture Debug Info for Completion Export", "", "", "");
m_includeFractureDebugInfoFile.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField( &showLasCurveWithoutTvdWarning,
"showLasCurveWithoutTvdWarning",
true,
"Show LAS Curve Without TVD Warning",
"",
"",
"" );
showLasCurveWithoutTvdWarning.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField(&showLegendBackground, "showLegendBackground", true, "Show Box around Legends", "", "", "");
showLegendBackground.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField( &useShaders, "useShaders", true, "Use Shaders", "", "", "" );
useShaders.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField( &showHud, "showHud", false, "Show 3D Information", "", "", "" );
showHud.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField( &m_appendClassNameToUiText, "appendClassNameToUiText", false, "Show Class Names", "", "", "" );
m_appendClassNameToUiText.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField( &m_appendFieldKeywordToToolTipText,
"appendFieldKeywordToToolTipText",
false,
"Show Field Keyword in ToolTip",
"",
"",
"" );
m_appendFieldKeywordToToolTipText.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField( &m_showTestToolbar, "showTestToolbar", false, "Enable Test Toolbar", "", "", "" );
m_showTestToolbar.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField( &m_includeFractureDebugInfoFile,
"includeFractureDebugInfoFile",
false,
"Include Fracture Debug Info for Completion Export",
"",
"",
"" );
m_includeFractureDebugInfoFile.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitFieldNoDefault(&lastUsedProjectFileName,"lastUsedProjectFileName", "Last Used Project File", "", "", "");
lastUsedProjectFileName.uiCapability()->setUiHidden(true);
CAF_PDM_InitField( &showLegendBackground, "showLegendBackground", true, "Show Box around Legends", "", "", "" );
showLegendBackground.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField(&autocomputeDepthRelatedProperties, "autocomputeDepth", true, "Compute DEPTH Related Properties", "", "DEPTH, DX, DY, DZ, TOP, BOTTOM", "");
autocomputeDepthRelatedProperties.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField(&loadAndShowSoil, "loadAndShowSoil", true, "Load and Show SOIL", "", "", "");
loadAndShowSoil.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitFieldNoDefault( &lastUsedProjectFileName, "lastUsedProjectFileName", "Last Used Project File", "", "", "" );
lastUsedProjectFileName.uiCapability()->setUiHidden( true );
CAF_PDM_InitFieldNoDefault(&summaryRestartFilesShowImportDialog, "summaryRestartFilesShowImportDialog", "Show Import Dialog", "", "", "");
CAF_PDM_InitField(&summaryImportMode, "summaryImportMode", SummaryRestartFilesImportModeType(RiaPreferences::IMPORT), "Default Summary Import Option", "", "", "");
CAF_PDM_InitField(&gridImportMode, "gridImportMode", SummaryRestartFilesImportModeType(RiaPreferences::NOT_IMPORT), "Default Grid Import Option", "", "", "");
CAF_PDM_InitField(&summaryEnsembleImportMode, "summaryEnsembleImportMode", SummaryRestartFilesImportModeType(RiaPreferences::IMPORT), "Default Ensemble Summary Import Option", "", "", "");
CAF_PDM_InitField( &autocomputeDepthRelatedProperties,
"autocomputeDepth",
true,
"Compute DEPTH Related Properties",
"",
"DEPTH, DX, DY, DZ, TOP, BOTTOM",
"" );
autocomputeDepthRelatedProperties.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitField(&defaultSummaryHistoryCurveStyle, "defaultSummaryHistoryCurveStyle", SummaryHistoryCurveStyleModeType(RiaPreferences::SYMBOLS), "Default Curve Style for History Vectors", "", "", "");
CAF_PDM_InitField(&defaultSummaryCurvesTextFilter, "defaultSummaryCurvesTextFilter", QString("FOPT"), "Default Summary Curves", "", "Semicolon separated list of filters used to create curves in new summary plots", "");
CAF_PDM_InitField( &loadAndShowSoil, "loadAndShowSoil", true, "Load and Show SOIL", "", "", "" );
loadAndShowSoil.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitFieldNoDefault(&m_holoLensExportFolder, "holoLensExportFolder", "HoloLens Export Folder", "", "", "");
m_holoLensExportFolder.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::TOP);
m_holoLensExportFolder.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &summaryRestartFilesShowImportDialog,
"summaryRestartFilesShowImportDialog",
"Show Import Dialog",
"",
"",
"" );
CAF_PDM_InitField( &summaryImportMode,
"summaryImportMode",
SummaryRestartFilesImportModeType( RiaPreferences::IMPORT ),
"Default Summary Import Option",
"",
"",
"" );
CAF_PDM_InitField( &gridImportMode,
"gridImportMode",
SummaryRestartFilesImportModeType( RiaPreferences::NOT_IMPORT ),
"Default Grid Import Option",
"",
"",
"" );
CAF_PDM_InitField( &summaryEnsembleImportMode,
"summaryEnsembleImportMode",
SummaryRestartFilesImportModeType( RiaPreferences::IMPORT ),
"Default Ensemble Summary Import Option",
"",
"",
"" );
CAF_PDM_InitField(&holoLensDisableCertificateVerification, "holoLensDisableCertificateVerification", false, "Disable SSL Certificate Verification (HoloLens)", "", "", "");
holoLensDisableCertificateVerification.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField( &defaultSummaryHistoryCurveStyle,
"defaultSummaryHistoryCurveStyle",
SummaryHistoryCurveStyleModeType( RiaPreferences::SYMBOLS ),
"Default Curve Style for History Vectors",
"",
"",
"" );
CAF_PDM_InitField( &defaultSummaryCurvesTextFilter,
"defaultSummaryCurvesTextFilter",
QString( "FOPT" ),
"Default Summary Curves",
"",
"Semicolon separated list of filters used to create curves in new summary plots",
"" );
CAF_PDM_InitField(&csvTextExportFieldSeparator, "csvTextExportFieldSeparator", QString(","), "CSV Text Export Field Separator", "", "", "");
CAF_PDM_InitFieldNoDefault( &m_holoLensExportFolder, "holoLensExportFolder", "HoloLens Export Folder", "", "", "" );
m_holoLensExportFolder.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP );
m_holoLensExportFolder.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitField(&m_showProjectChangedDialog, "showProjectChangedDialog", true, "Show 'Project has changed' dialog", "", "", "");
m_showProjectChangedDialog.uiCapability()->setUiLabelPosition(caf::PdmUiItemInfo::HIDDEN);
CAF_PDM_InitField( &holoLensDisableCertificateVerification,
"holoLensDisableCertificateVerification",
false,
"Disable SSL Certificate Verification (HoloLens)",
"",
"",
"" );
holoLensDisableCertificateVerification.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitFieldNoDefault(&m_readerSettings, "readerSettings", "Reader Settings", "", "", "");
CAF_PDM_InitField( &csvTextExportFieldSeparator,
"csvTextExportFieldSeparator",
QString( "," ),
"CSV Text Export Field Separator",
"",
"",
"" );
CAF_PDM_InitField( &m_showProjectChangedDialog,
"showProjectChangedDialog",
true,
"Show 'Project has changed' dialog",
"",
"",
"" );
m_showProjectChangedDialog.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN );
CAF_PDM_InitFieldNoDefault( &m_readerSettings, "readerSettings", "Reader Settings", "", "", "" );
m_readerSettings = new RifReaderSettings;
CAF_PDM_InitFieldNoDefault(&m_dateFormat, "dateFormat", "Date Format", "", "", "");
m_dateFormat.uiCapability()->setUiEditorTypeName(caf::PdmUiComboBoxEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &m_dateFormat, "dateFormat", "Date Format", "", "", "" );
m_dateFormat.uiCapability()->setUiEditorTypeName( caf::PdmUiComboBoxEditor::uiEditorTypeName() );
m_dateFormat = RiaQDateTimeTools::supportedDateFormats().front();
CAF_PDM_InitFieldNoDefault(&m_timeFormat, "timeFormat", "Time Format", "", "", "");
m_timeFormat.uiCapability()->setUiEditorTypeName(caf::PdmUiComboBoxEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &m_timeFormat, "timeFormat", "Time Format", "", "", "" );
m_timeFormat.uiCapability()->setUiEditorTypeName( caf::PdmUiComboBoxEditor::uiEditorTypeName() );
m_timeFormat = RiaQDateTimeTools::supportedTimeFormats().front();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaPreferences::~RiaPreferences(void)
RiaPreferences::~RiaPreferences( void )
{
delete m_readerSettings;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaPreferences::defineEditorAttribute(const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute * attribute)
void RiaPreferences::defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute )
{
m_readerSettings->defineEditorAttribute(field, uiConfigName, attribute);
m_readerSettings->defineEditorAttribute( field, uiConfigName, attribute );
if (field == &scriptDirectories)
if ( field == &scriptDirectories )
{
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>(attribute);
if (myAttr)
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>( attribute );
if ( myAttr )
{
myAttr->m_selectDirectory = true;
myAttr->m_selectDirectory = true;
myAttr->m_appendUiSelectedFolderToText = true;
}
}
else if (field == &octaveShowHeaderInfoWhenExecutingScripts ||
field == &autocomputeDepthRelatedProperties ||
field == &loadAndShowSoil ||
field == &useShaders ||
field == &showHud ||
field == &m_appendClassNameToUiText ||
field == &m_appendFieldKeywordToToolTipText ||
field == &m_showTestToolbar ||
field == &m_includeFractureDebugInfoFile ||
field == &showLasCurveWithoutTvdWarning ||
field == &holoLensDisableCertificateVerification ||
field == &m_showProjectChangedDialog ||
field == &showLegendBackground)
else if ( field == &octaveShowHeaderInfoWhenExecutingScripts || field == &autocomputeDepthRelatedProperties ||
field == &loadAndShowSoil || field == &useShaders || field == &showHud ||
field == &m_appendClassNameToUiText || field == &m_appendFieldKeywordToToolTipText ||
field == &m_showTestToolbar || field == &m_includeFractureDebugInfoFile ||
field == &showLasCurveWithoutTvdWarning || field == &holoLensDisableCertificateVerification ||
field == &m_showProjectChangedDialog || field == &showLegendBackground )
{
caf::PdmUiCheckBoxEditorAttribute* myAttr = dynamic_cast<caf::PdmUiCheckBoxEditorAttribute*>(attribute);
if (myAttr)
caf::PdmUiCheckBoxEditorAttribute* myAttr = dynamic_cast<caf::PdmUiCheckBoxEditorAttribute*>( attribute );
if ( myAttr )
{
myAttr->m_useNativeCheckBoxLabel = true;
}
}
else if (field == &m_holoLensExportFolder)
else if ( field == &m_holoLensExportFolder )
{
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>(attribute);
if (myAttr)
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>( attribute );
if ( myAttr )
{
myAttr->m_selectDirectory = true;
}
}
if (field == &defaultSceneFontSize || field == &defaultWellLabelFontSize ||
field == &defaultAnnotationFontSize || field == &defaultPlotFontSize)
if ( field == &defaultSceneFontSize || field == &defaultWellLabelFontSize || field == &defaultAnnotationFontSize ||
field == &defaultPlotFontSize )
{
caf::PdmUiComboBoxEditorAttribute* myAttr = dynamic_cast<caf::PdmUiComboBoxEditorAttribute*>(attribute);
myAttr->minimumContentsLength = 2;
caf::PdmUiComboBoxEditorAttribute* myAttr = dynamic_cast<caf::PdmUiComboBoxEditorAttribute*>( attribute );
myAttr->minimumContentsLength = 2;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaPreferences::defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering)
void RiaPreferences::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering )
{
if (uiConfigName == RiaPreferences::tabNameGeneral())
if ( uiConfigName == RiaPreferences::tabNameGeneral() )
{
caf::PdmUiGroup* colorGroup = uiOrdering.addNewGroup("Default Colors");
colorGroup->add(&defaultViewerBackgroundColor);
colorGroup->add(&defaultGridLineColors, false);
colorGroup->add(&defaultFaultGridLineColors);
colorGroup->add(&defaultWellLabelColor, false);
caf::PdmUiGroup* fontGroup = uiOrdering.addNewGroup("Default Font Sizes");
fontGroup->add(&defaultSceneFontSize);
fontGroup->add(&defaultAnnotationFontSize, false);
fontGroup->add(&defaultWellLabelFontSize);
fontGroup->add(&defaultPlotFontSize, false);
caf::PdmUiGroup* viewsGroup = uiOrdering.addNewGroup("3d Views");
viewsGroup->add(&defaultMeshModeType);
viewsGroup->add(&navigationPolicy);
viewsGroup->add(&defaultScaleFactorZ);
viewsGroup->add(&showLegendBackground);
viewsGroup->add(&useShaders);
viewsGroup->add(&showHud);
caf::PdmUiGroup* otherGroup = uiOrdering.addNewGroup("Other");
otherGroup->add(&ssihubAddress);
otherGroup->add(&showLasCurveWithoutTvdWarning);
otherGroup->add(&holoLensDisableCertificateVerification);
caf::PdmUiGroup* colorGroup = uiOrdering.addNewGroup( "Default Colors" );
colorGroup->add( &defaultViewerBackgroundColor );
colorGroup->add( &defaultGridLineColors, false );
colorGroup->add( &defaultFaultGridLineColors );
colorGroup->add( &defaultWellLabelColor, false );
caf::PdmUiGroup* fontGroup = uiOrdering.addNewGroup( "Default Font Sizes" );
fontGroup->add( &defaultSceneFontSize );
fontGroup->add( &defaultAnnotationFontSize, false );
fontGroup->add( &defaultWellLabelFontSize );
fontGroup->add( &defaultPlotFontSize, false );
caf::PdmUiGroup* viewsGroup = uiOrdering.addNewGroup( "3d Views" );
viewsGroup->add( &defaultMeshModeType );
viewsGroup->add( &navigationPolicy );
viewsGroup->add( &defaultScaleFactorZ );
viewsGroup->add( &showLegendBackground );
viewsGroup->add( &useShaders );
viewsGroup->add( &showHud );
caf::PdmUiGroup* otherGroup = uiOrdering.addNewGroup( "Other" );
otherGroup->add( &ssihubAddress );
otherGroup->add( &showLasCurveWithoutTvdWarning );
otherGroup->add( &holoLensDisableCertificateVerification );
}
else if (uiConfigName == RiaPreferences::tabNameEclipse())
else if ( uiConfigName == RiaPreferences::tabNameEclipse() )
{
caf::PdmUiGroup* newCaseBehaviourGroup = uiOrdering.addNewGroup("Behavior When Loading Data");
newCaseBehaviourGroup->add(&autocomputeDepthRelatedProperties);
newCaseBehaviourGroup->add(&loadAndShowSoil);
m_readerSettings->defineUiOrdering(uiConfigName, *newCaseBehaviourGroup);
caf::PdmUiGroup* restartBehaviourGroup = uiOrdering.addNewGroup("Origin Files");
restartBehaviourGroup->add(&summaryRestartFilesShowImportDialog);
caf::PdmUiGroup* newCaseBehaviourGroup = uiOrdering.addNewGroup( "Behavior When Loading Data" );
newCaseBehaviourGroup->add( &autocomputeDepthRelatedProperties );
newCaseBehaviourGroup->add( &loadAndShowSoil );
m_readerSettings->defineUiOrdering( uiConfigName, *newCaseBehaviourGroup );
caf::PdmUiGroup* restartBehaviourGroup = uiOrdering.addNewGroup( "Origin Files" );
restartBehaviourGroup->add( &summaryRestartFilesShowImportDialog );
{
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup("Origin Summary Files");
group->add(&summaryImportMode);
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup( "Origin Summary Files" );
group->add( &summaryImportMode );
}
{
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup("Origin Grid Files");
group->add(&gridImportMode);
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup( "Origin Grid Files" );
group->add( &gridImportMode );
}
{
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup("Origin Ensemble Summary Files");
group->add(&summaryEnsembleImportMode);
caf::PdmUiGroup* group = restartBehaviourGroup->addNewGroup( "Origin Ensemble Summary Files" );
group->add( &summaryEnsembleImportMode );
}
}
else if (uiConfigName == RiaPreferences::tabNamePlotting())
else if ( uiConfigName == RiaPreferences::tabNamePlotting() )
{
uiOrdering.add(&defaultSummaryCurvesTextFilter);
uiOrdering.add(&defaultSummaryHistoryCurveStyle);
uiOrdering.add(&m_dateFormat);
uiOrdering.add(&m_timeFormat);
uiOrdering.add( &defaultSummaryCurvesTextFilter );
uiOrdering.add( &defaultSummaryHistoryCurveStyle );
uiOrdering.add( &m_dateFormat );
uiOrdering.add( &m_timeFormat );
}
else if (uiConfigName == RiaPreferences::tabNameScripting())
else if ( uiConfigName == RiaPreferences::tabNameScripting() )
{
caf::PdmUiGroup* octaveGroup = uiOrdering.addNewGroup("Octave");
octaveGroup->add(&octaveExecutable);
octaveGroup->add(&octaveShowHeaderInfoWhenExecutingScripts);
caf::PdmUiGroup* octaveGroup = uiOrdering.addNewGroup( "Octave" );
octaveGroup->add( &octaveExecutable );
octaveGroup->add( &octaveShowHeaderInfoWhenExecutingScripts );
#ifdef ENABLE_GRPC
caf::PdmUiGroup* pythonGroup = uiOrdering.addNewGroup("Python");
pythonGroup->add(&enableGrpcServer);
pythonGroup->add(&showPythonDebugInfo);
pythonGroup->add(&defaultGrpcPortNumber);
pythonGroup->add(&pythonExecutable);
caf::PdmUiGroup* pythonGroup = uiOrdering.addNewGroup( "Python" );
pythonGroup->add( &enableGrpcServer );
pythonGroup->add( &showPythonDebugInfo );
pythonGroup->add( &defaultGrpcPortNumber );
pythonGroup->add( &pythonExecutable );
#endif
caf::PdmUiGroup* scriptGroup = uiOrdering.addNewGroup("Script files");
scriptGroup->add(&scriptDirectories);
scriptGroup->add(&scriptEditorExecutable);
caf::PdmUiGroup* scriptGroup = uiOrdering.addNewGroup( "Script files" );
scriptGroup->add( &scriptDirectories );
scriptGroup->add( &scriptEditorExecutable );
}
else if (uiConfigName == RiaPreferences::tabNameExport())
else if ( uiConfigName == RiaPreferences::tabNameExport() )
{
uiOrdering.add(&csvTextExportFieldSeparator);
uiOrdering.add( &csvTextExportFieldSeparator );
}
else if (RiaApplication::enableDevelopmentFeatures() && uiConfigName == RiaPreferences::tabNameSystem())
else if ( RiaApplication::enableDevelopmentFeatures() && uiConfigName == RiaPreferences::tabNameSystem() )
{
uiOrdering.add(&m_appendClassNameToUiText);
uiOrdering.add(&m_appendFieldKeywordToToolTipText);
uiOrdering.add( &m_appendClassNameToUiText );
uiOrdering.add( &m_appendFieldKeywordToToolTipText );
uiOrdering.add(&m_showProjectChangedDialog);
uiOrdering.add( &m_showProjectChangedDialog );
uiOrdering.add(&m_showTestToolbar);
uiOrdering.add(&m_includeFractureDebugInfoFile);
uiOrdering.add(&m_holoLensExportFolder);
uiOrdering.add( &m_showTestToolbar );
uiOrdering.add( &m_includeFractureDebugInfoFile );
uiOrdering.add( &m_holoLensExportFolder );
}
uiOrdering.skipRemainingFields(true);
uiOrdering.skipRemainingFields( true );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo> RiaPreferences::calculateValueOptions(const caf::PdmFieldHandle* fieldNeedingOptions, bool * useOptionsOnly)
QList<caf::PdmOptionItemInfo> RiaPreferences::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly )
{
QList<caf::PdmOptionItemInfo> options;
*useOptionsOnly = true;
if (fieldNeedingOptions == &gridImportMode)
if ( fieldNeedingOptions == &gridImportMode )
{
// Manual option handling in order to one only a subset of the enum values
SummaryRestartFilesImportModeType skip(RiaPreferences::NOT_IMPORT);
SummaryRestartFilesImportModeType separate(RiaPreferences::SEPARATE_CASES);
SummaryRestartFilesImportModeType skip( RiaPreferences::NOT_IMPORT );
SummaryRestartFilesImportModeType separate( RiaPreferences::SEPARATE_CASES );
options.push_back(caf::PdmOptionItemInfo(skip.uiText(), RiaPreferences::NOT_IMPORT));
options.push_back(caf::PdmOptionItemInfo(separate.uiText(), RiaPreferences::SEPARATE_CASES));
options.push_back( caf::PdmOptionItemInfo( skip.uiText(), RiaPreferences::NOT_IMPORT ) );
options.push_back( caf::PdmOptionItemInfo( separate.uiText(), RiaPreferences::SEPARATE_CASES ) );
}
else if (fieldNeedingOptions == &summaryEnsembleImportMode)
else if ( fieldNeedingOptions == &summaryEnsembleImportMode )
{
// Manual option handling in order to one only a subset of the enum values
SummaryRestartFilesImportModeType skip(RiaPreferences::NOT_IMPORT);
SummaryRestartFilesImportModeType allowImport(RiaPreferences::IMPORT);
SummaryRestartFilesImportModeType skip( RiaPreferences::NOT_IMPORT );
SummaryRestartFilesImportModeType allowImport( RiaPreferences::IMPORT );
options.push_back(caf::PdmOptionItemInfo(skip.uiText(), RiaPreferences::NOT_IMPORT));
options.push_back(caf::PdmOptionItemInfo(allowImport.uiText(), RiaPreferences::IMPORT));
options.push_back( caf::PdmOptionItemInfo( skip.uiText(), RiaPreferences::NOT_IMPORT ) );
options.push_back( caf::PdmOptionItemInfo( allowImport.uiText(), RiaPreferences::IMPORT ) );
}
else if (fieldNeedingOptions == &m_dateFormat)
else if ( fieldNeedingOptions == &m_dateFormat )
{
for (auto dateFormat : RiaQDateTimeTools::supportedDateFormats())
for ( auto dateFormat : RiaQDateTimeTools::supportedDateFormats() )
{
QDate exampleDate = QDate(2019, 8, 16);
QString fullDateFormat =
RiaQDateTimeTools::dateFormatString(dateFormat, RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY);
QString uiText = QString("%1 (%2)").arg(fullDateFormat).arg(exampleDate.toString(fullDateFormat));
uiText.replace("AP", "AM/PM");
options.push_back(caf::PdmOptionItemInfo(uiText, QVariant::fromValue(dateFormat)));
QDate exampleDate = QDate( 2019, 8, 16 );
QString fullDateFormat = RiaQDateTimeTools::dateFormatString( dateFormat,
RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY );
QString uiText = QString( "%1 (%2)" ).arg( fullDateFormat ).arg( exampleDate.toString( fullDateFormat ) );
uiText.replace( "AP", "AM/PM" );
options.push_back( caf::PdmOptionItemInfo( uiText, QVariant::fromValue( dateFormat ) ) );
}
}
else if (fieldNeedingOptions == &m_timeFormat)
else if ( fieldNeedingOptions == &m_timeFormat )
{
for (auto timeFormat : RiaQDateTimeTools::supportedTimeFormats())
for ( auto timeFormat : RiaQDateTimeTools::supportedTimeFormats() )
{
QTime exampleTime = QTime(15, 48, 22);
QTime exampleTime = QTime( 15, 48, 22 );
QString timeFormatString =
RiaQDateTimeTools::timeFormatString(timeFormat, RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND);
QString uiText = QString("%1 (%2)").arg(timeFormatString).arg(exampleTime.toString(timeFormatString));
uiText.replace("AP", "AM/PM");
options.push_back(caf::PdmOptionItemInfo(uiText, QVariant::fromValue(timeFormat)));
RiaQDateTimeTools::timeFormatString( timeFormat, RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND );
QString uiText = QString( "%1 (%2)" ).arg( timeFormatString ).arg( exampleTime.toString( timeFormatString ) );
uiText.replace( "AP", "AM/PM" );
options.push_back( caf::PdmOptionItemInfo( uiText, QVariant::fromValue( timeFormat ) ) );
}
}
@@ -406,10 +520,10 @@ QList<caf::PdmOptionItemInfo> RiaPreferences::calculateValueOptions(const caf::P
void RiaPreferences::initAfterRead()
{
// If the stored font size is larger than the maximum enum value, the stored font size is actually point size
int defaultSceneFontEnumValue = static_cast<int>(defaultSceneFontSize.v());
if (defaultSceneFontEnumValue > (int) RiaFontCache::MAX_FONT_SIZE)
int defaultSceneFontEnumValue = static_cast<int>( defaultSceneFontSize.v() );
if ( defaultSceneFontEnumValue > (int)RiaFontCache::MAX_FONT_SIZE )
{
defaultSceneFontSize = RiaFontCache::fontSizeEnumFromPointSize(defaultSceneFontEnumValue);
defaultSceneFontSize = RiaFontCache::fontSizeEnumFromPointSize( defaultSceneFontEnumValue );
}
}
@@ -432,7 +546,7 @@ QString RiaPreferences::tabNameEclipse()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaPreferences::tabNamePlotting()
QString RiaPreferences::tabNamePlotting()
{
return "Plotting";
}
@@ -462,7 +576,7 @@ QString RiaPreferences::tabNameSystem()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QStringList RiaPreferences::tabNames()
{
@@ -474,7 +588,7 @@ QStringList RiaPreferences::tabNames()
names << tabNameScripting();
names << tabNameExport();
if (RiaApplication::enableDevelopmentFeatures())
if ( RiaApplication::enableDevelopmentFeatures() )
{
names << tabNameSystem();
}
@@ -483,7 +597,7 @@ QStringList RiaPreferences::tabNames()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const RifReaderSettings* RiaPreferences::readerSettings() const
{
@@ -523,11 +637,11 @@ bool RiaPreferences::includeFractureDebugInfoFile() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaPreferences::showProjectChangedDialog() const
{
if (!RiaApplication::enableDevelopmentFeatures())
if ( !RiaApplication::enableDevelopmentFeatures() )
{
return true;
}
@@ -536,7 +650,7 @@ bool RiaPreferences::showProjectChangedDialog() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaPreferences::holoLensExportFolder() const
{

View File

@@ -4,17 +4,17 @@
// Copyright (C) 2011-2018 Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,9 +22,9 @@
#pragma once
#include "RiaApplication.h"
#include "RiaGuiApplication.h"
#include "RiaDefines.h"
#include "RiaFontCache.h"
#include "RiaGuiApplication.h"
#include "RiaQDateTimeTools.h"
#include "cafAppEnum.h"
@@ -33,7 +33,7 @@
#include "cafPdmObject.h"
// Include to make Pdm work for cvf::Color
#include "cafPdmFieldCvfColor.h"
#include "cafPdmFieldCvfColor.h"
#include <map>
@@ -44,9 +44,14 @@ class RiaPreferences : public caf::PdmObject
CAF_PDM_HEADER_INIT;
public:
enum SummaryRestartFilesImportMode { IMPORT, NOT_IMPORT, SEPARATE_CASES };
enum SummaryRestartFilesImportMode
{
IMPORT,
NOT_IMPORT,
SEPARATE_CASES
};
typedef caf::AppEnum<SummaryRestartFilesImportMode> SummaryRestartFilesImportModeType;
typedef RiaFontCache::FontSizeType FontSizeType;
typedef RiaFontCache::FontSizeType FontSizeType;
enum SummaryHistoryCurveStyleMode
{
@@ -56,19 +61,19 @@ public:
};
typedef caf::AppEnum<SummaryHistoryCurveStyleMode> SummaryHistoryCurveStyleModeType;
RiaPreferences(void);
~RiaPreferences(void) override;
RiaPreferences( void );
~RiaPreferences( void ) override;
QStringList tabNames();
const RifReaderSettings* readerSettings() const;
// Debug settings
bool appendClassNameToUiText() const;
bool appendFieldKeywordToToolTipText() const;
bool showTestToolbar() const;
bool includeFractureDebugInfoFile() const;
bool showProjectChangedDialog() const;
bool appendClassNameToUiText() const;
bool appendFieldKeywordToToolTipText() const;
bool showTestToolbar() const;
bool includeFractureDebugInfoFile() const;
bool showProjectChangedDialog() const;
QString holoLensExportFolder() const;
const QString& dateFormat() const;
@@ -77,21 +82,21 @@ public:
std::map<RiaDefines::FontSettingType, RiaFontCache::FontSize> defaultFontSizes() const;
public: // Pdm Fields
caf::PdmField<caf::AppEnum< RiaGuiApplication::RINavigationPolicy > > navigationPolicy;
caf::PdmField<caf::AppEnum<RiaGuiApplication::RINavigationPolicy>> navigationPolicy;
caf::PdmField<bool> enableGrpcServer;
caf::PdmField<int> defaultGrpcPortNumber;
caf::PdmField<bool> enableGrpcServer;
caf::PdmField<int> defaultGrpcPortNumber;
caf::PdmField<QString> scriptDirectories;
caf::PdmField<QString> scriptEditorExecutable;
caf::PdmField<QString> scriptDirectories;
caf::PdmField<QString> scriptEditorExecutable;
caf::PdmField<QString> octaveExecutable;
caf::PdmField<bool> octaveShowHeaderInfoWhenExecutingScripts;
caf::PdmField<QString> pythonExecutable;
caf::PdmField<bool> showPythonDebugInfo;
caf::PdmField<QString> octaveExecutable;
caf::PdmField<bool> octaveShowHeaderInfoWhenExecutingScripts;
caf::PdmField<QString> ssihubAddress;
caf::PdmField<QString> pythonExecutable;
caf::PdmField<bool> showPythonDebugInfo;
caf::PdmField<QString> ssihubAddress;
caf::PdmField<caf::AppEnum<RiaDefines::MeshModeType>> defaultMeshModeType;
@@ -106,33 +111,37 @@ public: // Pdm Fields
caf::PdmField<FontSizeType> defaultWellLabelFontSize;
caf::PdmField<FontSizeType> defaultAnnotationFontSize;
caf::PdmField<FontSizeType> defaultPlotFontSize;
caf::PdmField<bool> showLegendBackground;
caf::PdmField<bool> useShaders;
caf::PdmField<bool> showHud;
caf::PdmField<bool> showLegendBackground;
caf::PdmField<QString> lastUsedProjectFileName;
caf::PdmField<bool> useShaders;
caf::PdmField<bool> showHud;
caf::PdmField<bool> autocomputeDepthRelatedProperties;
caf::PdmField<bool> loadAndShowSoil;
caf::PdmField<QString> lastUsedProjectFileName;
caf::PdmField<bool> summaryRestartFilesShowImportDialog;
caf::PdmField<SummaryRestartFilesImportModeType> summaryImportMode;
caf::PdmField<SummaryRestartFilesImportModeType> gridImportMode;
caf::PdmField<SummaryRestartFilesImportModeType> summaryEnsembleImportMode;
caf::PdmField<bool> autocomputeDepthRelatedProperties;
caf::PdmField<bool> loadAndShowSoil;
caf::PdmField<bool> summaryRestartFilesShowImportDialog;
caf::PdmField<SummaryRestartFilesImportModeType> summaryImportMode;
caf::PdmField<SummaryRestartFilesImportModeType> gridImportMode;
caf::PdmField<SummaryRestartFilesImportModeType> summaryEnsembleImportMode;
caf::PdmField<QString> defaultSummaryCurvesTextFilter;
caf::PdmField<SummaryHistoryCurveStyleModeType> defaultSummaryHistoryCurveStyle;
caf::PdmField<bool> holoLensDisableCertificateVerification;
caf::PdmField<QString> csvTextExportFieldSeparator;
caf::PdmField<bool> holoLensDisableCertificateVerification;
caf::PdmField<QString> csvTextExportFieldSeparator;
protected:
void defineEditorAttribute(const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute) override;
void defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering) override;
QList<caf::PdmOptionItemInfo> calculateValueOptions(const caf::PdmFieldHandle* fieldNeedingOptions, bool * useOptionsOnly) override;
void initAfterRead() override;
void defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute ) override;
void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override;
QList<caf::PdmOptionItemInfo> calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions,
bool* useOptionsOnly ) override;
void initAfterRead() override;
private:
static QString tabNameGeneral();
static QString tabNameEclipse();
@@ -146,12 +155,12 @@ private:
caf::PdmField<bool> m_appendClassNameToUiText;
caf::PdmField<bool> m_appendFieldKeywordToToolTipText;
caf::PdmField<bool> m_showProjectChangedDialog;
caf::PdmField<bool> m_showProjectChangedDialog;
caf::PdmField<bool> m_showTestToolbar;
caf::PdmField<bool> m_includeFractureDebugInfoFile;
caf::PdmField<QString> m_holoLensExportFolder;
caf::PdmField<QString> m_dateFormat;
caf::PdmField<QString> m_timeFormat;
QStringList m_tabNames;
caf::PdmField<bool> m_showTestToolbar;
caf::PdmField<bool> m_includeFractureDebugInfoFile;
caf::PdmField<QString> m_holoLensExportFolder;
caf::PdmField<QString> m_dateFormat;
caf::PdmField<QString> m_timeFormat;
QStringList m_tabNames;
};

View File

@@ -21,10 +21,12 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRftPltCurveDefinition::RiaRftPltCurveDefinition(const RifDataSourceForRftPlt& address, const QString& wellName, const QDateTime& timeStep)
: m_curveAddress(address)
, m_wellName(wellName)
, m_timeStep(timeStep)
RiaRftPltCurveDefinition::RiaRftPltCurveDefinition( const RifDataSourceForRftPlt& address,
const QString& wellName,
const QDateTime& timeStep )
: m_curveAddress( address )
, m_wellName( wellName )
, m_timeStep( timeStep )
{
}
@@ -55,15 +57,15 @@ const QDateTime& RiaRftPltCurveDefinition::timeStep() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaRftPltCurveDefinition::operator<(const RiaRftPltCurveDefinition& other) const
bool RiaRftPltCurveDefinition::operator<( const RiaRftPltCurveDefinition& other ) const
{
if (m_curveAddress == other.m_curveAddress)
{
if (m_wellName == other.m_wellName)
{
if ( m_curveAddress == other.m_curveAddress )
{
if ( m_wellName == other.m_wellName )
{
return m_timeStep < other.m_timeStep;
}
}
return m_wellName < other.m_wellName;
}
}
return m_curveAddress < other.m_curveAddress;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -28,18 +28,20 @@
class RimSummaryCase;
//==================================================================================================
///
///
//==================================================================================================
class RiaRftPltCurveDefinition
{
public:
explicit RiaRftPltCurveDefinition(const RifDataSourceForRftPlt& address, const QString& wellName, const QDateTime& timeStep);
explicit RiaRftPltCurveDefinition( const RifDataSourceForRftPlt& address,
const QString& wellName,
const QDateTime& timeStep );
const RifDataSourceForRftPlt& address() const;
const QString& wellName() const;
const QDateTime& timeStep() const;
const RifDataSourceForRftPlt& address() const;
const QString& wellName() const;
const QDateTime& timeStep() const;
bool operator < (const RiaRftPltCurveDefinition& other) const;
bool operator<( const RiaRftPltCurveDefinition& other ) const;
private:
RifDataSourceForRftPlt m_curveAddress;

View File

@@ -26,8 +26,8 @@
///
//--------------------------------------------------------------------------------------------------
RiaSummaryCurveDefinition::RiaSummaryCurveDefinition()
: m_summaryCase(nullptr)
, m_ensemble(nullptr)
: m_summaryCase( nullptr )
, m_ensemble( nullptr )
{
}
@@ -35,12 +35,12 @@ RiaSummaryCurveDefinition::RiaSummaryCurveDefinition()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaSummaryCurveDefinition::RiaSummaryCurveDefinition(RimSummaryCase* summaryCase,
const RifEclipseSummaryAddress& summaryAddress,
RimSummaryCaseCollection* ensemble)
: m_summaryCase(summaryCase)
, m_ensemble(ensemble)
, m_summaryAddress(summaryAddress)
RiaSummaryCurveDefinition::RiaSummaryCurveDefinition( RimSummaryCase* summaryCase,
const RifEclipseSummaryAddress& summaryAddress,
RimSummaryCaseCollection* ensemble )
: m_summaryCase( summaryCase )
, m_ensemble( ensemble )
, m_summaryAddress( summaryAddress )
{
}
@@ -79,33 +79,34 @@ bool RiaSummaryCurveDefinition::isEnsembleCurve() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveDefinition::resultValues(const RiaSummaryCurveDefinition& curveDefinition, std::vector<double>* values)
void RiaSummaryCurveDefinition::resultValues( const RiaSummaryCurveDefinition& curveDefinition,
std::vector<double>* values )
{
CVF_ASSERT(values);
CVF_ASSERT( values );
if (!curveDefinition.summaryAddress().isValid()) return;
if (!curveDefinition.summaryCase()) return;
if ( !curveDefinition.summaryAddress().isValid() ) return;
if ( !curveDefinition.summaryCase() ) return;
RifSummaryReaderInterface* reader = curveDefinition.summaryCase()->summaryReader();
if (!reader) return;
if ( !reader ) return;
reader->values(curveDefinition.summaryAddress(), values);
reader->values( curveDefinition.summaryAddress(), values );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
const std::vector<time_t>& RiaSummaryCurveDefinition::timeSteps(const RiaSummaryCurveDefinition& curveDefinition)
const std::vector<time_t>& RiaSummaryCurveDefinition::timeSteps( const RiaSummaryCurveDefinition& curveDefinition )
{
static std::vector<time_t> dummy;
if (!curveDefinition.summaryAddress().isValid()) return dummy;
if (!curveDefinition.summaryCase()) return dummy;
if ( !curveDefinition.summaryAddress().isValid() ) return dummy;
if ( !curveDefinition.summaryCase() ) return dummy;
RifSummaryReaderInterface* reader = curveDefinition.summaryCase()->summaryReader();
if (!reader) return dummy;
if ( !reader ) return dummy;
return reader->timeSteps(curveDefinition.summaryAddress());
return reader->timeSteps( curveDefinition.summaryAddress() );
}
//--------------------------------------------------------------------------------------------------
@@ -114,25 +115,26 @@ const std::vector<time_t>& RiaSummaryCurveDefinition::timeSteps(const RiaSummary
QString RiaSummaryCurveDefinition::curveDefinitionText() const
{
QString caseName;
if (summaryCase())
if ( summaryCase() )
caseName = summaryCase()->caseName();
else if (ensemble())
else if ( ensemble() )
caseName = ensemble()->name();
return RiaSummaryCurveDefinition::curveDefinitionText(caseName, summaryAddress());
return RiaSummaryCurveDefinition::curveDefinitionText( caseName, summaryAddress() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaSummaryCurveDefinition::curveDefinitionText(const QString& caseName, const RifEclipseSummaryAddress& summaryAddress)
QString RiaSummaryCurveDefinition::curveDefinitionText( const QString& caseName,
const RifEclipseSummaryAddress& summaryAddress )
{
QString txt;
txt += caseName;
txt += ", ";
txt += QString::fromStdString(summaryAddress.uiText());
txt += QString::fromStdString( summaryAddress.uiText() );
return txt;
}
@@ -140,25 +142,25 @@ QString RiaSummaryCurveDefinition::curveDefinitionText(const QString& caseName,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaSummaryCurveDefinition::operator<(const RiaSummaryCurveDefinition& other) const
bool RiaSummaryCurveDefinition::operator<( const RiaSummaryCurveDefinition& other ) const
{
if (m_ensemble != other.ensemble())
if ( m_ensemble != other.ensemble() )
{
QString ensembleName;
QString otherEnsembleName;
if (m_ensemble)
if ( m_ensemble )
{
ensembleName = m_ensemble->name();
}
if (other.ensemble())
if ( other.ensemble() )
{
otherEnsembleName = other.ensemble()->name();
}
// First check if names are different to ensure stable alphabetic sort
if (ensembleName != otherEnsembleName)
if ( ensembleName != otherEnsembleName )
{
return ensembleName < otherEnsembleName;
}
@@ -167,22 +169,22 @@ bool RiaSummaryCurveDefinition::operator<(const RiaSummaryCurveDefinition& other
return m_ensemble < other.ensemble();
}
if (m_summaryCase != other.summaryCase())
if ( m_summaryCase != other.summaryCase() )
{
QString summaryCaseName;
QString otherSummaryCaseName;
if (m_summaryCase)
if ( m_summaryCase )
{
summaryCaseName = m_summaryCase->caseName();
}
if (other.summaryCase())
if ( other.summaryCase() )
{
otherSummaryCaseName = other.summaryCase()->caseName();
}
// First check if names are different to ensure stable alphabetic sort
if (summaryCaseName != otherSummaryCaseName)
if ( summaryCaseName != otherSummaryCaseName )
{
return summaryCaseName < otherSummaryCaseName;
}
@@ -191,5 +193,5 @@ bool RiaSummaryCurveDefinition::operator<(const RiaSummaryCurveDefinition& other
return m_summaryCase < other.summaryCase();
}
return (m_summaryAddress < other.summaryAddress());
return ( m_summaryAddress < other.summaryAddress() );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -29,35 +29,34 @@ class RimSummaryCase;
class RimSummaryCaseCollection;
//==================================================================================================
///
///
//==================================================================================================
class RiaSummaryCurveDefinition
{
public:
RiaSummaryCurveDefinition();
explicit RiaSummaryCurveDefinition(RimSummaryCase* summaryCase,
const RifEclipseSummaryAddress& summaryAddress,
RimSummaryCaseCollection* ensemble = nullptr);
explicit RiaSummaryCurveDefinition( RimSummaryCase* summaryCase,
const RifEclipseSummaryAddress& summaryAddress,
RimSummaryCaseCollection* ensemble = nullptr );
RimSummaryCase* summaryCase() const;
const RifEclipseSummaryAddress& summaryAddress() const;
RimSummaryCaseCollection* ensemble() const;
bool isEnsembleCurve() const;
bool operator < (const RiaSummaryCurveDefinition& other) const;
bool operator<( const RiaSummaryCurveDefinition& other ) const;
// TODO: Consider moving to a separate tools class
static void resultValues(const RiaSummaryCurveDefinition& curveDefinition, std::vector<double>* values);
static const std::vector<time_t>& timeSteps(const RiaSummaryCurveDefinition& curveDefinition);
static void resultValues( const RiaSummaryCurveDefinition& curveDefinition, std::vector<double>* values );
static const std::vector<time_t>& timeSteps( const RiaSummaryCurveDefinition& curveDefinition );
QString curveDefinitionText() const;
QString curveDefinitionText() const;
static QString curveDefinitionText(const QString& caseName, const RifEclipseSummaryAddress& summaryAddress);
static QString curveDefinitionText( const QString& caseName, const RifEclipseSummaryAddress& summaryAddress );
private:
private:
RimSummaryCase* m_summaryCase;
RifEclipseSummaryAddress m_summaryAddress;
RimSummaryCaseCollection* m_ensemble;
RimSummaryCase* m_summaryCase;
RifEclipseSummaryAddress m_summaryAddress;
RimSummaryCaseCollection* m_ensemble;
};

View File

@@ -19,31 +19,30 @@
#include "RiaViewRedrawScheduler.h"
#include "Rim3dView.h"
#include <QTimer>
#include <QCoreApplication>
#include <QTimer>
#include <set>
#include "cafProgressState.h"
#include <set>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaViewRedrawScheduler* RiaViewRedrawScheduler::instance()
{
static RiaViewRedrawScheduler theInstance;
static RiaViewRedrawScheduler theInstance;
return &theInstance;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaViewRedrawScheduler::clearViewsScheduledForUpdate()
{
if (m_resViewUpdateTimer)
if ( m_resViewUpdateTimer )
{
while (m_resViewUpdateTimer->isActive())
while ( m_resViewUpdateTimer->isActive() )
{
QCoreApplication::processEvents();
}
@@ -51,39 +50,37 @@ void RiaViewRedrawScheduler::clearViewsScheduledForUpdate()
m_resViewsToUpdate.clear();
}
//--------------------------------------------------------------------------------------------------
/// Schedule a creation of the Display model and redraw of the reservoir view
/// The redraw will happen as soon as the event loop is entered
//--------------------------------------------------------------------------------------------------
void RiaViewRedrawScheduler::scheduleDisplayModelUpdateAndRedraw(Rim3dView* resViewToUpdate)
void RiaViewRedrawScheduler::scheduleDisplayModelUpdateAndRedraw( Rim3dView* resViewToUpdate )
{
m_resViewsToUpdate.push_back(resViewToUpdate);
m_resViewsToUpdate.push_back( resViewToUpdate );
startTimer(0);
startTimer( 0 );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaViewRedrawScheduler::startTimer(int msecs)
void RiaViewRedrawScheduler::startTimer( int msecs )
{
if (!m_resViewUpdateTimer)
if ( !m_resViewUpdateTimer )
{
m_resViewUpdateTimer = new QTimer(this);
connect(m_resViewUpdateTimer, SIGNAL(timeout()), this, SLOT(slotUpdateAndRedrawScheduledViewsWhenReady()));
m_resViewUpdateTimer = new QTimer( this );
connect( m_resViewUpdateTimer, SIGNAL( timeout() ), this, SLOT( slotUpdateAndRedrawScheduledViewsWhenReady() ) );
}
if (!m_resViewUpdateTimer->isActive())
if ( !m_resViewUpdateTimer->isActive() )
{
m_resViewUpdateTimer->setSingleShot(true);
m_resViewUpdateTimer->start(msecs);
m_resViewUpdateTimer->setSingleShot( true );
m_resViewUpdateTimer->start( msecs );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaViewRedrawScheduler::updateAndRedrawScheduledViews()
{
@@ -93,29 +90,31 @@ void RiaViewRedrawScheduler::updateAndRedrawScheduledViews()
std::set<Rim3dView*> independent3DViewsToUpdate;
std::set<Rim3dView*> dependent3DViewsToUpdate;
for (size_t i = 0; i < m_resViewsToUpdate.size(); ++i)
for ( size_t i = 0; i < m_resViewsToUpdate.size(); ++i )
{
if (!m_resViewsToUpdate[i]) continue;
if ( !m_resViewsToUpdate[i] ) continue;
if (m_resViewsToUpdate[i]->viewController())
dependent3DViewsToUpdate.insert(m_resViewsToUpdate[i]);
if ( m_resViewsToUpdate[i]->viewController() )
dependent3DViewsToUpdate.insert( m_resViewsToUpdate[i] );
else
independent3DViewsToUpdate.insert(m_resViewsToUpdate[i]);
independent3DViewsToUpdate.insert( m_resViewsToUpdate[i] );
}
for (std::set<Rim3dView*>::iterator it = independent3DViewsToUpdate.begin(); it != independent3DViewsToUpdate.end(); ++it )
for ( std::set<Rim3dView*>::iterator it = independent3DViewsToUpdate.begin(); it != independent3DViewsToUpdate.end();
++it )
{
if (*it)
if ( *it )
{
(*it)->createDisplayModelAndRedraw();
( *it )->createDisplayModelAndRedraw();
}
}
for (std::set<Rim3dView*>::iterator it = dependent3DViewsToUpdate.begin(); it != dependent3DViewsToUpdate.end(); ++it)
for ( std::set<Rim3dView*>::iterator it = dependent3DViewsToUpdate.begin(); it != dependent3DViewsToUpdate.end();
++it )
{
if (*it)
if ( *it )
{
(*it)->createDisplayModelAndRedraw();
( *it )->createDisplayModelAndRedraw();
}
}
@@ -123,13 +122,13 @@ void RiaViewRedrawScheduler::updateAndRedrawScheduledViews()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaViewRedrawScheduler::slotUpdateAndRedrawScheduledViewsWhenReady()
{
if ( caf::ProgressState::isActive() )
{
startTimer(100);
startTimer( 100 );
return;
}
@@ -137,7 +136,7 @@ void RiaViewRedrawScheduler::slotUpdateAndRedrawScheduledViewsWhenReady()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaViewRedrawScheduler::~RiaViewRedrawScheduler()
{

View File

@@ -18,37 +18,38 @@
#pragma once
#include "cafPdmPointer.h"
#include <QObject>
#include <vector>
#include "cafPdmPointer.h"
class QTimer;
class Rim3dView;
class RiaViewRedrawScheduler : public QObject
{
Q_OBJECT;
public:
static RiaViewRedrawScheduler* instance();
void scheduleDisplayModelUpdateAndRedraw(Rim3dView* resViewToUpdate);
void clearViewsScheduledForUpdate();
void updateAndRedrawScheduledViews();
void scheduleDisplayModelUpdateAndRedraw( Rim3dView* resViewToUpdate );
void clearViewsScheduledForUpdate();
void updateAndRedrawScheduledViews();
private slots:
void slotUpdateAndRedrawScheduledViewsWhenReady();
void slotUpdateAndRedrawScheduledViewsWhenReady();
private:
void startTimer(int msecs);
void startTimer( int msecs );
RiaViewRedrawScheduler() : m_resViewUpdateTimer(nullptr) {}
RiaViewRedrawScheduler()
: m_resViewUpdateTimer( nullptr )
{
}
~RiaViewRedrawScheduler() override;
RiaViewRedrawScheduler(const RiaViewRedrawScheduler& o) = delete;
void operator=(const RiaViewRedrawScheduler& o) = delete;
RiaViewRedrawScheduler( const RiaViewRedrawScheduler& o ) = delete;
void operator=( const RiaViewRedrawScheduler& o ) = delete;
std::vector<caf::PdmPointer<Rim3dView> > m_resViewsToUpdate;
QTimer* m_resViewUpdateTimer;
std::vector<caf::PdmPointer<Rim3dView>> m_resViewsToUpdate;
QTimer* m_resViewUpdateTimer;
};

View File

@@ -48,91 +48,105 @@
#include <QString>
#include <QStringList>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaArgumentParser::parseArguments(cvf::ProgramOptions* progOpt)
bool RiaArgumentParser::parseArguments( cvf::ProgramOptions* progOpt )
{
CVF_ASSERT(progOpt);
progOpt->registerOption("help", "", "Displays help text and exits.");
progOpt->registerOption("?", "", "Displays help text and exits.");
CVF_ASSERT( progOpt );
progOpt->registerOption( "help", "", "Displays help text and exits." );
progOpt->registerOption( "?", "", "Displays help text and exits." );
progOpt->registerOption("project", "<filename>", "Open project file <filename>.", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("last", "", "Open last used project.");
progOpt->registerOption("case",
"<casename|filename> [<casename|filename> ...]",
"Imports the Eclipse cases specified by case name with or without extension."
"If <casename>, import the corresponding grid file and summary file"
"If <filename> has extension .GRRID/.EGRID, import the grid file and corresponding summary file"
"If <filename> has extension .SMSPEC, import the summary file (does not open the corresponding grid file)",
cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption("size", "<width> <height>", "Set size of the main application window.", cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption("console", "", "Launch as a console application without graphics");
progOpt->registerOption("server", "[<portnumber>]", "Launch as a GRPC server. Default port is 50051", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("startdir", "<folder>", "Set startup directory.\n", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "project", "<filename>", "Open project file <filename>.", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "last", "", "Open last used project." );
progOpt->registerOption( "case",
"<casename|filename> [<casename|filename> ...]",
"Imports the Eclipse cases specified by case name with or without extension."
"If <casename>, import the corresponding grid file and summary file"
"If <filename> has extension .GRRID/.EGRID, import the grid file and corresponding "
"summary file"
"If <filename> has extension .SMSPEC, import the summary file (does not open the "
"corresponding grid file)",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption( "size",
"<width> <height>",
"Set size of the main application window.",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption( "console", "", "Launch as a console application without graphics" );
progOpt->registerOption( "server",
"[<portnumber>]",
"Launch as a GRPC server. Default port is 50051",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "startdir", "<folder>", "Set startup directory.\n", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("summaryplot",
"[<plotOptions>] <eclipsesummaryvectors> [<eclipsedatafiles>]",
"Creates a summary plot using all the <eclipsedatafiles>,"
"and all the summary vectors defined in <eclipsesummaryvectors>."
"Use --summaryplot -help to show a more detailed help text.\n",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE);
progOpt->registerOption( "summaryplot",
"[<plotOptions>] <eclipsesummaryvectors> [<eclipsedatafiles>]",
"Creates a summary plot using all the <eclipsedatafiles>,"
"and all the summary vectors defined in <eclipsesummaryvectors>."
"Use --summaryplot -help to show a more detailed help text.\n",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE );
progOpt->registerOption("commandFile", "<commandfile>", "Execute the command file.", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("commandFileReplaceCases",
"[<caseId>] <caseListFile>",
"Supply list of cases to replace in project, performing command file for each case.",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("commandFileProject",
"<filename>",
"Project to use if performing case looping for command file. Used in conjunction with 'commandFileReplaceCases'.\n",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "commandFile",
"<commandfile>",
"Execute the command file.",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "commandFileReplaceCases",
"[<caseId>] <caseListFile>",
"Supply list of cases to replace in project, performing command file for each case.",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "commandFileProject",
"<filename>",
"Project to use if performing case looping for command file. Used in conjunction with "
"'commandFileReplaceCases'.\n",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("savesnapshots",
"all|views|plots",
"Save snapshot of all views or plots to project file location sub folder 'snapshots'. Option 'all' "
"will include both views and plots. Application closes after snapshots have been written.",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE);
progOpt->registerOption("multiCaseSnapshots",
"<gridListFile>",
"For each grid file listed in the <gridListFile> file, replace the first case in the project and save "
"snapshots of all views.\n",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "savesnapshots",
"all|views|plots",
"Save snapshot of all views or plots to project file location sub folder 'snapshots'. "
"Option 'all' "
"will include both views and plots. Application closes after snapshots have been written.",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE );
progOpt->registerOption( "multiCaseSnapshots",
"<gridListFile>",
"For each grid file listed in the <gridListFile> file, replace the first case in the "
"project and save "
"snapshots of all views.\n",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("replaceCase",
"[<caseId>] <newGridFile>",
"Replace grid in <caseId> or first case with <newgridFile>. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED);
progOpt->registerOption("replaceSourceCases",
"[<caseGroupId>] <gridListFile>",
"Replace source cases in <caseGroupId> or first grid case group with the grid files listed in the "
"<gridListFile> file. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED);
progOpt->registerOption("replacePropertiesFolder",
"[<caseId>] <newPropertiesFolder>",
"Replace the folder containing property files for an eclipse input case.\n",
cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption( "replaceCase",
"[<caseId>] <newGridFile>",
"Replace grid in <caseId> or first case with <newgridFile>. Repeat parameter for multiple "
"replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED );
progOpt->registerOption( "replaceSourceCases",
"[<caseGroupId>] <gridListFile>",
"Replace source cases in <caseGroupId> or first grid case group with the grid files "
"listed in the "
"<gridListFile> file. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED );
progOpt->registerOption( "replacePropertiesFolder",
"[<caseId>] <newPropertiesFolder>",
"Replace the folder containing property files for an eclipse input case.\n",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption("updateregressiontestbase", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("regressiontest", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "updateregressiontestbase", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "regressiontest", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE );
#ifdef USE_UNIT_TESTS
progOpt->registerOption("unittest", "", "System command");
progOpt->registerOption( "unittest", "", "System command" );
#endif
progOpt->registerOption("ignoreArgs", "", "System command. Ignore all arguments. Mostly for testing purposes");
progOpt->registerOption( "ignoreArgs", "", "System command. Ignore all arguments. Mostly for testing purposes" );
progOpt->setOptionPrefix(cvf::ProgramOptions::DOUBLE_DASH);
progOpt->setOptionPrefix( cvf::ProgramOptions::DOUBLE_DASH );
QStringList arguments = QCoreApplication::arguments();
bool parseOk = progOpt->parse(cvfqt::Utils::toStringVector(arguments));
// If positional parameter functionality is to be supported, the test for existence of positionalParameters must be removed
// This is based on a pull request by @andlaus https://github.com/OPM/ResInsight/pull/162
if (!parseOk || !progOpt->positionalParameters().empty())
bool parseOk = progOpt->parse( cvfqt::Utils::toStringVector( arguments ) );
// If positional parameter functionality is to be supported, the test for existence of positionalParameters must be
// removed This is based on a pull request by @andlaus https://github.com/OPM/ResInsight/pull/162
if ( !parseOk || !progOpt->positionalParameters().empty() )
{
return false;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,12 +26,11 @@ class ProgramOptions;
}
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaArgumentParser
{
public:
static bool parseArguments(cvf::ProgramOptions* progOpt);
static bool parseArguments( cvf::ProgramOptions* progOpt );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,12 +23,12 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::BoundingBox RiaBoundingBoxTools::inflate(const cvf::BoundingBox& boundingBox, double factor)
cvf::BoundingBox RiaBoundingBoxTools::inflate( const cvf::BoundingBox& boundingBox, double factor )
{
cvf::Vec3d center = boundingBox.center();
cvf::Vec3d sizes = boundingBox.extent() * factor;
cvf::Vec3d sizes = boundingBox.extent() * factor;
cvf::Vec3d newMin(center.x() - sizes.x() / 2.0, center.y() - sizes.y() / 2.0, center.z() - sizes.z() / 2.0);
cvf::Vec3d newMax(center.x() + sizes.x() / 2.0, center.y() + sizes.y() / 2.0, center.z() + sizes.z() / 2.0);
return cvf::BoundingBox(newMin, newMax);
cvf::Vec3d newMin( center.x() - sizes.x() / 2.0, center.y() - sizes.y() / 2.0, center.z() - sizes.z() / 2.0 );
cvf::Vec3d newMax( center.x() + sizes.x() / 2.0, center.y() + sizes.y() / 2.0, center.z() + sizes.z() / 2.0 );
return cvf::BoundingBox( newMin, newMax );
}

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,11 +25,11 @@
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaBoundingBoxTools
{
public:
static cvf::BoundingBox inflate(const cvf::BoundingBox& boundingBox, double factor);
static cvf::BoundingBox inflate( const cvf::BoundingBox& boundingBox, double factor );
};

View File

@@ -30,7 +30,7 @@
//--------------------------------------------------------------------------------------------------
/// Splits a line in a number of equal parts
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount);
std::vector<cvf::Vec3d> splitLine( cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount );
//--------------------------------------------------------------------------------------------------
/// Calculates all points on a face described by edge points from all four edges.
@@ -45,71 +45,74 @@ std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t p
/// edgeXPtsLow
///
//--------------------------------------------------------------------------------------------------
std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh);
std::vector<std::vector<cvf::Vec3d>> calcFacePoints( const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d>
RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz)
std::vector<cvf::Vec3d> RiaCellDividingTools::createHexCornerCoords( std::array<cvf::Vec3d, 8> mainCellCorners,
size_t nx,
size_t ny,
size_t nz )
{
std::array<std::pair<size_t, size_t>, 12> edgeCorners = {
std::make_pair(0, 1),
std::make_pair(3, 2),
std::make_pair(4, 5),
std::make_pair(7, 6), // X
std::make_pair(0, 3),
std::make_pair(4, 7),
std::make_pair(1, 2),
std::make_pair(5, 6), // Y
std::make_pair(0, 4),
std::make_pair(1, 5),
std::make_pair(3, 7),
std::make_pair(2, 6), // Z
std::make_pair( 0, 1 ),
std::make_pair( 3, 2 ),
std::make_pair( 4, 5 ),
std::make_pair( 7, 6 ), // X
std::make_pair( 0, 3 ),
std::make_pair( 4, 7 ),
std::make_pair( 1, 2 ),
std::make_pair( 5, 6 ), // Y
std::make_pair( 0, 4 ),
std::make_pair( 1, 5 ),
std::make_pair( 3, 7 ),
std::make_pair( 2, 6 ), // Z
};
std::array<size_t, 3> nxyz = {nx, ny, nz};
std::array<std::vector<cvf::Vec3d>, 12> edgePoints;
for (int i = 0; i < 12; i++)
for ( int i = 0; i < 12; i++ )
{
int partCountsIndex = i / 4;
edgePoints[i] =
splitLine(mainCellCorners[edgeCorners[i].first], mainCellCorners[edgeCorners[i].second], nxyz[partCountsIndex]);
edgePoints[i] = splitLine( mainCellCorners[edgeCorners[i].first],
mainCellCorners[edgeCorners[i].second],
nxyz[partCountsIndex] );
}
// lowIJ, highIJ, lowJK, highKJ,
std::vector<std::vector<std::vector<cvf::Vec3d>>> nodes;
nodes.reserve((nx + 1) * (ny + 1) * (nz + 1));
nodes.reserve( ( nx + 1 ) * ( ny + 1 ) * ( nz + 1 ) );
auto xyFacePtsLow = calcFacePoints(edgePoints[0], edgePoints[1], edgePoints[4], edgePoints[6]);
auto xyFacePtsHigh = calcFacePoints(edgePoints[2], edgePoints[3], edgePoints[5], edgePoints[7]);
auto yzFacePtsLow = calcFacePoints(edgePoints[4], edgePoints[5], edgePoints[8], edgePoints[10]);
auto yzFacePtsHigh = calcFacePoints(edgePoints[6], edgePoints[7], edgePoints[9], edgePoints[11]);
auto xzFacePtsLow = calcFacePoints(edgePoints[0], edgePoints[2], edgePoints[8], edgePoints[9]);
auto xzFacePtsHigh = calcFacePoints(edgePoints[1], edgePoints[3], edgePoints[10], edgePoints[11]);
auto xyFacePtsLow = calcFacePoints( edgePoints[0], edgePoints[1], edgePoints[4], edgePoints[6] );
auto xyFacePtsHigh = calcFacePoints( edgePoints[2], edgePoints[3], edgePoints[5], edgePoints[7] );
auto yzFacePtsLow = calcFacePoints( edgePoints[4], edgePoints[5], edgePoints[8], edgePoints[10] );
auto yzFacePtsHigh = calcFacePoints( edgePoints[6], edgePoints[7], edgePoints[9], edgePoints[11] );
auto xzFacePtsLow = calcFacePoints( edgePoints[0], edgePoints[2], edgePoints[8], edgePoints[9] );
auto xzFacePtsHigh = calcFacePoints( edgePoints[1], edgePoints[3], edgePoints[10], edgePoints[11] );
nodes.push_back(xyFacePtsLow);
nodes.push_back( xyFacePtsLow );
for (size_t z = 1; z < nz; z++)
for ( size_t z = 1; z < nz; z++ )
{
auto xyFacePoints = calcFacePoints(xzFacePtsLow[z], xzFacePtsHigh[z], yzFacePtsLow[z], yzFacePtsHigh[z]);
nodes.push_back(xyFacePoints);
auto xyFacePoints = calcFacePoints( xzFacePtsLow[z], xzFacePtsHigh[z], yzFacePtsLow[z], yzFacePtsHigh[z] );
nodes.push_back( xyFacePoints );
}
nodes.push_back(xyFacePtsHigh);
nodes.push_back( xyFacePtsHigh );
std::vector<cvf::Vec3d> coords;
coords.reserve(nx * ny * nz * 8);
coords.reserve( nx * ny * nz * 8 );
for (size_t z = 1; z < nz + 1; z++)
for ( size_t z = 1; z < nz + 1; z++ )
{
for (size_t y = 1; y < ny + 1; y++)
for ( size_t y = 1; y < ny + 1; y++ )
{
for (size_t x = 1; x < nx + 1; x++)
for ( size_t x = 1; x < nx + 1; x++ )
{
std::array<cvf::Vec3d, 8> cs;
@@ -123,7 +126,7 @@ RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCo
cs[6] = nodes[z][y][x];
cs[7] = nodes[z][y][x - 1];
coords.insert(coords.end(), cs.begin(), cs.end());
coords.insert( coords.end(), cs.begin(), cs.end() );
}
}
}
@@ -133,15 +136,15 @@ RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCo
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>& cellVertices,
const cvf::Vec3d& areaCenter)
double RiaCellDividingTools::computeFlowDistance( const std::array<cvf::Vec3d, 8>& cellVertices,
const cvf::Vec3d& areaCenter )
{
auto subCellCorners = createHexCornerCoords(cellVertices, 2, 2, 2);
auto subCellCorners = createHexCornerCoords( cellVertices, 2, 2, 2 );
double weightedDistanceTotal = 0.0;
double weightTotal = 0.0;
double weightTotal = 0.0;
for (size_t c = 0; c < 8; c++)
for ( size_t c = 0; c < 8; c++ )
{
double weight = 1.0;
weightTotal += weight;
@@ -149,12 +152,13 @@ double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>
cvf::Vec3d centerOfSubCell = cvf::Vec3d::ZERO;
{
cvf::Vec3d vertexSum = cvf::Vec3d::ZERO;
for (size_t v = 0; v < 8; v++) vertexSum += subCellCorners[c * 8 + v];
for ( size_t v = 0; v < 8; v++ )
vertexSum += subCellCorners[c * 8 + v];
centerOfSubCell = vertexSum / 8;
}
auto dist = (centerOfSubCell - areaCenter).length();
weightedDistanceTotal += (dist * weight);
auto dist = ( centerOfSubCell - areaCenter ).length();
weightedDistanceTotal += ( dist * weight );
}
return weightedDistanceTotal / weightTotal;
@@ -163,29 +167,29 @@ double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount)
std::vector<cvf::Vec3d> splitLine( cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount )
{
std::vector<cvf::Vec3d> pts = {ptStart};
for (size_t i = 1; i < partCount; i++)
for ( size_t i = 1; i < partCount; i++ )
{
pts.push_back(cvf::Vec3d(ptStart.x() + (ptEnd.x() - ptStart.x()) * i / partCount,
ptStart.y() + (ptEnd.y() - ptStart.y()) * i / partCount,
ptStart.z() + (ptEnd.z() - ptStart.z()) * i / partCount));
pts.push_back( cvf::Vec3d( ptStart.x() + ( ptEnd.x() - ptStart.x() ) * i / partCount,
ptStart.y() + ( ptEnd.y() - ptStart.y() ) * i / partCount,
ptStart.z() + ( ptEnd.z() - ptStart.z() ) * i / partCount ) );
}
pts.push_back(ptEnd);
pts.push_back( ptEnd );
return pts;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh)
std::vector<std::vector<cvf::Vec3d>> calcFacePoints( const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh )
{
CVF_ASSERT(edgeXPtsLow.size() == edgeXPtsHigh.size() && edgeYPtsLow.size() == edgeYPtsHigh.size());
CVF_ASSERT( edgeXPtsLow.size() == edgeXPtsHigh.size() && edgeYPtsLow.size() == edgeYPtsHigh.size() );
size_t xSize = edgeXPtsLow.size();
size_t ySize = edgeYPtsLow.size();
@@ -193,16 +197,16 @@ std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d
std::vector<std::vector<cvf::Vec3d>> pts;
// Add low edge points
pts.push_back(edgeXPtsLow);
pts.push_back( edgeXPtsLow );
// Interior points
for (size_t y = 1; y < ySize - 1; y++)
for ( size_t y = 1; y < ySize - 1; y++ )
{
auto interiorPts = splitLine(edgeYPtsLow[y], edgeYPtsHigh[y], xSize - 1);
pts.push_back(interiorPts);
auto interiorPts = splitLine( edgeYPtsLow[y], edgeYPtsHigh[y], xSize - 1 );
pts.push_back( interiorPts );
}
// Add low edge points
pts.push_back(edgeXPtsHigh);
pts.push_back( edgeXPtsHigh );
return pts;
}

View File

@@ -21,8 +21,8 @@
#include <cvfBase.h>
#include <cvfVector3.h>
#include <vector>
#include <array>
#include <vector>
//--------------------------------------------------------------------------------------------------
///
@@ -31,7 +31,7 @@ class RiaCellDividingTools
{
public:
static std::vector<cvf::Vec3d>
createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz);
createHexCornerCoords( std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz );
static double computeFlowDistance(const std::array<cvf::Vec3d, 8>& cellVertices, const cvf::Vec3d& areaCenter);
static double computeFlowDistance( const std::array<cvf::Vec3d, 8>& cellVertices, const cvf::Vec3d& areaCenter );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,145 +23,120 @@
#include <QColor>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::normalPaletteColors()
{
static std::vector<cvf::Color3ub> colors {
cvf::Color3ub( 0, 0, 255),
cvf::Color3ub( 0, 127, 255),
cvf::Color3ub( 0, 255, 255),
cvf::Color3ub( 0, 255, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 0, 0)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 0, 0, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 0, 0 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::normalPaletteOppositeOrderingColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(255, 0, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub( 0, 255, 0),
cvf::Color3ub( 0, 255, 255),
cvf::Color3ub( 0, 127, 255),
cvf::Color3ub( 0, 0, 255)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 255, 0, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 0, 255 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::blackWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::BLACK,
cvf::Color3ub::WHITE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::BLACK, cvf::Color3ub::WHITE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::whiteBlackPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::WHITE,
cvf::Color3ub::BLACK
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::WHITE, cvf::Color3ub::BLACK};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::pinkWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::DEEP_PINK,
cvf::Color3ub::WHITE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::DEEP_PINK, cvf::Color3ub::WHITE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::whitePinkPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::WHITE,
cvf::Color3ub::DEEP_PINK
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::WHITE, cvf::Color3ub::DEEP_PINK};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::blueWhiteRedPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::BLUE,
cvf::Color3ub::WHITE,
cvf::Color3ub::RED
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::BLUE, cvf::Color3ub::WHITE, cvf::Color3ub::RED};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::redWhiteBluePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::RED,
cvf::Color3ub::WHITE,
cvf::Color3ub::BLUE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::RED, cvf::Color3ub::WHITE, cvf::Color3ub::BLUE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::categoryPaletteColors()
{
static caf::ColorTable colorTable = caf::ColorTable(categoryColors());
static caf::ColorTable colorTable = caf::ColorTable( categoryColors() );
return colorTable;
}
@@ -171,13 +146,13 @@ const caf::ColorTable& RiaColorTables::categoryPaletteColors()
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::contrastCategoryPaletteColors()
{
static caf::ColorTable colorTable = caf::ColorTable(contrastCategoryColors());
static caf::ColorTable colorTable = caf::ColorTable( contrastCategoryColors() );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorWhiteGrayBlackPaletteColors()
{
@@ -187,109 +162,107 @@ const caf::ColorTable& RiaColorTables::tensorWhiteGrayBlackPaletteColors()
cvf::Color3ub::BLACK,
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorOrangeBlueWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub(56, 56, 255), // Vivid Blue
cvf::Color3ub(210, 248, 250), // White Turquoiseish
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 210, 248, 250 ), // White Turquoiseish
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorsMagentaBrownGrayPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub::BROWN,
cvf::Color3ub::LIGHT_GRAY,
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::angularPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(255, 0, 255),
cvf::Color3ub(0, 0, 255),
cvf::Color3ub(0, 127, 255),
cvf::Color3ub(0, 255, 255),
cvf::Color3ub(0, 255, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 0, 0),
cvf::Color3ub(255, 0, 255)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 255, 0, 255 ),
cvf::Color3ub( 0, 0, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 0, 0 ),
cvf::Color3ub( 255, 0, 255 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::stimPlanPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(220, 220, 220), //Grey
cvf::Color3ub(0, 0, 255), //Blue
cvf::Color3ub(0, 128, 255), //Lighter blue
cvf::Color3ub(80, 240, 60), //Darker green
cvf::Color3ub(0, 255, 0), //Green
cvf::Color3ub(255, 255, 0), //Yellow
cvf::Color3ub(255, 192, 0), //Light orange
cvf::Color3ub(255, 128, 0), //Orange
cvf::Color3ub(255, 64, 0), //Red-orange
cvf::Color3ub(255, 0, 255) //Magenta
cvf::Color3ub( 220, 220, 220 ), // Grey
cvf::Color3ub( 0, 0, 255 ), // Blue
cvf::Color3ub( 0, 128, 255 ), // Lighter blue
cvf::Color3ub( 80, 240, 60 ), // Darker green
cvf::Color3ub( 0, 255, 0 ), // Green
cvf::Color3ub( 255, 255, 0 ), // Yellow
cvf::Color3ub( 255, 192, 0 ), // Light orange
cvf::Color3ub( 255, 128, 0 ), // Orange
cvf::Color3ub( 255, 64, 0 ), // Red-orange
cvf::Color3ub( 255, 0, 255 ) // Magenta
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::faultsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(101, 132, 96), // Dark green
cvf::Color3ub(255, 131, 140), // Old pink
cvf::Color3ub(210, 176, 112), // Light Brown
cvf::Color3ub(140, 171, 238), // Light gray blue
cvf::Color3ub(255, 205, 131), // Peach
cvf::Color3ub(220, 212, 166), // Dark off white
cvf::Color3ub(130, 255, 120), // Light green
cvf::Color3ub(166, 220, 215), // Light gray torquise
cvf::Color3ub(168, 220, 166), // Light gray green
cvf::Color3ub(255, 64, 236) // Magneta
cvf::Color3ub( 101, 132, 96 ), // Dark green
cvf::Color3ub( 255, 131, 140 ), // Old pink
cvf::Color3ub( 210, 176, 112 ), // Light Brown
cvf::Color3ub( 140, 171, 238 ), // Light gray blue
cvf::Color3ub( 255, 205, 131 ), // Peach
cvf::Color3ub( 220, 212, 166 ), // Dark off white
cvf::Color3ub( 130, 255, 120 ), // Light green
cvf::Color3ub( 166, 220, 215 ), // Light gray torquise
cvf::Color3ub( 168, 220, 166 ), // Light gray green
cvf::Color3ub( 255, 64, 236 ) // Magneta
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellsPaletteColors()
{
@@ -297,226 +270,222 @@ const caf::ColorTable& RiaColorTables::wellsPaletteColors()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveDefaultPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 0, 112, 136), // Dark Green-Blue
cvf::Color3ub(202, 0, 0), // Red
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub( 0, 0, 0), // Black
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub(201, 168, 206), // Light Violet
cvf::Color3ub( 0, 205, 68), // Bluish Green
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub( 51, 204, 255), // Bluer Turquoise
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub( 0, 143, 239) // Dark Light Blue
cvf::Color3ub( 0, 112, 136 ), // Dark Green-Blue
cvf::Color3ub( 202, 0, 0 ), // Red
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 0, 0, 0 ), // Black
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 169, 2, 240 ), // Purple
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 201, 168, 206 ), // Light Violet
cvf::Color3ub( 0, 205, 68 ), // Bluish Green
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 51, 204, 255 ), // Bluer Turquoise
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 0, 143, 239 ) // Dark Light Blue
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveRedPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(202, 0, 0), // Off Red
cvf::Color3ub(255, 51, 51), // Bright Red
cvf::Color3ub(255, 102, 102) // Light Red
cvf::Color3ub( 202, 0, 0 ), // Off Red
cvf::Color3ub( 255, 51, 51 ), // Bright Red
cvf::Color3ub( 255, 102, 102 ) // Light Red
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveGreenPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub( 0, 205, 68) // Bluish Green
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 0, 205, 68 ) // Bluish Green
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveBluePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub( 0, 143, 239), // Dark Light Blue
cvf::Color3ub(153, 153, 255) // Off Light Blue
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 0, 143, 239 ), // Dark Light Blue
cvf::Color3ub( 153, 153, 255 ) // Off Light Blue
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveBrownPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(186, 101, 44),
cvf::Color3ub( 99, 53, 23), // Highway Brown
cvf::Color3ub(103, 56, 24), // Dark Brown
cvf::Color3ub( 186, 101, 44 ),
cvf::Color3ub( 99, 53, 23 ), // Highway Brown
cvf::Color3ub( 103, 56, 24 ), // Dark Brown
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveNoneRedGreenBlueBrownPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub( 0, 0, 0), // Black
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub(201, 168, 206) // Light Violet
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 0, 0, 0 ), // Black
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 169, 2, 240 ), // Purple
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 201, 168, 206 ) // Light Violet
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellLogPlotPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkBlue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkRed)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkGreen)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkYellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkMagenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkCyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkGray)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::blue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::red)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::green)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::yellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::magenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::cyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::gray)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::black))
};
static std::vector<cvf::Color3ub> colors{caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkBlue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkRed ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkGreen ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkYellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkMagenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkCyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkGray ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::blue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::red ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::green ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::yellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::magenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::cyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::gray ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::black ) )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::selectionPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::magenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::cyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::blue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::red)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::green)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::yellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::gray))
};
static std::vector<cvf::Color3ub> colors{caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::magenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::cyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::blue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::red ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::green ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::yellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::gray ) )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::timestepsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub( 0, 143, 239), // Dark Light Blue
cvf::Color3ub( 0, 112, 136), // Dark Green-Blue
cvf::Color3ub( 51, 204, 255), // Bluer Turquoise
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub( 0, 205, 68), // Bluish Green
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub(202, 0, 0), // Red
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(201, 168, 206), // Light Violet
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 0, 143, 239 ), // Dark Light Blue
cvf::Color3ub( 0, 112, 136 ), // Dark Green-Blue
cvf::Color3ub( 51, 204, 255 ), // Bluer Turquoise
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 0, 205, 68 ), // Bluish Green
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 202, 0, 0 ), // Red
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 201, 168, 206 ), // Light Violet
cvf::Color3ub( 169, 2, 240 ), // Purple
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::editableWellPathsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 204, 0, 204), // Dark magenta
cvf::Color3ub( 173, 23, 212), // Strong Purple
cvf::Color3ub( 143, 46, 219), //Purple
cvf::Color3ub( 102, 76, 230), // Gray Blue
cvf::Color3ub( 71, 99, 237), // Lighter Gray Blue
cvf::Color3ub( 31, 130, 247), // Strong Blue
cvf::Color3ub( 0, 153, 255), // Dark Turquise
cvf::Color3ub( 204, 0, 204 ), // Dark magenta
cvf::Color3ub( 173, 23, 212 ), // Strong Purple
cvf::Color3ub( 143, 46, 219 ), // Purple
cvf::Color3ub( 102, 76, 230 ), // Gray Blue
cvf::Color3ub( 71, 99, 237 ), // Lighter Gray Blue
cvf::Color3ub( 31, 130, 247 ), // Strong Blue
cvf::Color3ub( 0, 153, 255 ), // Dark Turquise
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellPathsPaletteColors()
{
// Use inverted category colors to avoid identical colors if we have few sim wells and few well paths
static caf::ColorTable colorTable = caf::ColorTable(invertedCategoryColors());
static caf::ColorTable colorTable = caf::ColorTable( invertedCategoryColors() );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::undefinedCellColor()
{
@@ -546,16 +515,15 @@ RiaColorTables::WellPathComponentColors RiaColorTables::wellPathComponentColors(
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultGridLineColor()
{
return cvf::Color3f(0.92f, 0.92f, 0.92f);
return cvf::Color3f( 0.92f, 0.92f, 0.92f );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultFaultLineColor()
{
return cvf::Color3f(0.08f, 0.08f, 0.08f);
return cvf::Color3f( 0.08f, 0.08f, 0.08f );
}
//--------------------------------------------------------------------------------------------------
@@ -563,7 +531,7 @@ cvf::Color3f RiaColorTables::defaultFaultLineColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultWellLabelColor()
{
return cvf::Color3f(0.92f, 0.92f, 0.92f);
return cvf::Color3f( 0.92f, 0.92f, 0.92f );
}
//--------------------------------------------------------------------------------------------------
@@ -571,37 +539,38 @@ cvf::Color3f RiaColorTables::defaultWellLabelColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultViewerBackgroundColor()
{
return cvf::Color3f(0.69f, 0.77f, 0.87f);
return cvf::Color3f( 0.69f, 0.77f, 0.87f );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::ColorTable RiaColorTables::createBrightnessBasedColorTable(cvf::Color3ub baseColor, int brightnessLevelCount)
caf::ColorTable RiaColorTables::createBrightnessBasedColorTable( cvf::Color3ub baseColor, int brightnessLevelCount )
{
CVF_ASSERT(brightnessLevelCount >= 1);
QColor baseRGB(baseColor.r(), baseColor.g(), baseColor.b());
float hueF = baseRGB.hslHueF();
float satF = baseRGB.hslSaturationF();
CVF_ASSERT( brightnessLevelCount >= 1 );
QColor baseRGB( baseColor.r(), baseColor.g(), baseColor.b() );
float hueF = baseRGB.hslHueF();
float satF = baseRGB.hslSaturationF();
std::vector<cvf::Color3ub> colors;
if (brightnessLevelCount == 1)
if ( brightnessLevelCount == 1 )
{
colors.push_back(cvf::Color3ub(RiaColorTools::fromQColorTo3f(QColor::fromHslF(hueF, satF, 0.5))));
colors.push_back( cvf::Color3ub( RiaColorTools::fromQColorTo3f( QColor::fromHslF( hueF, satF, 0.5 ) ) ) );
}
else
{
for (int i = 0; i < brightnessLevelCount; ++i)
for ( int i = 0; i < brightnessLevelCount; ++i )
{
float brightness = static_cast<float>(i) / static_cast<float>(brightnessLevelCount - 1);
colors.push_back(cvf::Color3ub(RiaColorTools::fromQColorTo3f(QColor::fromHslF(hueF, satF, brightness))));
float brightness = static_cast<float>( i ) / static_cast<float>( brightnessLevelCount - 1 );
colors.push_back(
cvf::Color3ub( RiaColorTools::fromQColorTo3f( QColor::fromHslF( hueF, satF, brightness ) ) ) );
}
}
return caf::ColorTable(colors);
return caf::ColorTable( colors );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Color3ub> RiaColorTables::categoryColors()
{
@@ -610,26 +579,26 @@ std::vector<cvf::Color3ub> RiaColorTables::categoryColors()
// See also http://www.w3schools.com/colors/ for palettes etc.
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(128, 62, 117), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 46, 76, 224) // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 128, 62, 117 ), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 46, 76, 224 ) // hwb(230, 18%, 12%) medium_blue
};
return colors;
@@ -645,58 +614,58 @@ std::vector<cvf::Color3ub> RiaColorTables::contrastCategoryColors()
// See also http://www.w3schools.com/colors/ for palettes etc.
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(128, 62, 117), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub(59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub(46, 76, 224), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub(89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(0, 0, 0) // hwb(0, 0%, 100%) black
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 128, 62, 117 ), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 46, 76, 224 ), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 0, 0, 0 ) // hwb(0, 0%, 100%) black
};
return colors;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Color3ub> RiaColorTables::invertedCategoryColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 46, 76, 224), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(128, 62, 117) // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 46, 76, 224 ), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 128, 62, 117 ) // hwb(310, 24%, 50%) strong_purple
};
return colors;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,8 +23,8 @@
#include <map>
//==================================================================================================
///
///
///
///
//==================================================================================================
class RiaColorTables
{
@@ -68,10 +68,10 @@ public:
static cvf::Color3f defaultGridLineColor();
static cvf::Color3f defaultFaultLineColor();
static cvf::Color3f defaultWellLabelColor();
static cvf::Color3f defaultViewerBackgroundColor();
static cvf::Color3f defaultViewerBackgroundColor();
static caf::ColorTable createBrightnessBasedColorTable( cvf::Color3ub baseColor, int brightnessLevelCount );
static caf::ColorTable createBrightnessBasedColorTable(cvf::Color3ub baseColor, int brightnessLevelCount);
private:
static std::vector<cvf::Color3ub> categoryColors();
static std::vector<cvf::Color3ub> contrastCategoryColors();

View File

@@ -31,9 +31,9 @@
/// Luminance is between [0, 1] so anything above 0.5 is considered in the bright half of the spectrum.
/// However, subjectively the contrast looks better if the threshold is to 0.4 so black contrast is used a bit more often.
//--------------------------------------------------------------------------------------------------
bool RiaColorTools::isBrightnessAboveThreshold(cvf::Color3f backgroundColor)
bool RiaColorTools::isBrightnessAboveThreshold( cvf::Color3f backgroundColor )
{
if (relativeLuminance(backgroundColor) > 0.4)
if ( relativeLuminance( backgroundColor ) > 0.4 )
{
return true;
}
@@ -44,27 +44,28 @@ bool RiaColorTools::isBrightnessAboveThreshold(cvf::Color3f backgroundColor)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::computeOffsetColor(cvf::Color3f color, float offsetFactor)
cvf::Color3f RiaColorTools::computeOffsetColor( cvf::Color3f color, float offsetFactor )
{
float gridR = 0.0;
float gridG = 0.0;
float gridB = 0.0;
if (isBrightnessAboveThreshold(color))
if ( isBrightnessAboveThreshold( color ) )
{
gridR = color.r() - (color.r() * offsetFactor);
gridG = color.g() - (color.g() * offsetFactor);
gridB = color.b() - (color.b() * offsetFactor);
gridR = color.r() - ( color.r() * offsetFactor );
gridG = color.g() - ( color.g() * offsetFactor );
gridB = color.b() - ( color.b() * offsetFactor );
}
else
{
gridR = color.r() + (1.0f - color.r()) * offsetFactor;
gridG = color.g() + (1.0f - color.g()) * offsetFactor;
gridB = color.b() + (1.0f - color.b()) * offsetFactor;
gridR = color.r() + ( 1.0f - color.r() ) * offsetFactor;
gridG = color.g() + ( 1.0f - color.g() ) * offsetFactor;
gridB = color.b() + ( 1.0f - color.b() ) * offsetFactor;
}
return cvf::Color3f(
cvf::Math::clamp(gridR, 0.0f, 1.0f), cvf::Math::clamp(gridG, 0.0f, 1.0f), cvf::Math::clamp(gridB, 0.0f, 1.0f));
return cvf::Color3f( cvf::Math::clamp( gridR, 0.0f, 1.0f ),
cvf::Math::clamp( gridG, 0.0f, 1.0f ),
cvf::Math::clamp( gridB, 0.0f, 1.0f ) );
}
//--------------------------------------------------------------------------------------------------
@@ -72,7 +73,7 @@ cvf::Color3f RiaColorTools::computeOffsetColor(cvf::Color3f color, float offsetF
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::darkContrastColor()
{
return cvf::Color3f::fromByteColor(10, 10, 10);
return cvf::Color3f::fromByteColor( 10, 10, 10 );
}
//--------------------------------------------------------------------------------------------------
@@ -88,7 +89,7 @@ cvf::Color3f RiaColorTools::brightContrastColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::darkContrastColorSofter()
{
return cvf::Color3f::fromByteColor(30, 30, 30);
return cvf::Color3f::fromByteColor( 30, 30, 30 );
}
//--------------------------------------------------------------------------------------------------
@@ -96,87 +97,84 @@ cvf::Color3f RiaColorTools::darkContrastColorSofter()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::brightContrastColorSofter()
{
return cvf::Color3f::fromByteColor(200, 200, 200);
return cvf::Color3f::fromByteColor( 200, 200, 200 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::contrastColor(cvf::Color3f backgroundColor, bool softerContrast)
cvf::Color3f RiaColorTools::contrastColor( cvf::Color3f backgroundColor, bool softerContrast )
{
if (isBrightnessAboveThreshold(backgroundColor))
if ( isBrightnessAboveThreshold( backgroundColor ) )
{
if (softerContrast)
return darkContrastColorSofter();
if ( softerContrast ) return darkContrastColorSofter();
return darkContrastColor();
}
if (softerContrast)
return brightContrastColorSofter();
if ( softerContrast ) return brightContrastColorSofter();
return brightContrastColor();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::toQColor(cvf::Color3f color, float alpha)
QColor RiaColorTools::toQColor( cvf::Color3f color, float alpha )
{
QColor qcolor(color.rByte(), color.gByte(), color.bByte());
qcolor.setAlphaF(alpha);
QColor qcolor( color.rByte(), color.gByte(), color.bByte() );
qcolor.setAlphaF( alpha );
return qcolor;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::toQColor(cvf::Color4f color)
QColor RiaColorTools::toQColor( cvf::Color4f color )
{
return toQColor(color.toColor3f(), color.a());
return toQColor( color.toColor3f(), color.a() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::fromQColorTo3f(QColor color)
cvf::Color3f RiaColorTools::fromQColorTo3f( QColor color )
{
return cvf::Color3f(color.redF(), color.greenF(), color.blueF());
return cvf::Color3f( color.redF(), color.greenF(), color.blueF() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::blendCvfColors(const cvf::Color3f& color1,
const cvf::Color3f& color2,
int weight1 /*= 1*/,
int weight2 /*= 1*/)
cvf::Color3f RiaColorTools::blendCvfColors( const cvf::Color3f& color1,
const cvf::Color3f& color2,
int weight1 /*= 1*/,
int weight2 /*= 1*/ )
{
CVF_ASSERT(weight1 > 0 && weight2 > 0);
CVF_ASSERT( weight1 > 0 && weight2 > 0 );
int weightsum = weight1 + weight2;
return cvf::Color3f((color1.r() * weight1 + color2.r() * weight2) / weightsum,
(color1.g() * weight1 + color2.g() * weight2) / weightsum,
(color1.b() * weight1 + color2.b() * weight2) / weightsum);
return cvf::Color3f( ( color1.r() * weight1 + color2.r() * weight2 ) / weightsum,
( color1.g() * weight1 + color2.g() * weight2 ) / weightsum,
( color1.b() * weight1 + color2.b() * weight2 ) / weightsum );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::blendQColors(const QColor& color1, const QColor& color2, int weight1 /*= 1*/, int weight2 /*= 1*/)
QColor RiaColorTools::blendQColors( const QColor& color1, const QColor& color2, int weight1 /*= 1*/, int weight2 /*= 1*/ )
{
CVF_ASSERT(weight1 > 0 && weight2 > 0);
CVF_ASSERT( weight1 > 0 && weight2 > 0 );
int weightsum = weight1 + weight2;
return QColor((color1.red() * weight1 + color2.red() * weight2) / weightsum,
(color1.green() * weight1 + color2.green() * weight2) / weightsum,
(color1.blue() * weight1 + color2.blue() * weight2) / weightsum);
return QColor( ( color1.red() * weight1 + color2.red() * weight2 ) / weightsum,
( color1.green() * weight1 + color2.green() * weight2 ) / weightsum,
( color1.blue() * weight1 + color2.blue() * weight2 ) / weightsum );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float RiaColorTools::relativeLuminance(cvf::Color3f backgroundColor)
float RiaColorTools::relativeLuminance( cvf::Color3f backgroundColor )
{
float R = calculateNonLinearColorValue(backgroundColor.r());
float G = calculateNonLinearColorValue(backgroundColor.g());
float B = calculateNonLinearColorValue(backgroundColor.b());
float R = calculateNonLinearColorValue( backgroundColor.r() );
float G = calculateNonLinearColorValue( backgroundColor.g() );
float B = calculateNonLinearColorValue( backgroundColor.b() );
double luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
return luminance;
@@ -185,7 +183,7 @@ float RiaColorTools::relativeLuminance(cvf::Color3f backgroundColor)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float RiaColorTools::calculateNonLinearColorValue(float colorFraction)
float RiaColorTools::calculateNonLinearColorValue( float colorFraction )
{
return colorFraction <= 0.03928 ? colorFraction / 12.92 : std::pow((colorFraction + 0.055) / 1.055, 2.4);
return colorFraction <= 0.03928 ? colorFraction / 12.92 : std::pow( ( colorFraction + 0.055 ) / 1.055, 2.4 );
}

View File

@@ -19,34 +19,34 @@
#pragma once
#include "cvfArray.h"
#include <QColor>
//==================================================================================================
///
///
///
///
//==================================================================================================
class RiaColorTools
{
public:
static bool isBrightnessAboveThreshold(cvf::Color3f backgroundColor);
static cvf::Color3f computeOffsetColor(cvf::Color3f color, float offsetFactor);
static bool isBrightnessAboveThreshold( cvf::Color3f backgroundColor );
static cvf::Color3f computeOffsetColor( cvf::Color3f color, float offsetFactor );
static cvf::Color3f darkContrastColor();
static cvf::Color3f brightContrastColor();
static cvf::Color3f darkContrastColorSofter();
static cvf::Color3f brightContrastColorSofter();
static cvf::Color3f contrastColor(cvf::Color3f backgroundColor, bool softerContrast = false);
static QColor toQColor(cvf::Color3f color, float alpha = 1.0f);
static QColor toQColor(cvf::Color4f color);
static cvf::Color3f fromQColorTo3f(QColor);
static cvf::Color3f contrastColor( cvf::Color3f backgroundColor, bool softerContrast = false );
static QColor toQColor( cvf::Color3f color, float alpha = 1.0f );
static QColor toQColor( cvf::Color4f color );
static cvf::Color3f fromQColorTo3f( QColor );
static cvf::Color3f blendCvfColors(const cvf::Color3f& color1, const cvf::Color3f& color2, int weight1 = 1, int weight2 = 1);
static QColor blendQColors(const QColor& color1, const QColor& color2, int weight1 = 1, int weight2 = 1);
static cvf::Color3f
blendCvfColors( const cvf::Color3f& color1, const cvf::Color3f& color2, int weight1 = 1, int weight2 = 1 );
static QColor blendQColors( const QColor& color1, const QColor& color2, int weight1 = 1, int weight2 = 1 );
private:
static float relativeLuminance(cvf::Color3f backgroundColor);
static float calculateNonLinearColorValue(float colorFraction);
static float relativeLuminance( cvf::Color3f backgroundColor );
static float calculateNonLinearColorValue( float colorFraction );
};

View File

@@ -2,52 +2,50 @@
//
// Copyright (C) 2015- Statoil ASA
// Copyright (C) 2015- Ceetron Solutions AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaCurveDataTools.h"
#include <cmath> // Needed for HUGE_VAL on Linux
#include <cmath> // Needed for HUGE_VAL on Linux
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidValues(const std::vector<double>& values,
bool includePositiveValuesOnly)
RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidValues( const std::vector<double>& values,
bool includePositiveValuesOnly )
{
CurveIntervals intervals;
int startIdx = -1;
size_t vIdx = 0;
int startIdx = -1;
size_t vIdx = 0;
size_t valueCount = values.size();
while (vIdx < valueCount)
while ( vIdx < valueCount )
{
bool isValid = RiaCurveDataTools::isValidValue(values[vIdx], includePositiveValuesOnly);
bool isValid = RiaCurveDataTools::isValidValue( values[vIdx], includePositiveValuesOnly );
if (!isValid)
if ( !isValid )
{
if (startIdx >= 0)
if ( startIdx >= 0 )
{
intervals.push_back(std::make_pair(startIdx, vIdx - 1));
intervals.push_back( std::make_pair( startIdx, vIdx - 1 ) );
startIdx = -1;
}
}
else if (startIdx < 0)
else if ( startIdx < 0 )
{
startIdx = (int)vIdx;
}
@@ -55,30 +53,29 @@ RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidVa
vIdx++;
}
if (startIdx >= 0 && startIdx < ((int)valueCount))
if ( startIdx >= 0 && startIdx < ( (int)valueCount ) )
{
intervals.push_back(std::make_pair(startIdx, valueCount - 1));
intervals.push_back( std::make_pair( startIdx, valueCount - 1 ) );
}
return intervals;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartStopIndices(const CurveIntervals& intervals)
std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartStopIndices( const CurveIntervals& intervals )
{
std::vector<std::pair<size_t, size_t>> lineStartAndStopIndices;
const size_t intervalCount = intervals.size();
if (intervalCount < 1) return lineStartAndStopIndices;
if ( intervalCount < 1 ) return lineStartAndStopIndices;
size_t index = 0;
for (size_t intIdx = 0; intIdx < intervalCount; intIdx++)
for ( size_t intIdx = 0; intIdx < intervalCount; intIdx++ )
{
size_t intervalSize = intervals[intIdx].second - intervals[intIdx].first + 1;
lineStartAndStopIndices.push_back(std::make_pair(index, index + intervalSize - 1));
lineStartAndStopIndices.push_back( std::make_pair( index, index + intervalSize - 1 ) );
index += intervalSize;
}
@@ -86,22 +83,20 @@ std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartSt
return lineStartAndStopIndices;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaCurveDataTools::isValidValue(double value, bool allowPositiveValuesOnly)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaCurveDataTools::isValidValue( double value, bool allowPositiveValuesOnly )
{
if (value == HUGE_VAL || value == -HUGE_VAL || value != value)
if ( value == HUGE_VAL || value == -HUGE_VAL || value != value )
{
return false;
}
if (allowPositiveValuesOnly && value <= 0)
if ( allowPositiveValuesOnly && value <= 0 )
{
return false;
}
return true;
}

View File

@@ -2,17 +2,17 @@
//
// Copyright (C) 2015- Statoil ASA
// Copyright (C) 2015- Ceetron Solutions AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,15 +22,14 @@
#include "cvfAssert.h"
#include <cstddef>
#include <vector>
#include <utility>
#include <set>
#include <utility>
#include <vector>
class QDateTime;
//==================================================================================================
///
///
//==================================================================================================
class RiaCurveDataTools
{
@@ -38,28 +37,27 @@ public:
typedef std::vector<std::pair<size_t, size_t>> CurveIntervals;
public:
static CurveIntervals calculateIntervalsOfValidValues(const std::vector<double>& values,
bool includePositiveValuesOnly);
static CurveIntervals calculateIntervalsOfValidValues( const std::vector<double>& values,
bool includePositiveValuesOnly );
template <typename T>
static void getValuesByIntervals(const std::vector<T>& values,
const CurveIntervals& intervals,
std::vector<T>* filteredValues)
static void getValuesByIntervals( const std::vector<T>& values,
const CurveIntervals& intervals,
std::vector<T>* filteredValues )
{
CVF_ASSERT(filteredValues);
CVF_ASSERT( filteredValues );
for (size_t intIdx = 0; intIdx < intervals.size(); intIdx++)
for ( size_t intIdx = 0; intIdx < intervals.size(); intIdx++ )
{
for (size_t vIdx = intervals[intIdx].first; vIdx <= intervals[intIdx].second; vIdx++)
for ( size_t vIdx = intervals[intIdx].first; vIdx <= intervals[intIdx].second; vIdx++ )
{
filteredValues->push_back(values[vIdx]);
filteredValues->push_back( values[vIdx] );
}
}
}
static std::vector<std::pair<size_t, size_t>> computePolyLineStartStopIndices(const CurveIntervals& intervals);
static std::vector<std::pair<size_t, size_t>> computePolyLineStartStopIndices( const CurveIntervals& intervals );
public:
static bool isValidValue(double value, bool allowPositiveValuesOnly);
static bool isValidValue( double value, bool allowPositiveValuesOnly );
};

View File

@@ -6,15 +6,15 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<>
bool XValueComparator<double>::equals(const double& lhs, const double& rhs)
template <>
bool XValueComparator<double>::equals( const double& lhs, const double& rhs )
{
double eps = 1.0e-12 * std::max(std::fabs(lhs), std::fabs(rhs));
return std::fabs(lhs - rhs) < eps;
double eps = 1.0e-12 * std::max( std::fabs( lhs ), std::fabs( rhs ) );
return std::fabs( lhs - rhs ) < eps;
}
template<>
double XValueComparator<time_t>::diff(const time_t& lhs, const time_t& rhs)
template <>
double XValueComparator<time_t>::diff( const time_t& lhs, const time_t& rhs )
{
return difftime(lhs, rhs);
return difftime( lhs, rhs );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,66 +22,65 @@
#include <ctime>
template<typename XValueType>
template <typename XValueType>
class XValueComparator
{
public:
bool operator()(const XValueType& lhs, const XValueType& rhs) const;
static bool equals(const XValueType& lhs, const XValueType& rhs);
static double diff(const XValueType& lhs, const XValueType& rhs);
bool operator()( const XValueType& lhs, const XValueType& rhs ) const;
static bool equals( const XValueType& lhs, const XValueType& rhs );
static double diff( const XValueType& lhs, const XValueType& rhs );
};
//==================================================================================================
///
///
//==================================================================================================
template<typename XValueType>
template <typename XValueType>
class RiaCurveMerger
{
public:
typedef XValueComparator<XValueType> XComparator;
RiaCurveMerger();
void addCurveData(const std::vector<XValueType>& xValues, const std::vector<double>& yValues);
void addCurveData( const std::vector<XValueType>& xValues, const std::vector<double>& yValues );
size_t curveCount() const;
void computeInterpolatedValues(bool includeValuesFromPartialCurves = true);
void computeInterpolatedValues( bool includeValuesFromPartialCurves = true );
RiaCurveDataTools::CurveIntervals validIntervalsForAllXValues() const;
const std::vector<XValueType>& allXValues() const;
const std::vector<double>& interpolatedYValuesForAllXValues(size_t curveIdx) const;
RiaCurveDataTools::CurveIntervals validIntervalsForAllXValues() const;
const std::vector<XValueType>& allXValues() const;
const std::vector<double>& interpolatedYValuesForAllXValues( size_t curveIdx ) const;
// Non-const access is not required by any clients, but the expression parser has no available const interface
// for specifying a data source for an expression variable. Allow non-const access to avoid copy of the contained
// for specifying a data source for an expression variable. Allow non-const access to avoid copy of the contained
// values, interpolated for all time steps
//
// See ExpressionParserImpl::assignVector()
std::vector<double>& interpolatedYValuesForAllXValues(size_t curveIdx);
std::vector<double>& interpolatedYValuesForAllXValues( size_t curveIdx );
public:
// Helper methods, available as public to be able to access from unit tests
static double interpolatedYValue(const XValueType& xValue,
const std::vector<XValueType>& curveXValues,
const std::vector<double>& curveYValues);
static double interpolatedYValue( const XValueType& xValue,
const std::vector<XValueType>& curveXValues,
const std::vector<double>& curveYValues );
private:
void computeUnionOfXValues(bool includeValuesFromPartialCurves);
void computeUnionOfXValues( bool includeValuesFromPartialCurves );
private:
std::vector<std::pair<std::vector<XValueType>, std::vector<double>>> m_originalValues;
RiaCurveDataTools::CurveIntervals m_validIntervalsForAllXValues;
RiaCurveDataTools::CurveIntervals m_validIntervalsForAllXValues;
std::vector<XValueType> m_allXValues;
std::vector<std::vector<double>> m_interpolatedValuesForAllCurves;
std::vector<XValueType> m_allXValues;
std::vector<std::vector<double>> m_interpolatedValuesForAllCurves;
};
typedef RiaCurveMerger<time_t> RiaTimeHistoryCurveMerger;
template<>
bool XValueComparator<double>::equals(const double& lhs, const double& rhs);
template<>
double XValueComparator<time_t>::diff(const time_t& lhs, const time_t& rhs);
template <>
bool XValueComparator<double>::equals( const double& lhs, const double& rhs );
template <>
double XValueComparator<time_t>::diff( const time_t& lhs, const time_t& rhs );
#include "RiaCurveMerger.inl"

View File

@@ -1,66 +1,52 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaDateStringParser.h"
#include "RiaStdStringTools.h"
#include "RiaQDateTimeTools.h"
#include "RiaStdStringTools.h"
#include <algorithm>
const std::string MONTH_NAMES[] =
{
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
};
{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaDateStringParser::parseDateString(const QString& dateString)
QDateTime RiaDateStringParser::parseDateString( const QString& dateString )
{
return RiaDateStringParser::parseDateString(dateString.toStdString());
return RiaDateStringParser::parseDateString( dateString.toStdString() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaDateStringParser::parseDateString(const std::string& dateString)
QDateTime RiaDateStringParser::parseDateString( const std::string& dateString )
{
int year, month, day;
bool parsedOk =
tryParseYearFirst(dateString, year, month, day) ||
tryParseDayFirst(dateString, year, month, day) ||
tryParseMonthFirst(dateString, year, month, day);
int year, month, day;
bool parsedOk = tryParseYearFirst( dateString, year, month, day ) ||
tryParseDayFirst( dateString, year, month, day ) ||
tryParseMonthFirst( dateString, year, month, day );
QDateTime dt;
dt.setTimeSpec(RiaQDateTimeTools::currentTimeSpec());
if (parsedOk) dt.setDate(QDate(year, month, day));
dt.setTimeSpec( RiaQDateTimeTools::currentTimeSpec() );
if ( parsedOk ) dt.setDate( QDate( year, month, day ) );
return dt;
}
@@ -77,25 +63,25 @@ QDateTime RiaDateStringParser::parseDateString(const std::string& dateString)
/// 'yyyy.MMM.dd'
/// MMM is month name (shortened)
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseYearFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseYearFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sYear = s.substr(0, firstSep);
auto sMonth = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sDay = s.substr(lastSep + 1);
auto sYear = s.substr( 0, firstSep );
auto sMonth = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sDay = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
/// Try parse formats
/// 'dd mm yyyy'
/// 'dd mm yyyy'
/// 'dd MMM yyyy'
/// 'dd_mm_yyyy'
/// 'dd_mm_yyyy'
/// 'dd_MMM_yyyy'
/// 'dd-mm-yyyy'
/// 'dd-MMM-yyyy'
@@ -103,47 +89,47 @@ bool RiaDateStringParser::tryParseYearFirst(const std::string& s, int& year, int
/// 'dd.MMM.yyyy'
/// MMM is month name (shortened)
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseDayFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseDayFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sDay = s.substr(0, firstSep);
auto sMonth = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sYear = s.substr(lastSep + 1);
auto sDay = s.substr( 0, firstSep );
auto sMonth = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sYear = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseMonthFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseMonthFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sMonth = s.substr(0, firstSep);
auto sDay = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sYear = s.substr(lastSep + 1);
auto sMonth = s.substr( 0, firstSep );
auto sDay = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sYear = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseYear(const std::string& s, int &year)
bool RiaDateStringParser::tryParseYear( const std::string& s, int& year )
{
if (RiaStdStringTools::containsAlphabetic(s)) return false;
if ( RiaStdStringTools::containsAlphabetic( s ) ) return false;
auto today = QDate::currentDate();
int y = RiaStdStringTools::toInt(s);
if (y > 1970 && y <= today.year())
int y = RiaStdStringTools::toInt( s );
if ( y > 1970 && y <= today.year() )
{
year = y;
@@ -154,20 +140,21 @@ bool RiaDateStringParser::tryParseYear(const std::string& s, int &year)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
bool RiaDateStringParser::tryParseMonth( const std::string& s, int& month )
{
if (RiaStdStringTools::containsAlphabetic(s))
if ( RiaStdStringTools::containsAlphabetic( s ) )
{
auto sMonth = s;
sMonth = trimString(sMonth);
std::transform(sMonth.begin(), sMonth.end(), sMonth.begin(),
[](const char c) -> char { return (char)::tolower(c); });
sMonth = trimString( sMonth );
std::transform( sMonth.begin(), sMonth.end(), sMonth.begin(), []( const char c ) -> char {
return (char)::tolower( c );
} );
for (int i = 0; i < 12; i++)
for ( int i = 0; i < 12; i++ )
{
if (MONTH_NAMES[i].compare(0, sMonth.size(), sMonth) == 0)
if ( MONTH_NAMES[i].compare( 0, sMonth.size(), sMonth ) == 0 )
{
month = i + 1;
return true;
@@ -176,11 +163,11 @@ bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
}
else
{
int m = RiaStdStringTools::toInt(s);
if (m >= 1 && m <= 12)
int m = RiaStdStringTools::toInt( s );
if ( m >= 1 && m <= 12 )
{
month = m;
return true;
}
}
@@ -189,14 +176,14 @@ bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseDay(const std::string& s, int &day)
bool RiaDateStringParser::tryParseDay( const std::string& s, int& day )
{
if (RiaStdStringTools::containsAlphabetic(s)) return false;
if ( RiaStdStringTools::containsAlphabetic( s ) ) return false;
int d = RiaStdStringTools::toInt(s);
if (d >= 1 && d <= 31)
int d = RiaStdStringTools::toInt( s );
if ( d >= 1 && d <= 31 )
{
day = d;
@@ -207,11 +194,11 @@ bool RiaDateStringParser::tryParseDay(const std::string& s, int &day)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaDateStringParser::trimString(const std::string& s)
std::string RiaDateStringParser::trimString( const std::string& s )
{
auto sCopy = s.substr(0, s.find_last_not_of(' ') + 1);
sCopy = sCopy.substr(sCopy.find_first_not_of(' '));
auto sCopy = s.substr( 0, s.find_last_not_of( ' ' ) + 1 );
sCopy = sCopy.substr( sCopy.find_first_not_of( ' ' ) );
return sCopy;
}

View File

@@ -1,47 +1,46 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <QString>
#include <QDateTime>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaDateStringParser
{
public:
static QDateTime parseDateString(const QString& dateString);
static QDateTime parseDateString(const std::string& dateString);
static QDateTime parseDateString( const QString& dateString );
static QDateTime parseDateString( const std::string& dateString );
private:
static bool tryParseYearFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseDayFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseMonthFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseYearFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseDayFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseMonthFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseYear(const std::string& s, int &year);
static bool tryParseMonth(const std::string& s, int &month);
static bool tryParseDay(const std::string& s, int &day);
static bool tryParseYear( const std::string& s, int& year );
static bool tryParseMonth( const std::string& s, int& month );
static bool tryParseDay( const std::string& s, int& day );
static std::string trimString(const std::string& s);
static std::string trimString( const std::string& s );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017- Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,21 +25,21 @@
namespace caf
{
template<>
void RiaEclipseUnitTools::UnitSystemType::setUp()
{
addItem(RiaEclipseUnitTools::UNITS_METRIC, "UNITS_METRIC", "Metric");
addItem(RiaEclipseUnitTools::UNITS_FIELD, "UNITS_FIELD", "Field");
addItem(RiaEclipseUnitTools::UNITS_UNKNOWN, "UNITS_UNKNOWN", "Unknown");
template <>
void RiaEclipseUnitTools::UnitSystemType::setUp()
{
addItem( RiaEclipseUnitTools::UNITS_METRIC, "UNITS_METRIC", "Metric" );
addItem( RiaEclipseUnitTools::UNITS_FIELD, "UNITS_FIELD", "Field" );
addItem( RiaEclipseUnitTools::UNITS_UNKNOWN, "UNITS_UNKNOWN", "Unknown" );
setDefault(RiaEclipseUnitTools::UNITS_METRIC);
}
setDefault( RiaEclipseUnitTools::UNITS_METRIC );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::darcysConstant(UnitSystem unitSystem)
double RiaEclipseUnitTools::darcysConstant( UnitSystem unitSystem )
{
// See "Cartesian transmissibility calculations" in the "Eclipse Technical Description"
// CDARCY Darcys constant
@@ -47,109 +47,115 @@ double RiaEclipseUnitTools::darcysConstant(UnitSystem unitSystem)
// = 0.00112712 (E300); 0.001127 (ECLIPSE 100) (FIELD)
// = 3.6 (LAB)
// = 0.00864 (PVT - M)
switch (unitSystem)
switch ( unitSystem )
{
case UNITS_FIELD:
return 0.001127;
case UNITS_METRIC:
return 0.008527;
default:
CVF_ASSERT(false);
return 0.0;
case UNITS_FIELD:
return 0.001127;
case UNITS_METRIC:
return 0.008527;
default:
CVF_ASSERT( false );
return 0.0;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaDefines::DepthUnitType RiaEclipseUnitTools::depthUnit(UnitSystem unit)
RiaDefines::DepthUnitType RiaEclipseUnitTools::depthUnit( UnitSystem unit )
{
switch (unit)
switch ( unit )
{
case RiaEclipseUnitTools::UNITS_METRIC:
return RiaDefines::UNIT_METER;
break;
case RiaEclipseUnitTools::UNITS_FIELD:
return RiaDefines::UNIT_FEET;
break;
case RiaEclipseUnitTools::UNITS_LAB:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return RiaDefines::UNIT_NONE;
break;
default:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_METRIC:
return RiaDefines::UNIT_METER;
break;
case RiaEclipseUnitTools::UNITS_FIELD:
return RiaDefines::UNIT_FEET;
break;
case RiaEclipseUnitTools::UNITS_LAB:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return RiaDefines::UNIT_NONE;
break;
default:
return RiaDefines::UNIT_NONE;
break;
}
}
//--------------------------------------------------------------------------------------------------
/// Convert Gas to oil equivalents
/// If field unit, the Gas is in Mega ft^3 while the others are in [stb] (barrel)
/// If field unit, the Gas is in Mega ft^3 while the others are in [stb] (barrel)
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents(UnitSystem caseUnitSystem, double eclGasFlowRate)
double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents( UnitSystem caseUnitSystem, double eclGasFlowRate )
{
/// Unused Gas to Barrel conversion :
/// we convert gas to stb as well. Based on
/// we convert gas to stb as well. Based on
/// 1 [stb] = 0.15898729492800007 [m^3]
/// 1 [ft] = 0.3048 [m]
/// megaFt3ToStbFactor = 1.0 / (1.0e-6 * 0.15898729492800007 * ( 1.0 / 0.3048 )^3 )
/// double megaFt3ToStbFactor = 178107.60668;
double fieldGasToOilEquivalent = 1.0e6/5800; // Mega ft^3 to BOE
double metricGasToOilEquivalent = 1.0/1.0e3; // Sm^3 Gas to Sm^3 oe
double fieldGasToOilEquivalent = 1.0e6 / 5800; // Mega ft^3 to BOE
double metricGasToOilEquivalent = 1.0 / 1.0e3; // Sm^3 Gas to Sm^3 oe
double oilEquivalentGasRate = HUGE_VAL;
if (caseUnitSystem == RiaEclipseUnitTools::UNITS_FIELD) oilEquivalentGasRate = fieldGasToOilEquivalent * eclGasFlowRate;
if (caseUnitSystem == RiaEclipseUnitTools::UNITS_METRIC) oilEquivalentGasRate = metricGasToOilEquivalent * eclGasFlowRate;
if ( caseUnitSystem == RiaEclipseUnitTools::UNITS_FIELD )
oilEquivalentGasRate = fieldGasToOilEquivalent * eclGasFlowRate;
if ( caseUnitSystem == RiaEclipseUnitTools::UNITS_METRIC )
oilEquivalentGasRate = metricGasToOilEquivalent * eclGasFlowRate;
return oilEquivalentGasRate;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaEclipseUnitTools::unitStringPressure(UnitSystem unitSystem)
QString RiaEclipseUnitTools::unitStringPressure( UnitSystem unitSystem )
{
switch (unitSystem)
switch ( unitSystem )
{
case RiaEclipseUnitTools::UNITS_METRIC: return "barsa";
case RiaEclipseUnitTools::UNITS_FIELD: return "psia";
case RiaEclipseUnitTools::UNITS_LAB: return "atma";
case RiaEclipseUnitTools::UNITS_UNKNOWN: return "";
default: return "";
case RiaEclipseUnitTools::UNITS_METRIC:
return "barsa";
case RiaEclipseUnitTools::UNITS_FIELD:
return "psia";
case RiaEclipseUnitTools::UNITS_LAB:
return "atma";
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return "";
default:
return "";
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertToMeter(double sourceValue, const QString& sourceValueUnitText)
double RiaEclipseUnitTools::convertToMeter( double sourceValue, const QString& sourceValueUnitText )
{
QString timmed = sourceValueUnitText.trimmed();
if (timmed.compare("m", Qt::CaseInsensitive) == 0 || timmed.compare("md-m", Qt::CaseInsensitive) == 0)
if ( timmed.compare( "m", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-m", Qt::CaseInsensitive ) == 0 )
{
return sourceValue;
}
else if (timmed.compare("cm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "cm", Qt::CaseInsensitive ) == 0 )
{
return sourceValue / 100.0;
}
else if (timmed.compare("mm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "mm", Qt::CaseInsensitive ) == 0 )
{
return sourceValue / 1000.0;
}
else if (timmed.compare("in", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "in", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::inchToMeter(sourceValue);
return RiaEclipseUnitTools::inchToMeter( sourceValue );
}
else if (timmed.compare("ft", Qt::CaseInsensitive) == 0 || timmed.compare("md-ft", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "ft", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-ft", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::feetToMeter(sourceValue);
return RiaEclipseUnitTools::feetToMeter( sourceValue );
}
return HUGE_VAL;
@@ -158,31 +164,31 @@ double RiaEclipseUnitTools::convertToMeter(double sourceValue, const QString& so
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertToFeet(double sourceValue, const QString& sourceValueUnitText)
double RiaEclipseUnitTools::convertToFeet( double sourceValue, const QString& sourceValueUnitText )
{
QString timmed = sourceValueUnitText.trimmed();
if (timmed.compare("ft", Qt::CaseInsensitive) == 0 || timmed.compare("md-ft", Qt::CaseInsensitive) == 0)
if ( timmed.compare( "ft", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-ft", Qt::CaseInsensitive ) == 0 )
{
return sourceValue;
}
else if (timmed.compare("in", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "in", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::inchToFeet(sourceValue);
return RiaEclipseUnitTools::inchToFeet( sourceValue );
}
else if (timmed.compare("cm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "cm", Qt::CaseInsensitive ) == 0 )
{
double meter = sourceValue / 100.0;
return RiaEclipseUnitTools::meterToFeet(meter);
return RiaEclipseUnitTools::meterToFeet( meter );
}
else if (timmed.compare("mm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "mm", Qt::CaseInsensitive ) == 0 )
{
double meter = sourceValue / 1000.0;
return RiaEclipseUnitTools::meterToFeet(meter);
return RiaEclipseUnitTools::meterToFeet( meter );
}
else if (timmed.compare("m", Qt::CaseInsensitive) == 0 || timmed.compare("md-m", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "m", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-m", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::meterToFeet(sourceValue);
return RiaEclipseUnitTools::meterToFeet( sourceValue );
}
return HUGE_VAL;

View File

@@ -1,29 +1,28 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017- Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "cafAppEnum.h"
#include "RiaDefines.h"
#include "cafAppEnum.h"
class RiaEclipseUnitTools
{
public:
enum UnitSystem
{
@@ -33,28 +32,54 @@ public:
UNITS_UNKNOWN,
};
typedef caf::AppEnum< RiaEclipseUnitTools::UnitSystem > UnitSystemType;
typedef caf::AppEnum<RiaEclipseUnitTools::UnitSystem> UnitSystemType;
static double feetPerMeter() { return 3.2808399; }
static double meterPerFeet() { return 0.3048000; }
static double feetPerMeter()
{
return 3.2808399;
}
static double meterPerFeet()
{
return 0.3048000;
}
static double meterToFeet(double meter) { return meter * feetPerMeter(); }
static double feetToMeter(double feet) { return feet * meterPerFeet();}
static double meterToInch(double meter) { return meter * feetPerMeter()*12.0; }
static double inchToMeter(double inch) { return (inch / 12.0) * meterPerFeet(); }
static double inchToFeet (double inch) { return (inch / 12.0); }
static double mmToMeter(double mm) { return mm / 1000.0; }
static double meterToMm(double meter) { return 1000.0 * meter; }
static double meterToFeet( double meter )
{
return meter * feetPerMeter();
}
static double feetToMeter( double feet )
{
return feet * meterPerFeet();
}
static double meterToInch( double meter )
{
return meter * feetPerMeter() * 12.0;
}
static double inchToMeter( double inch )
{
return ( inch / 12.0 ) * meterPerFeet();
}
static double inchToFeet( double inch )
{
return ( inch / 12.0 );
}
static double mmToMeter( double mm )
{
return mm / 1000.0;
}
static double meterToMm( double meter )
{
return 1000.0 * meter;
}
static double darcysConstant(UnitSystem unitSystem);
static double darcysConstant( UnitSystem unitSystem );
static RiaDefines::DepthUnitType depthUnit(UnitSystem unit);
static RiaDefines::DepthUnitType depthUnit( UnitSystem unit );
static double convertSurfaceGasFlowRateToOilEquivalents(UnitSystem, double eclGasFlowRate);
static double convertSurfaceGasFlowRateToOilEquivalents( UnitSystem, double eclGasFlowRate );
static QString unitStringPressure(UnitSystem unitSystem);
static QString unitStringPressure( UnitSystem unitSystem );
static double convertToMeter(double sourceValue, const QString& unitText);
static double convertToFeet(double sourceValue, const QString& unitText);
static double convertToMeter( double sourceValue, const QString& unitText );
static double convertToFeet( double sourceValue, const QString& unitText );
};

View File

@@ -30,50 +30,54 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RiaExtractionTools::wellLogExtractorEclipseCase(RimWellPath* wellPath, RimEclipseCase* eclipseCase)
RigEclipseWellLogExtractor* RiaExtractionTools::wellLogExtractorEclipseCase( RimWellPath* wellPath,
RimEclipseCase* eclipseCase )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
return wlPlotCollection->findOrCreateExtractor(wellPath, eclipseCase);
return wlPlotCollection->findOrCreateExtractor( wellPath, eclipseCase );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigGeoMechWellLogExtractor* RiaExtractionTools::wellLogExtractorGeoMechCase(RimWellPath* wellPath, RimGeoMechCase* geomCase)
RigGeoMechWellLogExtractor* RiaExtractionTools::wellLogExtractorGeoMechCase( RimWellPath* wellPath,
RimGeoMechCase* geomCase )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
return wlPlotCollection->findOrCreateExtractor(wellPath, geomCase);
return wlPlotCollection->findOrCreateExtractor( wellPath, geomCase );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor(const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom)
RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor( const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
if (!(simWell && wellPathGeom))
if ( !( simWell && wellPathGeom ) )
{
return nullptr;
}
RimEclipseCase* eclipseCase = nullptr;
simWell->firstAncestorOrThisOfType(eclipseCase);
if (!(eclipseCase && eclipseCase->eclipseCaseData()))
simWell->firstAncestorOrThisOfType( eclipseCase );
if ( !( eclipseCase && eclipseCase->eclipseCaseData() ) )
{
return nullptr;
}
QString caseUserDescription = eclipseCase->caseUserDescription();
return wlPlotCollection->findOrCreateSimWellExtractor(
simWell->name, caseUserDescription, wellPathGeom, eclipseCase->eclipseCaseData());
return wlPlotCollection->findOrCreateSimWellExtractor( simWell->name,
caseUserDescription,
wellPathGeom,
eclipseCase->eclipseCaseData() );
}
//--------------------------------------------------------------------------------------------------
@@ -82,10 +86,10 @@ RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor(con
RimWellLogPlotCollection* RiaExtractionTools::wellLogPlotCollection()
{
auto proj = RiaApplication::instance()->project();
if (!proj) return nullptr;
if ( !proj ) return nullptr;
auto plotCollection = proj->mainPlotCollection();
if (!plotCollection) return nullptr;
if ( !plotCollection ) return nullptr;
auto wellLogPlotCollection = plotCollection->wellLogPlotCollection();
return wellLogPlotCollection;

View File

@@ -34,10 +34,11 @@ class QString;
//==================================================================================================
namespace RiaExtractionTools
{
RigEclipseWellLogExtractor* wellLogExtractorEclipseCase(RimWellPath* wellPath, RimEclipseCase* eclipseCase);
RigGeoMechWellLogExtractor* wellLogExtractorGeoMechCase(RimWellPath* wellPath, RimGeoMechCase* geomCase);
RigEclipseWellLogExtractor* wellLogExtractorEclipseCase( RimWellPath* wellPath, RimEclipseCase* eclipseCase );
RigGeoMechWellLogExtractor* wellLogExtractorGeoMechCase( RimWellPath* wellPath, RimGeoMechCase* geomCase );
RigEclipseWellLogExtractor* findOrCreateSimWellExtractor(const RimSimWellInView* simWell, const RigWellPath* wellPathGeom);
RigEclipseWellLogExtractor* findOrCreateSimWellExtractor( const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom );
RimWellLogPlotCollection* wellLogPlotCollection();

View File

@@ -28,17 +28,17 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaFieldhandleTools::disableWriteAndSetFieldHidden(caf::PdmFieldHandle* fieldHandle)
void RiaFieldhandleTools::disableWriteAndSetFieldHidden( caf::PdmFieldHandle* fieldHandle )
{
CVF_ASSERT(fieldHandle);
CVF_ASSERT( fieldHandle );
if (fieldHandle->uiCapability())
if ( fieldHandle->uiCapability() )
{
fieldHandle->uiCapability()->setUiHidden(true);
fieldHandle->uiCapability()->setUiHidden( true );
}
if (fieldHandle->xmlCapability())
if ( fieldHandle->xmlCapability() )
{
fieldHandle->xmlCapability()->setIOWritable(false);
fieldHandle->xmlCapability()->setIOWritable( false );
}
}

View File

@@ -30,5 +30,5 @@ class PdmFieldHandle;
class RiaFieldhandleTools
{
public:
static void disableWriteAndSetFieldHidden(caf::PdmFieldHandle* fieldHandle);
static void disableWriteAndSetFieldHidden( caf::PdmFieldHandle* fieldHandle );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,20 +22,19 @@
#include <QDir>
#include <set>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QChar RiaFilePathTools::SEPARATOR = '/';
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::toInternalSeparator(const QString& path)
QString RiaFilePathTools::toInternalSeparator( const QString& path )
{
QString currNativeSep = QDir::separator();
if (currNativeSep == "/")
if ( currNativeSep == "/" )
{
// On Linux like system -> Do not convert separators
return path;
@@ -43,33 +42,33 @@ QString RiaFilePathTools::toInternalSeparator(const QString& path)
// On other systems (i.e. Windows) -> Convert to internal separator (/)
QString output = path;
return output.replace(QString("\\"), SEPARATOR);
return output.replace( QString( "\\" ), SEPARATOR );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString& RiaFilePathTools::appendSeparatorIfNo(QString& path)
QString& RiaFilePathTools::appendSeparatorIfNo( QString& path )
{
if (!path.endsWith(SEPARATOR))
if ( !path.endsWith( SEPARATOR ) )
{
path.append(SEPARATOR);
path.append( SEPARATOR );
}
return path;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::relativePath(const QString& rootDir, const QString& dir)
QString RiaFilePathTools::relativePath( const QString& rootDir, const QString& dir )
{
if (dir.startsWith(rootDir))
if ( dir.startsWith( rootDir ) )
{
QString relPath = dir;
relPath.remove(0, rootDir.size());
relPath.remove( 0, rootDir.size() );
if (relPath.startsWith(SEPARATOR)) relPath.remove(0, 1);
return appendSeparatorIfNo(relPath);
if ( relPath.startsWith( SEPARATOR ) ) relPath.remove( 0, 1 );
return appendSeparatorIfNo( relPath );
}
else
{
@@ -78,87 +77,86 @@ QString RiaFilePathTools::relativePath(const QString& rootDir, const QString& di
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaFilePathTools::equalPaths(const QString& path1, const QString& path2)
bool RiaFilePathTools::equalPaths( const QString& path1, const QString& path2 )
{
QString p1 = path1;
QString p2 = path2;
appendSeparatorIfNo(p1);
appendSeparatorIfNo(p2);
appendSeparatorIfNo( p1 );
appendSeparatorIfNo( p2 );
return p1 == p2;
}
//--------------------------------------------------------------------------------------------------
/// Own canonicalPath method since the QDir::canonicalPath seems to not work
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::canonicalPath(const QString& path)
QString RiaFilePathTools::canonicalPath( const QString& path )
{
return QDir(path).absolutePath();
return QDir( path ).absolutePath();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::pair<QString, QString> RiaFilePathTools::toFolderAndFileName(const QString& absFileName)
std::pair<QString, QString> RiaFilePathTools::toFolderAndFileName( const QString& absFileName )
{
auto absFN = toInternalSeparator(absFileName);
int lastSep = absFN.lastIndexOf(SEPARATOR);
if (lastSep > 0)
auto absFN = toInternalSeparator( absFileName );
int lastSep = absFN.lastIndexOf( SEPARATOR );
if ( lastSep > 0 )
{
return std::make_pair(absFN.left(lastSep), absFN.mid(lastSep+1));
return std::make_pair( absFN.left( lastSep ), absFN.mid( lastSep + 1 ) );
}
else
{
return std::make_pair("", absFN);
return std::make_pair( "", absFN );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::removeDuplicatePathSeparators(const QString& path)
QString RiaFilePathTools::removeDuplicatePathSeparators( const QString& path )
{
QString correctedPath = path;
int len;
int len;
do
{
len = correctedPath.size();
correctedPath.replace(QString("%1%1").arg(SEPARATOR), SEPARATOR);
} while (correctedPath.size() != len);
correctedPath.replace( QString( "%1%1" ).arg( SEPARATOR ), SEPARATOR );
} while ( correctedPath.size() != len );
return correctedPath;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::rootSearchPathFromSearchFilter(const QString& searchFilter)
QString RiaFilePathTools::rootSearchPathFromSearchFilter( const QString& searchFilter )
{
std::set<QChar> globStartCharacters = {'*', '?', '['}; // ']' not needed
QStringList pathPartList = searchFilter.split(SEPARATOR);
QStringList pathPartList = searchFilter.split( SEPARATOR );
QStringList::iterator pathPartIt= pathPartList.begin();
QStringList::iterator pathPartIt = pathPartList.begin();
for ( ; pathPartIt != pathPartList.end(); ++pathPartIt)
for ( ; pathPartIt != pathPartList.end(); ++pathPartIt )
{
QString pathPart = *pathPartIt;
// Remove allowed escaping of wildcards
pathPart.replace("[[]", "");
pathPart.replace("[]]", "");
pathPart.replace("[?]", "");
pathPart.replace("[*]", "");
if (pathPart.contains("*")) break;
if (pathPart.contains("?")) break;
if (pathPart.contains("[")) break;
pathPart.replace( "[[]", "" );
pathPart.replace( "[]]", "" );
pathPart.replace( "[?]", "" );
pathPart.replace( "[*]", "" );
if ( pathPart.contains( "*" ) ) break;
if ( pathPart.contains( "?" ) ) break;
if ( pathPart.contains( "[" ) ) break;
}
pathPartList.erase(pathPartIt, pathPartList.end());
pathPartList.erase( pathPartIt, pathPartList.end() );
return pathPartList.join(SEPARATOR);
return pathPartList.join( SEPARATOR );
}

View File

@@ -3,30 +3,30 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <QString>
#include <QByteArray>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaFilePathTools
@@ -34,12 +34,12 @@ class RiaFilePathTools
public:
static const QChar SEPARATOR;
static QString toInternalSeparator(const QString& path);
static QString& appendSeparatorIfNo(QString& path);
static QString relativePath(const QString& rootDir, const QString& dir);
static bool equalPaths(const QString& path1, const QString& path2);
static QString canonicalPath(const QString& path);
static std::pair<QString, QString> toFolderAndFileName(const QString& absFileName);
static QString removeDuplicatePathSeparators(const QString& path);
static QString rootSearchPathFromSearchFilter(const QString& searchFilter);
static QString toInternalSeparator( const QString& path );
static QString& appendSeparatorIfNo( QString& path );
static QString relativePath( const QString& rootDir, const QString& dir );
static bool equalPaths( const QString& path1, const QString& path2 );
static QString canonicalPath( const QString& path );
static std::pair<QString, QString> toFolderAndFileName( const QString& absFileName );
static QString removeDuplicatePathSeparators( const QString& path );
static QString rootSearchPathFromSearchFilter( const QString& searchFilter );
};

View File

@@ -26,8 +26,8 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaGitDiff::RiaGitDiff(const QString& pathToDiffTool)
: m_pathToGitTool(pathToDiffTool)
RiaGitDiff::RiaGitDiff( const QString& pathToDiffTool )
: m_pathToGitTool( pathToDiffTool )
{
reset();
}
@@ -51,32 +51,32 @@ void RiaGitDiff::reset()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaGitDiff::executeDiff(const QString& baseFolder)
bool RiaGitDiff::executeDiff( const QString& baseFolder )
{
reset();
QString fullFilePath = "git";
if (!m_pathToGitTool.isEmpty())
if ( !m_pathToGitTool.isEmpty() )
{
fullFilePath = m_pathToGitTool + "/" + fullFilePath;
}
QString incomingCurrentPath = QDir::currentPath();
QDir::setCurrent(baseFolder);
QDir::setCurrent( baseFolder );
QString args = "diff";
QString completeCommand = QString("\"%1\" %2").arg(fullFilePath).arg(args);
QString completeCommand = QString( "\"%1\" %2" ).arg( fullFilePath ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QDir::setCurrent(incomingCurrentPath);
QDir::setCurrent( incomingCurrentPath );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running 'git' tool process";

View File

@@ -36,10 +36,10 @@ public:
};
public:
explicit RiaGitDiff(const QString& pathToGitTool);
explicit RiaGitDiff( const QString& pathToGitTool );
~RiaGitDiff();
bool executeDiff(const QString& baseFolder);
bool executeDiff( const QString& baseFolder );
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;

View File

@@ -1,66 +1,66 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaImageCompareReporter.h"
#include <iostream>
#include <fstream>
#include <QDir>
#include <fstream>
#include <iostream>
RiaImageCompareReporter::RiaImageCompareReporter(void)
RiaImageCompareReporter::RiaImageCompareReporter( void )
{
m_showOriginal = true;
m_showGenerated = true;
m_showOriginal = true;
m_showGenerated = true;
m_showInteractiveDiff = false;
}
RiaImageCompareReporter::~RiaImageCompareReporter(void)
{
}
RiaImageCompareReporter::~RiaImageCompareReporter( void ) {}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::addImageDirectoryComparisonSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir)
void RiaImageCompareReporter::addImageDirectoryComparisonSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir )
{
m_directorySets.push_back(DirSet(title, baseImageDir, newImagesDir, diffImagesDir));
m_directorySets.push_back( DirSet( title, baseImageDir, newImagesDir, diffImagesDir ) );
}
std::string removeCommonStart(const std::string& mask, const std::string& filename)
std::string removeCommonStart( const std::string& mask, const std::string& filename )
{
size_t i;
for (i = 0; i < mask.size() && i < filename.size(); ++i)
for ( i = 0; i < mask.size() && i < filename.size(); ++i )
{
if (mask[i] != filename[i]) break;
if ( mask[i] != filename[i] ) break;
}
return filename.substr(i);
return filename.substr( i );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, const std::string& diff2htmlHeaderText)
void RiaImageCompareReporter::generateHTMLReport( const std::string& fileName, const std::string& diff2htmlHeaderText )
{
if (m_directorySets.size() == 0) return;
if ( m_directorySets.size() == 0 ) return;
std::ofstream output(fileName.c_str());
if (!output)
std::ofstream output( fileName.c_str() );
if ( !output )
{
std::cout << "Trouble opening test report file: " << fileName;
return;
@@ -71,7 +71,7 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
html += "<html>\n";
html += "<head>\n";
if (m_showInteractiveDiff)
if ( m_showInteractiveDiff )
{
html += cssString();
}
@@ -84,42 +84,48 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
html += "<title>Regression-Test Report</title>\n";
html += "\n";
for (size_t dsIdx = 0; dsIdx < m_directorySets.size(); ++dsIdx)
for ( size_t dsIdx = 0; dsIdx < m_directorySets.size(); ++dsIdx )
{
std::vector<std::string> baseImageNames = getPngFilesInDirectory(m_directorySets[dsIdx].m_baseImageDir);
std::vector<std::string> baseImageNames = getPngFilesInDirectory( m_directorySets[dsIdx].m_baseImageDir );
html += "<table>\n";
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " + m_directorySets[dsIdx].m_title + " </font></b> </td>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
m_directorySets[dsIdx].m_title + " </font></b> </td>\n";
html += " </tr>\n";
std::string baseImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_baseImageDir );
std::string genImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_newImagesDir );
std::string diffImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_diffImagesDir);
std::string baseImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_baseImageDir );
std::string genImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_newImagesDir );
std::string diffImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_diffImagesDir );
for (size_t fIdx = 0; fIdx < baseImageNames.size(); ++fIdx)
for ( size_t fIdx = 0; fIdx < baseImageNames.size(); ++fIdx )
{
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"lightgray\"> " + baseImageNames[fIdx] + "</td>\n";
html += " </tr>\n";
html += " <tr>\n";
if (m_showOriginal)
if ( m_showOriginal )
{
html += " <td> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
}
if (m_showGenerated)
if ( m_showGenerated )
{
html += " <td> <img src=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + genImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
}
if (m_showInteractiveDiff)
if ( m_showInteractiveDiff )
{
html += " <td> <div class = \"image-slider\"> <div> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </div> <img src = \"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </div> </td>\n";
html += " <td> <div class = \"image-slider\"> <div> <img src=\"" + baseImageFolder + "/" +
baseImageNames[fIdx] + "\" > </div> <img src = \"" + genImageFolder + "/" +
baseImageNames[fIdx] + "\" > </div> </td>\n";
}
html += " <td> <img src=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + diffImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " </tr>\n";
// A little air between images
@@ -135,12 +141,12 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::showInteractiveOnly()
{
m_showOriginal = false;
m_showGenerated = false;
m_showOriginal = false;
m_showGenerated = false;
m_showInteractiveDiff = true;
}
@@ -148,28 +154,28 @@ void RiaImageCompareReporter::showInteractiveOnly()
/// Retuns the names of the *.png files in a directory. The names are without path, but with extention
//--------------------------------------------------------------------------------------------------
std::vector<std::string> RiaImageCompareReporter::getPngFilesInDirectory(const std::string& searchPath)
std::vector<std::string> RiaImageCompareReporter::getPngFilesInDirectory( const std::string& searchPath )
{
QDir searchDir(QString::fromStdString(searchPath));
QDir searchDir( QString::fromStdString( searchPath ) );
searchDir.setFilter(QDir::Files);
//QStringList filter;
//filter.append("*.png");
//searchDir.setNameFilters(filter);
searchDir.setFilter( QDir::Files );
// QStringList filter;
// filter.append("*.png");
// searchDir.setNameFilters(filter);
QStringList imageFiles = searchDir.entryList();
std::vector<std::string> fileNames;
for (int i = 0; i < imageFiles.size(); ++i)
for ( int i = 0; i < imageFiles.size(); ++i )
{
fileNames.push_back(imageFiles[i].toStdString());
fileNames.push_back( imageFiles[i].toStdString() );
}
return fileNames;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaImageCompareReporter::cssString() const
{
@@ -179,36 +185,36 @@ std::string RiaImageCompareReporter::cssString() const
html += "";
html += ".image-slider {";
html += "position:relative;";
html += "display: inline-block;";
html += "line-height: 0;";
html += "position:relative;";
html += "display: inline-block;";
html += "line-height: 0;";
html += "}";
html += ".image-slider > div {";
html += "position: absolute;";
html += "top: 0; bottom: 0; left: 0;";
html += "width: 25px;";
html += "max-width: 100%;";
html += "overflow: hidden;";
html += "resize: horizontal;";
html += "position: absolute;";
html += "top: 0; bottom: 0; left: 0;";
html += "width: 25px;";
html += "max-width: 100%;";
html += "overflow: hidden;";
html += "resize: horizontal;";
html += "}";
html += ".image-slider > div:before {";
html += "content: '';";
html += "position: absolute;";
html += "right: 0; bottom: 0;";
html += "width: 23px; height: 23px;";
html += "padding: 5px;";
html += "background: linear-gradient(-45deg, gray 50%, transparent 0);";
html += "background-clip: content-box;";
html += "cursor: ew-resize;";
html += "-webkit-filter: drop-shadow(0 0 6px black);";
html += "filter: drop-shadow(0 0 6px black);";
html += "content: '';";
html += "position: absolute;";
html += "right: 0; bottom: 0;";
html += "width: 23px; height: 23px;";
html += "padding: 5px;";
html += "background: linear-gradient(-45deg, gray 50%, transparent 0);";
html += "background-clip: content-box;";
html += "cursor: ew-resize;";
html += "-webkit-filter: drop-shadow(0 0 6px black);";
html += "filter: drop-shadow(0 0 6px black);";
html += "}";
html += ".image-slider img {";
html += "user-select: none;";
html += "max-width: 1000px;";
html += "user-select: none;";
html += "max-width: 1000px;";
html += "}";
html += "</style>";

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -27,25 +27,31 @@ public:
RiaImageCompareReporter();
virtual ~RiaImageCompareReporter();
void addImageDirectoryComparisonSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir );
void generateHTMLReport(const std::string& filenName, const std::string& pathToDiff2html);
void addImageDirectoryComparisonSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir );
void generateHTMLReport( const std::string& filenName, const std::string& pathToDiff2html );
void showInteractiveOnly();
private:
static std::vector<std::string> getPngFilesInDirectory(const std::string& searchPath);
std::string cssString() const;
static std::vector<std::string> getPngFilesInDirectory( const std::string& searchPath );
std::string cssString() const;
private:
struct DirSet
{
DirSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir )
: m_title(title),
m_baseImageDir(baseImageDir),
m_newImagesDir(newImagesDir),
m_diffImagesDir(diffImagesDir)
{}
DirSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir )
: m_title( title )
, m_baseImageDir( baseImageDir )
, m_newImagesDir( newImagesDir )
, m_diffImagesDir( diffImagesDir )
{
}
std::string m_title;
std::string m_baseImageDir;
@@ -59,4 +65,3 @@ private:
bool m_showGenerated;
bool m_showInteractiveDiff;
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,89 +19,89 @@
#include "RiaImageFileCompare.h"
#include <QtCore/QProcess>
//==================================================================================================
//
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::RiaImageFileCompare(QString compareExecutable)
: m_compareExecutable(compareExecutable)
RiaImageFileCompare::RiaImageFileCompare( QString compareExecutable )
: m_compareExecutable( compareExecutable )
{
reset();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::~RiaImageFileCompare() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::~RiaImageFileCompare()
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageFileCompare::reset()
{
m_imagesEqual = false;
m_lastError = IC_NO_ERROR;
m_errorMsg = "";
m_imagesEqual = false;
m_lastError = IC_NO_ERROR;
m_errorMsg = "";
m_errorDetails = "";
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImageFileCompare::runComparison(QString imgFileName, QString refFileName, QString diffFileName)
bool RiaImageFileCompare::runComparison( QString imgFileName, QString refFileName, QString diffFileName )
{
reset();
if (m_compareExecutable.isEmpty())
if ( m_compareExecutable.isEmpty() )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Cannot compare images, no compare executable set";
m_errorMsg = "Cannot compare images, no compare executable set";
return false;
}
//QString args = QString("-fuzz 2% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
// QString args = QString("-fuzz 2% -lowlight-color white -metric ae \"%1\" \"%2\"
// \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
// The ImageMagick compare tool on RedHat 5 does not support the lowlight-color options
// Use GCC version as a crude mechanism for disabling use of this option on RedHat5
#if (__GNUC__ == 4 && __GNUC_MINOR__ <= 1)
QString args = QString("-fuzz 0.4% -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
#if ( __GNUC__ == 4 && __GNUC_MINOR__ <= 1 )
QString args = QString( "-fuzz 0.4% -metric ae \"%1\" \"%2\" \"%3\"" )
.arg( imgFileName )
.arg( refFileName )
.arg( ( diffFileName ) );
#else
QString args = QString("-fuzz 0.4% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
QString args = QString( "-fuzz 0.4% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"" )
.arg( imgFileName )
.arg( refFileName )
.arg( ( diffFileName ) );
#endif
QString completeCommand = QString("\"%1\" %2").arg(m_compareExecutable).arg(args);
QString completeCommand = QString( "\"%1\" %2" ).arg( m_compareExecutable ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running compare tool process";
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running compare tool process";
m_errorDetails = completeCommand;
return false;
}
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if (procExitCode == 0)
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if ( procExitCode == 0 )
{
// Strip out whitespace and look for 0 (as in zero pixel differences)
stdErr = stdErr.simplified();
if (!stdErr.isEmpty() && stdErr[0] == '0')
if ( !stdErr.isEmpty() && stdErr[0] == '0' )
{
m_imagesEqual = true;
}
@@ -111,44 +111,40 @@ bool RiaImageFileCompare::runComparison(QString imgFileName, QString refFileName
else
{
// Report non-severe error
m_lastError = IC_ERROR;
m_errorMsg = "Error running compare tool process";
m_lastError = IC_ERROR;
m_errorMsg = "Error running compare tool process";
m_errorDetails = stdErr;
return false;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImageFileCompare::imagesEqual() const
{
return m_imagesEqual;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::ErrorType RiaImageFileCompare::error() const
{
return m_lastError;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaImageFileCompare::errorMessage() const
{
return m_errorMsg;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaImageFileCompare::errorDetails() const
{

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -30,31 +30,28 @@ class RiaImageFileCompare
public:
enum ErrorType
{
IC_NO_ERROR, // No error occurred
IC_ERROR, // An error occurred
SEVERE_ERROR // Severe error occurred, it is likely that another call to compare() will also fail
IC_NO_ERROR, // No error occurred
IC_ERROR, // An error occurred
SEVERE_ERROR // Severe error occurred, it is likely that another call to compare() will also fail
};
public:
explicit RiaImageFileCompare(QString compareExecutable);
explicit RiaImageFileCompare( QString compareExecutable );
~RiaImageFileCompare();
bool runComparison(QString imgFileName, QString refFileName, QString diffFileName);
bool imagesEqual() const;
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;
bool runComparison( QString imgFileName, QString refFileName, QString diffFileName );
bool imagesEqual() const;
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;
private:
void reset();
void reset();
private:
QString m_compareExecutable; // The executable for the ImageMagick compare tool
bool m_imagesEqual; // Result of last comparison
ErrorType m_lastError; // Error for last execution
QString m_errorMsg;
QString m_errorDetails;
QString m_compareExecutable; // The executable for the ImageMagick compare tool
bool m_imagesEqual; // Result of last comparison
ErrorType m_lastError; // Error for last execution
QString m_errorMsg;
QString m_errorDetails;
};

View File

@@ -14,13 +14,13 @@
/// http://fab.cba.mit.edu/classes/S62.12/docs/Meijster_distance.pdf
/// Currently Euclidean only, but can be easily extended by replacing the lambda functions.
//--------------------------------------------------------------------------------------------------
void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>& image)
void RiaImageTools::distanceTransform2d( std::vector<std::vector<unsigned int>>& image )
{
if (image.empty())
if ( image.empty() )
{
return;
}
if (image.front().empty())
if ( image.front().empty() )
{
return;
}
@@ -28,22 +28,22 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
const int64_t N = (int64_t)image.front().size();
int64_t infVal = M + N;
CVF_ASSERT(infVal <= std::numeric_limits<unsigned int>::max());
CVF_ASSERT( infVal <= std::numeric_limits<unsigned int>::max() );
// First phase
std::vector<std::vector<int64_t>> g(M);
std::vector<std::vector<int64_t>> g( M );
#pragma omp parallel for
for (int64_t x = 0; x < M; ++x)
for ( int64_t x = 0; x < M; ++x )
{
g[x].resize(N, infVal);
if (image[x][0])
g[x].resize( N, infVal );
if ( image[x][0] )
{
g[x][0] = 0;
}
for (int64_t y = 1; y < N - 1; ++y)
for ( int64_t y = 1; y < N - 1; ++y )
{
if (image[x][y])
if ( image[x][y] )
{
g[x][y] = 0;
}
@@ -52,50 +52,50 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
g[x][y] = 1 + g[x][y - 1];
}
}
for (int64_t y = N - 2; y >= 0; --y)
for ( int64_t y = N - 2; y >= 0; --y )
{
if (g[x][y + 1] < g[x][y])
if ( g[x][y + 1] < g[x][y] )
{
g[x][y] = 1 + g[x][y + 1];
}
}
}
auto f = [](int64_t x, int64_t i, const std::vector<std::vector<int64_t>>& g, int64_t y) {
return (x - i) * (x - i) + g[i][y] * g[i][y];
auto f = []( int64_t x, int64_t i, const std::vector<std::vector<int64_t>>& g, int64_t y ) {
return ( x - i ) * ( x - i ) + g[i][y] * g[i][y];
};
auto sep = [](int64_t i, int64_t u, const std::vector<std::vector<int64_t>>& g, int64_t y) {
if (i == u) return (int64_t)0;
auto sep = []( int64_t i, int64_t u, const std::vector<std::vector<int64_t>>& g, int64_t y ) {
if ( i == u ) return (int64_t)0;
int64_t numerator = u * u - i * i + g[u][y] * g[u][y] - g[i][y] * g[i][y];
int64_t divisor = 2 * (u - i);
int64_t divisor = 2 * ( u - i );
return numerator / divisor;
};
// Second phase
#pragma omp parallel for
for (int64_t y = 0; y < N; ++y)
for ( int64_t y = 0; y < N; ++y )
{
int64_t q = 0;
std::vector<int64_t> s(std::max(N, M), (int64_t) 0);
std::vector<int64_t> t(std::max(N, M), (int64_t) 0);
int64_t q = 0;
std::vector<int64_t> s( std::max( N, M ), (int64_t)0 );
std::vector<int64_t> t( std::max( N, M ), (int64_t)0 );
for (int64_t u = 1; u < M - 1; ++u)
for ( int64_t u = 1; u < M - 1; ++u )
{
while (q >= 0 && f(t[q], s[q], g, y) > f(t[q], u, g, y))
while ( q >= 0 && f( t[q], s[q], g, y ) > f( t[q], u, g, y ) )
{
q--;
}
if (q < 0)
if ( q < 0 )
{
q = 0;
s[0] = u;
}
else
{
int64_t w = 1 + sep((int64_t)s[q], u, g, y);
if (w < M)
int64_t w = 1 + sep( (int64_t)s[q], u, g, y );
if ( w < M )
{
q++;
s[q] = u;
@@ -103,12 +103,12 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
}
}
}
for (int64_t u = M - 1; u >= 0; --u)
for ( int64_t u = M - 1; u >= 0; --u )
{
int64_t fVal = f(u, s[q], g, y);
CVF_ASSERT(fVal <= std::numeric_limits<double>::max());
image[u][y] = static_cast<unsigned int>(fVal);
if (u == t[q])
int64_t fVal = f( u, s[q], g, y );
CVF_ASSERT( fVal <= std::numeric_limits<double>::max() );
image[u][y] = static_cast<unsigned int>( fVal );
if ( u == t[q] )
{
q = q - 1;
}
@@ -119,18 +119,17 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaImageTools::makeGrayScale(QImage& image)
void RiaImageTools::makeGrayScale( QImage& image )
{
for (int i = 0; i < image.height(); i++)
for ( int i = 0; i < image.height(); i++ )
{
uchar* scanLine = image.scanLine(i);
for (int j = 0; j < image.width(); j++)
uchar* scanLine = image.scanLine( i );
for ( int j = 0; j < image.width(); j++ )
{
QRgb* pixel = reinterpret_cast<QRgb*>(scanLine + j * 4);
int gray = qGray(*pixel);
int alpha = qAlpha(*pixel);
*pixel = QColor(gray, gray, gray, alpha).rgba();
QRgb* pixel = reinterpret_cast<QRgb*>( scanLine + j * 4 );
int gray = qGray( *pixel );
int alpha = qAlpha( *pixel );
*pixel = QColor( gray, gray, gray, alpha ).rgba();
}
}
}

View File

@@ -25,8 +25,6 @@ class QImage;
class RiaImageTools
{
public:
static void distanceTransform2d(std::vector<std::vector<unsigned int>>& image);
static void makeGrayScale(QImage& image);
static void distanceTransform2d( std::vector<std::vector<unsigned int>>& image );
static void makeGrayScale( QImage& image );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -20,8 +20,8 @@
#include "ApplicationCommands/RicShowMainWindowFeature.h"
#include "SummaryPlotCommands/RicNewSummaryPlotFeature.h"
#include "SummaryPlotCommands/RicNewSummaryCurveFeature.h"
#include "SummaryPlotCommands/RicNewSummaryPlotFeature.h"
#include "SummaryPlotCommands/RicSummaryPlotFeatureImpl.h"
#include "RiaApplication.h"
@@ -61,85 +61,88 @@
#include "RiuPlotMainWindow.h"
#include "RiuPlotMainWindowTools.h"
#include "cafUtils.h"
#include "cafProgressInfo.h"
#include "cafUtils.h"
#include <QFileInfo>
#include <QMessageBox>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& fileNames, FileCaseIdMap* openedFilesOut, bool noDialog)
bool RiaImportEclipseCaseTools::openEclipseCasesFromFile( const QStringList& fileNames,
FileCaseIdMap* openedFilesOut,
bool noDialog )
{
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
// Get list of files to import
RifSummaryCaseRestartSelector selector;
if(noDialog) selector.showDialog(false);
selector.determineFilesToImportFromGridFiles(fileNames);
if ( noDialog ) selector.showDialog( false );
selector.determineFilesToImportFromGridFiles( fileNames );
std::vector<RifSummaryCaseFileResultInfo> summaryFileInfos = selector.summaryFileInfos();
FileCaseIdMap openedFiles;
// Import eclipse case files
for (const QString& gridCaseFile : selector.gridCaseFiles())
for ( const QString& gridCaseFile : selector.gridCaseFiles() )
{
int caseId = RiaImportEclipseCaseTools::openEclipseCaseFromFile(gridCaseFile);
if (caseId >= 0)
int caseId = RiaImportEclipseCaseTools::openEclipseCaseFromFile( gridCaseFile );
if ( caseId >= 0 )
{
openedFiles.insert(std::make_pair(gridCaseFile, caseId));
openedFiles.insert( std::make_pair( gridCaseFile, caseId ) );
}
}
// Import summary cases
if (!summaryFileInfos.empty())
if ( !summaryFileInfos.empty() )
{
RimSummaryCaseMainCollection* sumCaseColl = project->activeOilField() ? project->activeOilField()->summaryCaseMainCollection() : nullptr;
if (sumCaseColl)
RimSummaryCaseMainCollection* sumCaseColl = project->activeOilField()
? project->activeOilField()->summaryCaseMainCollection()
: nullptr;
if ( sumCaseColl )
{
std::vector<RimSummaryCase*> newSumCases = sumCaseColl->createSummaryCasesFromFileInfos(summaryFileInfos);
for (RimSummaryCase* newSumCase : newSumCases)
std::vector<RimSummaryCase*> newSumCases = sumCaseColl->createSummaryCasesFromFileInfos( summaryFileInfos );
for ( RimSummaryCase* newSumCase : newSumCases )
{
RimSummaryCaseCollection* existingCollection = nullptr;
QString gridCaseFile = RifEclipseSummaryTools::findGridCaseFileFromSummaryHeaderFile(newSumCase->summaryHeaderFilename());
RimEclipseCase* gridCase = project->eclipseCaseFromGridFileName(gridCaseFile);
if (gridCase)
QString gridCaseFile = RifEclipseSummaryTools::findGridCaseFileFromSummaryHeaderFile(
newSumCase->summaryHeaderFilename() );
RimEclipseCase* gridCase = project->eclipseCaseFromGridFileName( gridCaseFile );
if ( gridCase )
{
RimSummaryCase* existingSummaryCase = sumCaseColl->findSummaryCaseFromFileName(newSumCase->summaryHeaderFilename());
RimGridSummaryCase* existingGridSummaryCase = dynamic_cast<RimGridSummaryCase*>(existingSummaryCase);
RimFileSummaryCase* existingFileSummaryCase = dynamic_cast<RimFileSummaryCase*>(existingSummaryCase);
if (existingGridSummaryCase)
RimSummaryCase* existingSummaryCase = sumCaseColl->findSummaryCaseFromFileName(
newSumCase->summaryHeaderFilename() );
RimGridSummaryCase* existingGridSummaryCase = dynamic_cast<RimGridSummaryCase*>( existingSummaryCase );
RimFileSummaryCase* existingFileSummaryCase = dynamic_cast<RimFileSummaryCase*>( existingSummaryCase );
if ( existingGridSummaryCase )
{
delete newSumCase; // No need to add anything new. Already have one.
continue;
}
else if (existingFileSummaryCase)
else if ( existingFileSummaryCase )
{
existingFileSummaryCase->firstAncestorOrThisOfType(existingCollection);
existingFileSummaryCase->firstAncestorOrThisOfType( existingCollection );
// Replace all occurrences of file sum with ecl sum
std::vector<RimSummaryCurve*> objects;
existingFileSummaryCase->objectsWithReferringPtrFieldsOfType(objects);
existingFileSummaryCase->objectsWithReferringPtrFieldsOfType( objects );
// UI settings of a curve filter is updated based
// on the new case association for the curves in the curve filter
// UI is updated by loadDataAndUpdate()
for (RimSummaryCurve* summaryCurve : objects)
for ( RimSummaryCurve* summaryCurve : objects )
{
if (summaryCurve)
if ( summaryCurve )
{
RimSummaryCurveCollection* parentCollection = nullptr;
summaryCurve->firstAncestorOrThisOfType(parentCollection);
if (parentCollection)
summaryCurve->firstAncestorOrThisOfType( parentCollection );
if ( parentCollection )
{
parentCollection->loadDataAndUpdate(true);
parentCollection->loadDataAndUpdate( true );
parentCollection->updateConnectedEditors();
break;
}
@@ -147,43 +150,43 @@ bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& file
}
// Remove existing case
sumCaseColl->removeCase(existingFileSummaryCase);
sumCaseColl->removeCase( existingFileSummaryCase );
delete existingFileSummaryCase;
}
}
if (existingCollection)
if ( existingCollection )
{
existingCollection->addCase(newSumCase);
existingCollection->addCase( newSumCase );
}
else
{
sumCaseColl->addCase(newSumCase);
sumCaseColl->addCase( newSumCase );
}
sumCaseColl->updateAllRequiredEditors();
}
if (!newSumCases.empty())
if ( !newSumCases.empty() )
{
RimSummaryPlotCollection* summaryPlotColl = project->mainPlotCollection()->summaryPlotCollection();
RicSummaryPlotFeatureImpl::ensureAtLeastOnePlot(summaryPlotColl, newSumCases.front());
RicSummaryPlotFeatureImpl::ensureAtLeastOnePlot( summaryPlotColl, newSumCases.front() );
RiuPlotMainWindowTools::setExpanded(newSumCases.front());
RiuPlotMainWindowTools::setExpanded( newSumCases.front() );
}
}
}
if (selector.foundErrors())
if ( selector.foundErrors() )
{
QString errorMessage = selector.createCombinedErrorMessage();
RiaLogging::error(errorMessage);
RiaLogging::error( errorMessage );
}
project->activeOilField()->completionTemplateCollection()->setDefaultUnitSystemBasedOnLoadedCases();
RiuPlotMainWindowTools::refreshToolbars();
RiuPlotMainWindowTools::refreshToolbars();
if (openedFilesOut)
if ( openedFilesOut )
{
*openedFilesOut = openedFiles;
}
@@ -192,65 +195,67 @@ bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& file
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaImportEclipseCaseTools::openEclipseCaseFromFile(const QString& fileName)
int RiaImportEclipseCaseTools::openEclipseCaseFromFile( const QString& fileName )
{
if (!caf::Utils::fileExists(fileName)) return -1;
if ( !caf::Utils::fileExists( fileName ) ) return -1;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(fileName, false);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilter(const QString& fileName)
{
if (!caf::Utils::fileExists(fileName)) return false;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(fileName, true) >= 0;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( fileName, false );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames(const QStringList& fileNames, QString* fileContainingGrid/*=nullptr*/)
bool RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilter( const QString& fileName )
{
if ( !caf::Utils::fileExists( fileName ) ) return false;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( fileName, true ) >= 0;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames( const QStringList& fileNames,
QString* fileContainingGrid /*=nullptr*/ )
{
RimEclipseInputCase* rimInputReservoir = new RimEclipseInputCase();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
project->assignCaseIdToCase(rimInputReservoir);
project->assignCaseIdToCase( rimInputReservoir );
bool gridImportSuccess = rimInputReservoir->openDataFileSet(fileNames);
if (!gridImportSuccess)
bool gridImportSuccess = rimInputReservoir->openDataFileSet( fileNames );
if ( !gridImportSuccess )
{
RiaLogging::error("Failed to import grid");
RiaLogging::error( "Failed to import grid" );
return false;
}
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels() : nullptr;
if (analysisModels == nullptr) return false;
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels()
: nullptr;
if ( analysisModels == nullptr ) return false;
analysisModels->cases.push_back(rimInputReservoir);
analysisModels->cases.push_back( rimInputReservoir );
RimEclipseView* riv = rimInputReservoir->createAndAddReservoirView();
riv->cellResult()->setResultType(RiaDefines::INPUT_PROPERTY);
riv->cellResult()->setResultType( RiaDefines::INPUT_PROPERTY );
riv->loadDataAndUpdate();
if (!riv->cellResult()->hasResult())
if ( !riv->cellResult()->hasResult() )
{
riv->cellResult()->setResultVariable(RiaDefines::undefinedResultName());
riv->cellResult()->setResultVariable( RiaDefines::undefinedResultName() );
}
analysisModels->updateConnectedEditors();
Riu3DMainWindowTools::selectAsCurrentItem(riv->cellResult());
Riu3DMainWindowTools::selectAsCurrentItem( riv->cellResult() );
if (fileContainingGrid)
if ( fileContainingGrid )
{
*fileContainingGrid = rimInputReservoir->gridFileName();
}
@@ -259,44 +264,45 @@ bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames(const QStringL
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openMockModel(const QString& name)
bool RiaImportEclipseCaseTools::openMockModel( const QString& name )
{
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(name, false);
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( name, false );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(const QString& fileName, bool showTimeStepFilter)
int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( const QString& fileName, bool showTimeStepFilter )
{
QFileInfo gridFileName(fileName);
QString caseName = gridFileName.completeBaseName();
QFileInfo gridFileName( fileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, fileName);
rimResultReservoir->setCaseInfo( caseName, fileName );
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels() : nullptr;
if (analysisModels == nullptr)
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels()
: nullptr;
if ( analysisModels == nullptr )
{
delete rimResultReservoir;
return -1;
}
if (RiaGuiApplication::isRunning())
if ( RiaGuiApplication::isRunning() )
{
RicShowMainWindowFeature::showMainWindow();
}
analysisModels->cases.push_back(rimResultReservoir);
analysisModels->cases.push_back( rimResultReservoir );
if (!rimResultReservoir->importGridAndResultMetaData(showTimeStepFilter))
if ( !rimResultReservoir->importGridAndResultMetaData( showTimeStepFilter ) )
{
analysisModels->removeCaseFromAllGroups(rimResultReservoir);
analysisModels->removeCaseFromAllGroups( rimResultReservoir );
delete rimResultReservoir;
@@ -307,86 +313,87 @@ int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(const QStri
riv->loadDataAndUpdate();
if (!riv->cellResult()->hasResult())
if ( !riv->cellResult()->hasResult() )
{
riv->cellResult()->setResultVariable(RiaDefines::undefinedResultName());
riv->cellResult()->setResultVariable( RiaDefines::undefinedResultName() );
}
analysisModels->updateConnectedEditors();
if (RiaGuiApplication::isRunning())
if ( RiaGuiApplication::isRunning() )
{
RiuMainWindow::instance()->selectAsCurrentItem(riv->cellResult());
RiuMainWindow::instance()->selectAsCurrentItem( riv->cellResult() );
}
return rimResultReservoir->caseId();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup/*=nullptr*/)
bool RiaImportEclipseCaseTools::addEclipseCases( const QStringList& fileNames,
RimIdenticalGridCaseGroup** resultingCaseGroup /*=nullptr*/ )
{
if (fileNames.size() == 0) return true;
if ( fileNames.size() == 0 ) return true;
// First file is read completely including grid.
// The main grid from the first case is reused directly in for the other cases.
// The main grid from the first case is reused directly in for the other cases.
// When reading active cell info, only the total cell count is tested for consistency
RimEclipseResultCase* mainResultCase = nullptr;
std::vector< std::vector<int> > mainCaseGridDimensions;
RimIdenticalGridCaseGroup* gridCaseGroup = nullptr;
RimEclipseResultCase* mainResultCase = nullptr;
std::vector<std::vector<int>> mainCaseGridDimensions;
RimIdenticalGridCaseGroup* gridCaseGroup = nullptr;
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
{
QString firstFileName = fileNames[0];
QFileInfo gridFileName(firstFileName);
QString firstFileName = fileNames[0];
QFileInfo gridFileName( firstFileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, firstFileName);
if (!rimResultReservoir->openEclipseGridFile())
rimResultReservoir->setCaseInfo( caseName, firstFileName );
if ( !rimResultReservoir->openEclipseGridFile() )
{
delete rimResultReservoir;
return false;
}
rimResultReservoir->readGridDimensions(mainCaseGridDimensions);
rimResultReservoir->readGridDimensions( mainCaseGridDimensions );
mainResultCase = rimResultReservoir;
mainResultCase = rimResultReservoir;
RimOilField* oilField = project->activeOilField();
if (oilField && oilField->analysisModels())
if ( oilField && oilField->analysisModels() )
{
gridCaseGroup = oilField->analysisModels->createIdenticalCaseGroupFromMainCase(mainResultCase);
gridCaseGroup = oilField->analysisModels->createIdenticalCaseGroupFromMainCase( mainResultCase );
}
}
caf::ProgressInfo info(fileNames.size(), "Reading Active Cell data");
caf::ProgressInfo info( fileNames.size(), "Reading Active Cell data" );
for (int i = 1; i < fileNames.size(); i++)
for ( int i = 1; i < fileNames.size(); i++ )
{
QString caseFileName = fileNames[i];
QFileInfo gridFileName(caseFileName);
QString caseFileName = fileNames[i];
QFileInfo gridFileName( caseFileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, caseFileName);
rimResultReservoir->setCaseInfo( caseName, caseFileName );
std::vector< std::vector<int> > caseGridDimensions;
rimResultReservoir->readGridDimensions(caseGridDimensions);
std::vector<std::vector<int>> caseGridDimensions;
rimResultReservoir->readGridDimensions( caseGridDimensions );
bool identicalGrid = RigGridManager::isGridDimensionsEqual(mainCaseGridDimensions, caseGridDimensions);
if (identicalGrid)
bool identicalGrid = RigGridManager::isGridDimensionsEqual( mainCaseGridDimensions, caseGridDimensions );
if ( identicalGrid )
{
if (rimResultReservoir->openAndReadActiveCellData(mainResultCase->eclipseCaseData()))
if ( rimResultReservoir->openAndReadActiveCellData( mainResultCase->eclipseCaseData() ) )
{
RimOilField* oilField = project->activeOilField();
if (oilField && oilField->analysisModels())
if ( oilField && oilField->analysisModels() )
{
oilField->analysisModels()->insertCaseInCaseGroup(gridCaseGroup, rimResultReservoir);
oilField->analysisModels()->insertCaseInCaseGroup( gridCaseGroup, rimResultReservoir );
}
}
else
@@ -399,15 +406,15 @@ bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, Ri
delete rimResultReservoir;
}
info.setProgress(i);
info.setProgress( i );
}
if (gridCaseGroup)
if ( gridCaseGroup )
{
// Create placeholder results and propagate results info from main case to all other cases
// Create placeholder results and propagate results info from main case to all other cases
gridCaseGroup->loadMainCaseAndActiveCellInfo();
if (resultingCaseGroup)
if ( resultingCaseGroup )
{
*resultingCaseGroup = gridCaseGroup;
}
@@ -415,11 +422,11 @@ bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, Ri
project->activeOilField()->analysisModels()->updateConnectedEditors();
if (RiaGuiApplication::isRunning() && gridCaseGroup && gridCaseGroup->statisticsCaseCollection()->reservoirs.size() > 0)
if ( RiaGuiApplication::isRunning() && gridCaseGroup &&
gridCaseGroup->statisticsCaseCollection()->reservoirs.size() > 0 )
{
RiuMainWindow::instance()->selectAsCurrentItem(gridCaseGroup->statisticsCaseCollection()->reservoirs[0]);
RiuMainWindow::instance()->selectAsCurrentItem( gridCaseGroup->statisticsCaseCollection()->reservoirs[0] );
}
return true;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,23 +26,24 @@ class QStringList;
class RimIdenticalGridCaseGroup;
//==================================================================================================
///
///
//==================================================================================================
class RiaImportEclipseCaseTools
{
public:
typedef std::map<QString, int> FileCaseIdMap;
static bool openEclipseCasesFromFile(const QStringList& fileNames, FileCaseIdMap* openedFilesOut = nullptr, bool noDialog = false);
static bool openEclipseCaseShowTimeStepFilter(const QString& fileName);
static bool openEclipseInputCaseFromFileNames(const QStringList& fileNames, QString* fileContainingGrid = nullptr);
static bool openMockModel(const QString& name);
static bool addEclipseCases(const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup = nullptr);
static bool openEclipseCasesFromFile( const QStringList& fileNames,
FileCaseIdMap* openedFilesOut = nullptr,
bool noDialog = false );
static bool openEclipseCaseShowTimeStepFilter( const QString& fileName );
static bool openEclipseInputCaseFromFileNames( const QStringList& fileNames, QString* fileContainingGrid = nullptr );
static bool openMockModel( const QString& name );
static bool addEclipseCases( const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup = nullptr );
private:
static int openEclipseCaseFromFile(const QString& fileName);
static int openEclipseCaseShowTimeStepFilterImpl(const QString& fileName, bool showTimeStepFilter);
static int openEclipseCaseFromFile( const QString& fileName );
static int openEclipseCaseShowTimeStepFilterImpl( const QString& fileName, bool showTimeStepFilter );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,26 +22,24 @@
#include <sstream>
#ifdef WIN32
#pragma warning (push)
#pragma warning (disable: 4668)
#pragma warning( push )
#pragma warning( disable : 4668 )
// Define this one to tell windows.h to not define min() and max() as macros
#if defined WIN32 && !defined NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#pragma warning (pop)
#pragma warning( pop )
#else
#include <cstring>
#include <cstdio>
#include <cstring>
#endif
#include "QString"
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaDefaultConsoleLogger : public RiaLogger
@@ -49,33 +47,31 @@ class RiaDefaultConsoleLogger : public RiaLogger
public:
RiaDefaultConsoleLogger();
int level() const override;
void setLevel(int logLevel) override;
void error( const char* message) override;
void warning(const char* message) override;
void info( const char* message) override;
void debug( const char* message) override;
int level() const override;
void setLevel( int logLevel ) override;
void error( const char* message ) override;
void warning( const char* message ) override;
void info( const char* message ) override;
void debug( const char* message ) override;
private:
static void writeMessageToConsole(const char* prefix, const char* message);
static void writeToConsole(const std::string& str);
static void writeMessageToConsole( const char* prefix, const char* message );
static void writeToConsole( const std::string& str );
private:
int m_logLevel;
int m_logLevel;
};
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaDefaultConsoleLogger::RiaDefaultConsoleLogger()
: m_logLevel(RI_LL_WARNING)
: m_logLevel( RI_LL_WARNING )
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaDefaultConsoleLogger::level() const
{
@@ -83,59 +79,56 @@ int RiaDefaultConsoleLogger::level() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::setLevel(int logLevel)
void RiaDefaultConsoleLogger::setLevel( int logLevel )
{
m_logLevel = logLevel;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::error(const char* message)
void RiaDefaultConsoleLogger::error( const char* message )
{
writeMessageToConsole("ERROR: ", message);
writeMessageToConsole( "ERROR: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::warning(const char* message)
void RiaDefaultConsoleLogger::warning( const char* message )
{
writeMessageToConsole("warn: ", message);
writeMessageToConsole( "warn: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::info(const char* message)
void RiaDefaultConsoleLogger::info( const char* message )
{
writeMessageToConsole("info: ", message);
writeMessageToConsole( "info: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::debug(const char* message)
void RiaDefaultConsoleLogger::debug( const char* message )
{
writeMessageToConsole("debug: ", message);
writeMessageToConsole( "debug: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::writeMessageToConsole(const char* prefix, const char* message)
void RiaDefaultConsoleLogger::writeMessageToConsole( const char* prefix, const char* message )
{
std::ostringstream oss;
// VF_ASSERT(prefix);
// VF_ASSERT(prefix);
oss << prefix;
if (message)
if ( message )
{
oss << message << std::endl;
}
@@ -144,54 +137,52 @@ void RiaDefaultConsoleLogger::writeMessageToConsole(const char* prefix, const ch
oss << "<no message>" << std::endl;
}
writeToConsole(oss.str());
writeToConsole( oss.str() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::writeToConsole(const std::string& str)
void RiaDefaultConsoleLogger::writeToConsole( const std::string& str )
{
#ifdef WIN32
AllocConsole();
HANDLE hStdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdOutputHandle)
HANDLE hStdOutputHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if ( hStdOutputHandle )
{
DWORD stringLength = static_cast<DWORD>(str.length());
DWORD stringLength = static_cast<DWORD>( str.length() );
unsigned long iDum = 0;
WriteConsoleA(hStdOutputHandle, str.c_str(), stringLength, &iDum, nullptr);
WriteConsoleA( hStdOutputHandle, str.c_str(), stringLength, &iDum, nullptr );
}
#else
fputs(str.c_str(), stderr);
fputs( str.c_str(), stderr );
#endif
}
//==================================================================================================
//
//
//
//
//==================================================================================================
RiaLogger* RiaLogging::sm_logger = new RiaDefaultConsoleLogger;
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaLogger* RiaLogging::loggerInstance()
{
return sm_logger;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::setLoggerInstance(RiaLogger* loggerInstance)
void RiaLogging::setLoggerInstance( RiaLogger* loggerInstance )
{
// Only delete if we're currently using our own default impl
if (dynamic_cast<RiaDefaultConsoleLogger*>(sm_logger))
if ( dynamic_cast<RiaDefaultConsoleLogger*>( sm_logger ) )
{
delete sm_logger;
}
@@ -199,9 +190,8 @@ void RiaLogging::setLoggerInstance(RiaLogger* loggerInstance)
sm_logger = loggerInstance;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::deleteLoggerInstance()
{
@@ -210,50 +200,50 @@ void RiaLogging::deleteLoggerInstance()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::error(const QString& message)
void RiaLogging::error( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_ERROR)
if ( sm_logger && sm_logger->level() >= RI_LL_ERROR )
{
#pragma omp critical(critical_section_logging)
sm_logger->error(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->error( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::warning(const QString& message)
void RiaLogging::warning( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_WARNING)
if ( sm_logger && sm_logger->level() >= RI_LL_WARNING )
{
#pragma omp critical(critical_section_logging)
sm_logger->warning(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->warning( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::info(const QString& message)
void RiaLogging::info( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_INFO)
if ( sm_logger && sm_logger->level() >= RI_LL_INFO )
{
#pragma omp critical(critical_section_logging)
sm_logger->info(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->info( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::debug(const QString& message)
void RiaLogging::debug( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_DEBUG)
if ( sm_logger && sm_logger->level() >= RI_LL_DEBUG )
{
#pragma omp critical(critical_section_logging)
sm_logger->debug(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->debug( message.toLatin1().constData() );
}
}
@@ -261,7 +251,7 @@ void RiaLogging::debug(const QString& message)
///
//--------------------------------------------------------------------------------------------------
RiuMessageLoggerBase::RiuMessageLoggerBase()
: m_logLevel(RI_LL_WARNING)
: m_logLevel( RI_LL_WARNING )
{
}
@@ -276,7 +266,7 @@ int RiuMessageLoggerBase::level() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::setLevel(int logLevel)
void RiuMessageLoggerBase::setLevel( int logLevel )
{
m_logLevel = logLevel;
}
@@ -284,45 +274,45 @@ void RiuMessageLoggerBase::setLevel(int logLevel)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::error(const char* message)
void RiuMessageLoggerBase::error( const char* message )
{
writeMessageWithPrefixToLogger("ERROR: ", message);
writeMessageWithPrefixToLogger( "ERROR: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::warning(const char* message)
void RiuMessageLoggerBase::warning( const char* message )
{
writeMessageWithPrefixToLogger("warning: ", message);
writeMessageWithPrefixToLogger( "warning: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::info(const char* message)
void RiuMessageLoggerBase::info( const char* message )
{
writeMessageWithPrefixToLogger("info: ", message);
writeMessageWithPrefixToLogger( "info: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::debug(const char* message)
void RiuMessageLoggerBase::debug( const char* message )
{
writeMessageWithPrefixToLogger("debug: ", message);
writeMessageWithPrefixToLogger( "debug: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::writeMessageWithPrefixToLogger(const char* prefix, const char* message)
void RiuMessageLoggerBase::writeMessageWithPrefixToLogger( const char* prefix, const char* message )
{
std::ostringstream oss;
oss << prefix;
if (message)
if ( message )
{
oss << message << std::endl;
}
@@ -331,13 +321,13 @@ void RiuMessageLoggerBase::writeMessageWithPrefixToLogger(const char* prefix, co
oss << "<no message>" << std::endl;
}
writeMessageToLogger(oss.str());
writeMessageToLogger( oss.str() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaStdOutLogger::writeMessageToLogger(const std::string& str)
void RiaStdOutLogger::writeMessageToLogger( const std::string& str )
{
std::cout << str;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -24,14 +24,12 @@ class QString;
enum RILogLevel
{
RI_LL_ERROR = 1,
RI_LL_ERROR = 1,
RI_LL_WARNING = 2,
RI_LL_INFO = 3,
RI_LL_DEBUG = 4
RI_LL_INFO = 3,
RI_LL_DEBUG = 4
};
//==================================================================================================
//
// Logger interface for the application
@@ -42,36 +40,34 @@ class RiaLogger
public:
virtual ~RiaLogger() {}
virtual int level() const = 0;
virtual void setLevel(int logLevel) = 0;
virtual int level() const = 0;
virtual void setLevel( int logLevel ) = 0;
virtual void error( const char* message) = 0;
virtual void warning(const char* message) = 0;
virtual void info( const char* message) = 0;
virtual void debug( const char* message) = 0;
virtual void error( const char* message ) = 0;
virtual void warning( const char* message ) = 0;
virtual void info( const char* message ) = 0;
virtual void debug( const char* message ) = 0;
};
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaLogging
{
public:
static RiaLogger* loggerInstance();
static void setLoggerInstance(RiaLogger* loggerInstance);
static void deleteLoggerInstance();
static RiaLogger* loggerInstance();
static void setLoggerInstance( RiaLogger* loggerInstance );
static void deleteLoggerInstance();
static void error( const QString& message);
static void warning(const QString& message);
static void info( const QString& message);
static void debug( const QString& message);
static void error( const QString& message );
static void warning( const QString& message );
static void info( const QString& message );
static void debug( const QString& message );
private:
static RiaLogger* sm_logger;
static RiaLogger* sm_logger;
};
//==================================================================================================
@@ -83,18 +79,18 @@ public:
explicit RiuMessageLoggerBase();
int level() const override;
void setLevel(int logLevel) override;
void setLevel( int logLevel ) override;
void error(const char* message) override;
void warning(const char* message) override;
void info(const char* message) override;
void debug(const char* message) override;
void error( const char* message ) override;
void warning( const char* message ) override;
void info( const char* message ) override;
void debug( const char* message ) override;
protected:
virtual void writeMessageToLogger(const std::string& str) = 0;
virtual void writeMessageToLogger( const std::string& str ) = 0;
private:
void writeMessageWithPrefixToLogger(const char* prefix, const char* message);
void writeMessageWithPrefixToLogger( const char* prefix, const char* message );
private:
int m_logLevel;
@@ -106,5 +102,5 @@ private:
class RiaStdOutLogger : public RiuMessageLoggerBase
{
public:
void writeMessageToLogger(const std::string& str) override;
void writeMessageToLogger( const std::string& str ) override;
};

View File

@@ -18,8 +18,8 @@
#pragma once
#include <array>
#include "cvfVector3.h"
#include <array>
#include <cmath>
// Y - North, X - East, Z - up but depth is negative Z
@@ -31,49 +31,61 @@ const double singularityEpsilon = 1.0e-5;
class RiaOffshoreSphericalCoords
{
public:
explicit RiaOffshoreSphericalCoords(const cvf::Vec3f& vec)
explicit RiaOffshoreSphericalCoords( const cvf::Vec3f& vec )
{
// Azimuth:
if ( fabs(vec[0]) < singularityEpsilon && fabs(vec[1]) < singularityEpsilon ) incAziR[1] = 0.0f;
else incAziR[1] = atan2(vec[0], vec[1]); // atan2(Y, X)
// Azimuth:
if ( fabs( vec[0] ) < singularityEpsilon && fabs( vec[1] ) < singularityEpsilon )
incAziR[1] = 0.0f;
else
incAziR[1] = atan2( vec[0], vec[1] ); // atan2(Y, X)
// R
incAziR[2] = vec.length();
// Inclination from vertical down
if (fabs( incAziR[2]) < singularityEpsilon) incAziR[0] = 0.0f;
else incAziR[0] = acos(-vec[2]/incAziR[2]);
if ( fabs( incAziR[2] ) < singularityEpsilon )
incAziR[0] = 0.0f;
else
incAziR[0] = acos( -vec[2] / incAziR[2] );
}
explicit RiaOffshoreSphericalCoords(const cvf::Vec3d& vec)
explicit RiaOffshoreSphericalCoords( const cvf::Vec3d& vec )
{
// Azimuth:
if (fabs(vec[0]) < singularityEpsilon && fabs(vec[1]) < singularityEpsilon ) incAziR[1] = 0.0;
else incAziR[1] = atan2(vec[0], vec[1]); // atan2(Y, X)
// Azimuth:
if ( fabs( vec[0] ) < singularityEpsilon && fabs( vec[1] ) < singularityEpsilon )
incAziR[1] = 0.0;
else
incAziR[1] = atan2( vec[0], vec[1] ); // atan2(Y, X)
// R
// R
incAziR[2] = vec.length();
// Inclination from vertical down
if (fabs( incAziR[2]) < singularityEpsilon) incAziR[0] = 0.0;
else incAziR[0] = acos(-vec[2]/incAziR[2]);
if ( fabs( incAziR[2] ) < singularityEpsilon )
incAziR[0] = 0.0;
else
incAziR[0] = acos( -vec[2] / incAziR[2] );
}
double inc() const
{
return incAziR[0];
}
double azi() const
{
return incAziR[1];
}
double r() const
{
return incAziR[2];
}
double inc() const { return incAziR[0];}
double azi() const { return incAziR[1];}
double r() const { return incAziR[2];}
// Note that this is a double function, while the rest of the class is float.
// Todo: Convert class to a template to enable float and double versions of everything
static cvf::Vec3d unitVectorFromAziInc(double azimuth, double inclination)
static cvf::Vec3d unitVectorFromAziInc( double azimuth, double inclination )
{
return cvf::Vec3d(sin(azimuth)*sin(inclination),
cos(azimuth)*sin(inclination),
-cos(inclination));
return cvf::Vec3d( sin( azimuth ) * sin( inclination ), cos( azimuth ) * sin( inclination ), -cos( inclination ) );
}
private:
std::array<double, 3> incAziR;
};

View File

@@ -24,15 +24,16 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName(Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems)
void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName( Rim3dView* view,
QList<caf::PdmOptionItemInfo>* optionItems )
{
if (!view || !optionItems) return;
if ( !view || !optionItems ) return;
QString caseName;
RimCase* rimCase = nullptr;
view->firstAncestorOrThisOfType(rimCase);
if (rimCase)
view->firstAncestorOrThisOfType( rimCase );
if ( rimCase )
{
caseName = rimCase->caseUserDescription();
}
@@ -45,5 +46,5 @@ void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName(Rim3dView* vi
caf::QIconProvider iconProvider = view->uiCapability()->uiIconProvider();
optionItems->push_back(caf::PdmOptionItemInfo(displayName, view, false, iconProvider));
optionItems->push_back( caf::PdmOptionItemInfo( displayName, view, false, iconProvider ) );
}

View File

@@ -27,5 +27,5 @@ class Rim3dView;
class RiaOptionItemFactory
{
public:
static void appendOptionItemFromViewNameAndCaseName(Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems);
static void appendOptionItemFromViewNameAndCaseName( Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems );
};

View File

@@ -23,62 +23,73 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectFileVersionTools::isCandidateVersionNewerThanOther(const QString& candidateProjectFileVersion,
const QString& projectFileVersion)
bool RiaProjectFileVersionTools::isCandidateVersionNewerThanOther( const QString& candidateProjectFileVersion,
const QString& projectFileVersion )
{
int candidateMajorVersion = 0;
int candidateMinorVersion = 0;
int candidatePatchNumber = 0;
int candidateDevelopmentId = 0;
RiaProjectFileVersionTools::decodeVersionString(candidateProjectFileVersion, &candidateMajorVersion, &candidateMinorVersion,
&candidatePatchNumber, &candidateDevelopmentId);
RiaProjectFileVersionTools::decodeVersionString( candidateProjectFileVersion,
&candidateMajorVersion,
&candidateMinorVersion,
&candidatePatchNumber,
&candidateDevelopmentId );
int majorVersion = 0;
int minorVersion = 0;
int patchNumber = 0;
int developmentId = 0;
RiaProjectFileVersionTools::decodeVersionString(projectFileVersion, &majorVersion, &minorVersion, &patchNumber,
&developmentId);
RiaProjectFileVersionTools::decodeVersionString( projectFileVersion,
&majorVersion,
&minorVersion,
&patchNumber,
&developmentId );
return RiaProjectFileVersionTools::isCandidateNewerThanOther(candidateMajorVersion, candidateMinorVersion,
candidatePatchNumber, candidateDevelopmentId, majorVersion,
minorVersion, patchNumber, developmentId);
return RiaProjectFileVersionTools::isCandidateNewerThanOther( candidateMajorVersion,
candidateMinorVersion,
candidatePatchNumber,
candidateDevelopmentId,
majorVersion,
minorVersion,
patchNumber,
developmentId );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectFileVersionTools::decodeVersionString(const QString& projectFileVersion, int* majorVersion, int* minorVersion,
int* patch, int* developmentId)
void RiaProjectFileVersionTools::decodeVersionString(
const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch, int* developmentId )
{
if (projectFileVersion.isEmpty()) return;
if ( projectFileVersion.isEmpty() ) return;
QStringList subStrings = projectFileVersion.split(".");
QStringList subStrings = projectFileVersion.split( "." );
if (subStrings.size() > 0)
if ( subStrings.size() > 0 )
{
*majorVersion = subStrings[0].toInt();
}
if (subStrings.size() > 1)
if ( subStrings.size() > 1 )
{
*minorVersion = subStrings[1].toInt();
}
if (subStrings.size() > 2)
if ( subStrings.size() > 2 )
{
QString candidate = subStrings[2];
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits(candidate);
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits( candidate );
*patch = candidateDigitsOnly.toInt();
}
if (subStrings.size() > 3)
if ( subStrings.size() > 3 )
{
QString candidate = subStrings.back();
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits(candidate);
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits( candidate );
*developmentId = candidateDigitsOnly.toInt();
}
@@ -87,29 +98,33 @@ void RiaProjectFileVersionTools::decodeVersionString(const QString& projectFileV
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectFileVersionTools::isCandidateNewerThanOther(int candidateMajorVersion, int candidateMinorVersion,
int candidatePatchNumber, int candidateDevelopmentId,
int otherMajorVersion, int otherMinorVersion, int otherPatchNumber,
int otherDevelopmentId)
bool RiaProjectFileVersionTools::isCandidateNewerThanOther( int candidateMajorVersion,
int candidateMinorVersion,
int candidatePatchNumber,
int candidateDevelopmentId,
int otherMajorVersion,
int otherMinorVersion,
int otherPatchNumber,
int otherDevelopmentId )
{
if (candidateMajorVersion != otherMajorVersion)
if ( candidateMajorVersion != otherMajorVersion )
{
return (candidateMajorVersion > otherMajorVersion);
return ( candidateMajorVersion > otherMajorVersion );
}
if (candidateMinorVersion != otherMinorVersion)
if ( candidateMinorVersion != otherMinorVersion )
{
return (candidateMinorVersion > otherMinorVersion);
return ( candidateMinorVersion > otherMinorVersion );
}
if (candidatePatchNumber != otherPatchNumber)
if ( candidatePatchNumber != otherPatchNumber )
{
return (candidatePatchNumber > otherPatchNumber);
return ( candidatePatchNumber > otherPatchNumber );
}
if (candidateDevelopmentId != otherDevelopmentId)
if ( candidateDevelopmentId != otherDevelopmentId )
{
return (candidateDevelopmentId > otherDevelopmentId);
return ( candidateDevelopmentId > otherDevelopmentId );
}
return false;
@@ -118,19 +133,19 @@ bool RiaProjectFileVersionTools::isCandidateNewerThanOther(int candidateMajorVer
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaProjectFileVersionTools::stringOfDigits(const QString& string)
QString RiaProjectFileVersionTools::stringOfDigits( const QString& string )
{
QString digitsOnly;
for (const auto& c : string)
for ( const auto& c : string )
{
if (c.isDigit())
if ( c.isDigit() )
{
digitsOnly += c;
}
else
{
if (!digitsOnly.isEmpty())
if ( !digitsOnly.isEmpty() )
{
return digitsOnly;
}
@@ -139,4 +154,3 @@ QString RiaProjectFileVersionTools::stringOfDigits(const QString& string)
return digitsOnly;
}

View File

@@ -26,17 +26,22 @@
class RiaProjectFileVersionTools
{
public:
static bool isCandidateVersionNewerThanOther(const QString& candidateProjectFileVersion,
const QString& otherProjectFileVersion);
static bool isCandidateVersionNewerThanOther( const QString& candidateProjectFileVersion,
const QString& otherProjectFileVersion );
// Public to be able to unit test function, not intended to be used
static void decodeVersionString(const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch,
int* developmentId);
static void decodeVersionString(
const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch, int* developmentId );
private:
static bool isCandidateNewerThanOther(int candidateMajorVersion, int candidateMinorVersion, int candidatePatchNumber,
int candidateDevelopmentId, int otherMajorVersion, int otherMinorVersion,
int otherPatchNumber, int otherDevelopmentId);
static bool isCandidateNewerThanOther( int candidateMajorVersion,
int candidateMinorVersion,
int candidatePatchNumber,
int candidateDevelopmentId,
int otherMajorVersion,
int otherMinorVersion,
int otherPatchNumber,
int otherDevelopmentId );
static QString stringOfDigits(const QString& string);
static QString stringOfDigits( const QString& string );
};

View File

@@ -2,17 +2,17 @@
//
// Copyright (C) Statoil ASA
// Copyright (C) Ceetron Solutions AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -28,131 +28,128 @@
#include "RimOilField.h"
#include "RimProject.h"
#include <QFileInfo>
#include <QDir>
#include <QFileInfo>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaProjectModifier::RiaProjectModifier()
RiaProjectModifier::RiaProjectModifier() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCaseFirstOccurrence( QString newGridFileName )
{
m_caseIdToGridFileNameMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute( newGridFileName );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCaseFirstOccurrence(QString newGridFileName)
void RiaProjectModifier::setReplaceCase( int caseIdToReplace, QString newGridFileName )
{
m_caseIdToGridFileNameMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute(newGridFileName);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCase(int caseIdToReplace, QString newGridFileName)
{
if (caseIdToReplace >= 0)
if ( caseIdToReplace >= 0 )
{
m_caseIdToGridFileNameMap[caseIdToReplace] = makeFilePathAbsolute(newGridFileName);
m_caseIdToGridFileNameMap[caseIdToReplace] = makeFilePathAbsolute( newGridFileName );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceSourceCasesFirstOccurrence(std::vector<QString> newGridFileNames)
void RiaProjectModifier::setReplaceSourceCasesFirstOccurrence( std::vector<QString> newGridFileNames )
{
m_groupIdToGridFileNamesMap[RiaProjectModifier::firstOccurrenceId()] = newGridFileNames;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceSourceCasesById(int caseGroupIdToReplace, std::vector<QString> newGridFileNames)
void RiaProjectModifier::setReplaceSourceCasesById( int caseGroupIdToReplace, std::vector<QString> newGridFileNames )
{
if (caseGroupIdToReplace >= 0)
if ( caseGroupIdToReplace >= 0 )
{
m_groupIdToGridFileNamesMap[caseGroupIdToReplace] = newGridFileNames;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplacePropertiesFolderFirstOccurrence(QString newPropertiesFolder)
void RiaProjectModifier::setReplacePropertiesFolderFirstOccurrence( QString newPropertiesFolder )
{
m_caseIdToPropertiesFolderMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute(newPropertiesFolder);
m_caseIdToPropertiesFolderMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute( newPropertiesFolder );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplacePropertiesFolder(int caseIdToReplace, QString newPropertiesFolder)
void RiaProjectModifier::setReplacePropertiesFolder( int caseIdToReplace, QString newPropertiesFolder )
{
if (caseIdToReplace >= 0)
if ( caseIdToReplace >= 0 )
{
m_caseIdToPropertiesFolderMap[caseIdToReplace] = makeFilePathAbsolute(newPropertiesFolder);
m_caseIdToPropertiesFolderMap[caseIdToReplace] = makeFilePathAbsolute( newPropertiesFolder );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectModifier::applyModificationsToProject(RimProject* project)
bool RiaProjectModifier::applyModificationsToProject( RimProject* project )
{
if (m_caseIdToGridFileNameMap.size() > 0)
if ( m_caseIdToGridFileNameMap.size() > 0 )
{
replaceCase(project);
replaceCase( project );
}
if (m_groupIdToGridFileNamesMap.size() > 0)
if ( m_groupIdToGridFileNamesMap.size() > 0 )
{
replaceSourceCases(project);
replaceSourceCases( project );
}
if (m_caseIdToPropertiesFolderMap.size() > 0)
if ( m_caseIdToPropertiesFolderMap.size() > 0 )
{
replacePropertiesFolder(project);
replacePropertiesFolder( project );
}
return true;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replaceSourceCases(RimProject* project)
void RiaProjectModifier::replaceSourceCases( RimProject* project )
{
for (RimOilField* oilField : project->oilFields())
for ( RimOilField* oilField : project->oilFields() )
{
RimEclipseCaseCollection* analysisModels = oilField ? oilField->analysisModels() : nullptr;
if (analysisModels)
if ( analysisModels )
{
for (RimIdenticalGridCaseGroup* caseGroup : analysisModels->caseGroups)
for ( RimIdenticalGridCaseGroup* caseGroup : analysisModels->caseGroups )
{
for (auto item : m_groupIdToGridFileNamesMap)
for ( auto item : m_groupIdToGridFileNamesMap )
{
int groupIdToReplace = item.first;
if (groupIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( groupIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
groupIdToReplace = firstGroupId(project);
groupIdToReplace = firstGroupId( project );
}
if (groupIdToReplace == caseGroup->groupId())
if ( groupIdToReplace == caseGroup->groupId() )
{
RimCaseCollection* caseCollection = caseGroup->caseCollection;
caseCollection->reservoirs.deleteAllChildObjects();
for (QString fileName : item.second)
for ( QString fileName : item.second )
{
QString caseName = caseNameFromGridFileName(fileName);
QString caseName = caseNameFromGridFileName( fileName );
// Use this slightly hackish method in order to get a new unique ID
RimEclipseResultCase* resCase = new RimEclipseResultCase;
resCase->setCaseInfo(caseName, fileName);
resCase->setCaseInfo( caseName, fileName );
caseCollection->reservoirs.push_back(resCase);
caseCollection->reservoirs.push_back( resCase );
}
}
}
@@ -162,39 +159,39 @@ void RiaProjectModifier::replaceSourceCases(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replaceCase(RimProject* project)
void RiaProjectModifier::replaceCase( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
for (RimCase* rimCase : allCases)
project->allCases( allCases );
for ( RimCase* rimCase : allCases )
{
RimEclipseResultCase* eclipseResultCase = dynamic_cast<RimEclipseResultCase*>(rimCase);
RimGeoMechCase* geomechCase = dynamic_cast<RimGeoMechCase*>(rimCase);
if (eclipseResultCase || geomechCase)
RimEclipseResultCase* eclipseResultCase = dynamic_cast<RimEclipseResultCase*>( rimCase );
RimGeoMechCase* geomechCase = dynamic_cast<RimGeoMechCase*>( rimCase );
if ( eclipseResultCase || geomechCase )
{
for (auto item : m_caseIdToGridFileNameMap)
for ( auto item : m_caseIdToGridFileNameMap )
{
int caseIdToReplace = item.first;
if (caseIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( caseIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
caseIdToReplace = firstCaseId(project);
caseIdToReplace = firstCaseId( project );
}
if (caseIdToReplace == rimCase->caseId())
if ( caseIdToReplace == rimCase->caseId() )
{
QString replaceFileName = item.second;
if (eclipseResultCase)
if ( eclipseResultCase )
{
eclipseResultCase->setGridFileName(replaceFileName);
eclipseResultCase->caseUserDescription = caseNameFromGridFileName(replaceFileName);
eclipseResultCase->setGridFileName( replaceFileName );
eclipseResultCase->caseUserDescription = caseNameFromGridFileName( replaceFileName );
}
else if (geomechCase)
else if ( geomechCase )
{
geomechCase->setFileName(replaceFileName);
geomechCase->caseUserDescription = caseNameFromGridFileName(replaceFileName);
geomechCase->setFileName( replaceFileName );
geomechCase->caseUserDescription = caseNameFromGridFileName( replaceFileName );
}
}
}
@@ -203,31 +200,31 @@ void RiaProjectModifier::replaceCase(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replacePropertiesFolder(RimProject* project)
void RiaProjectModifier::replacePropertiesFolder( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseInputCase* inputCase = dynamic_cast<RimEclipseInputCase*>(rimCase);
RimEclipseInputCase* inputCase = dynamic_cast<RimEclipseInputCase*>( rimCase );
if (inputCase)
if ( inputCase )
{
for (auto item : m_caseIdToPropertiesFolderMap)
for ( auto item : m_caseIdToPropertiesFolderMap )
{
int caseIdToReplace = item.first;
if (caseIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( caseIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
caseIdToReplace = firstInputCaseId(project);
caseIdToReplace = firstInputCaseId( project );
}
if (caseIdToReplace == inputCase->caseId())
if ( caseIdToReplace == inputCase->caseId() )
{
inputCase->updateAdditionalFileFolder(item.second);
inputCase->updateAdditionalFileFolder( item.second );
}
}
}
@@ -235,45 +232,45 @@ void RiaProjectModifier::replacePropertiesFolder(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
/// Returns absolute path name to the specified file.
///
/// Returns absolute path name to the specified file.
///
/// If \a relOrAbsolutePath is a relative, the current working directory for the process will be
/// used in order to make the path absolute.
//--------------------------------------------------------------------------------------------------
QString RiaProjectModifier::makeFilePathAbsolute(QString relOrAbsolutePath)
QString RiaProjectModifier::makeFilePathAbsolute( QString relOrAbsolutePath )
{
QFileInfo theFile(relOrAbsolutePath);
QFileInfo theFile( relOrAbsolutePath );
theFile.makeAbsolute();
return theFile.filePath();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaProjectModifier::caseNameFromGridFileName(QString fullGridFilePathName)
QString RiaProjectModifier::caseNameFromGridFileName( QString fullGridFilePathName )
{
QString fn = QDir::fromNativeSeparators(fullGridFilePathName);
// Extract file name plus the 'deepest' directory
QString deepestDirPlusFileName = fn.section('/', -2, -1);
QString fn = QDir::fromNativeSeparators( fullGridFilePathName );
deepestDirPlusFileName.replace("/", "--");
// Extract file name plus the 'deepest' directory
QString deepestDirPlusFileName = fn.section( '/', -2, -1 );
deepestDirPlusFileName.replace( "/", "--" );
return deepestDirPlusFileName;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstCaseId(RimProject* project)
int RiaProjectModifier::firstCaseId( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseResultCase* resultCase = dynamic_cast<RimEclipseResultCase*>(rimCase);
if (resultCase)
RimEclipseResultCase* resultCase = dynamic_cast<RimEclipseResultCase*>( rimCase );
if ( resultCase )
{
return resultCase->caseId();
}
@@ -283,17 +280,17 @@ int RiaProjectModifier::firstCaseId(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstGroupId(RimProject* project)
int RiaProjectModifier::firstGroupId( RimProject* project )
{
for (size_t oilFieldIdx = 0; oilFieldIdx < project->oilFields().size(); oilFieldIdx++)
for ( size_t oilFieldIdx = 0; oilFieldIdx < project->oilFields().size(); oilFieldIdx++ )
{
RimOilField* oilField = project->oilFields[oilFieldIdx];
RimOilField* oilField = project->oilFields[oilFieldIdx];
RimEclipseCaseCollection* analysisModels = oilField ? oilField->analysisModels() : nullptr;
if (analysisModels)
if ( analysisModels )
{
if (analysisModels->caseGroups.size() > 0)
if ( analysisModels->caseGroups.size() > 0 )
{
return analysisModels->caseGroups[0]->groupId();
}
@@ -304,17 +301,17 @@ int RiaProjectModifier::firstGroupId(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstInputCaseId(RimProject * project)
int RiaProjectModifier::firstInputCaseId( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseInputCase* resultCase = dynamic_cast<RimEclipseInputCase*>(rimCase);
if (resultCase)
RimEclipseInputCase* resultCase = dynamic_cast<RimEclipseInputCase*>( rimCase );
if ( resultCase )
{
return resultCase->caseId();
}
@@ -324,10 +321,9 @@ int RiaProjectModifier::firstInputCaseId(RimProject * project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstOccurrenceId()
{
return -999;
}

View File

@@ -2,38 +2,35 @@
//
// Copyright (C) Statoil ASA
// Copyright (C) Ceetron Solutions AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "cvfObject.h"
#include <QString>
#include <vector>
#include <map>
#include <vector>
class RimProject;
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaProjectModifier : public cvf::Object
@@ -41,34 +38,33 @@ class RiaProjectModifier : public cvf::Object
public:
RiaProjectModifier();
void setReplaceCaseFirstOccurrence(QString newGridFileName);
void setReplaceCase(int caseIdToReplace, QString newGridFileName);
void setReplaceCaseFirstOccurrence( QString newGridFileName );
void setReplaceCase( int caseIdToReplace, QString newGridFileName );
void setReplaceSourceCasesFirstOccurrence(std::vector<QString> newGridFileNames);
void setReplaceSourceCasesById(int caseGroupIdToReplace, std::vector<QString> newGridFileNames);
void setReplaceSourceCasesFirstOccurrence( std::vector<QString> newGridFileNames );
void setReplaceSourceCasesById( int caseGroupIdToReplace, std::vector<QString> newGridFileNames );
void setReplacePropertiesFolderFirstOccurrence(QString newPropertiesFolder);
void setReplacePropertiesFolder(int caseIdToReplace, QString newPropertiesFolder);
void setReplacePropertiesFolderFirstOccurrence( QString newPropertiesFolder );
void setReplacePropertiesFolder( int caseIdToReplace, QString newPropertiesFolder );
bool applyModificationsToProject(RimProject* project);
bool applyModificationsToProject( RimProject* project );
private:
void replaceSourceCases(RimProject* project);
void replaceCase(RimProject* project);
void replacePropertiesFolder(RimProject* project);
void replaceSourceCases( RimProject* project );
void replaceCase( RimProject* project );
void replacePropertiesFolder( RimProject* project );
static QString makeFilePathAbsolute(QString relOrAbsolutePath);
static QString caseNameFromGridFileName(QString fullGridFilePathName);
static QString makeFilePathAbsolute( QString relOrAbsolutePath );
static QString caseNameFromGridFileName( QString fullGridFilePathName );
static int firstCaseId(RimProject* project);
static int firstGroupId(RimProject* project);
static int firstInputCaseId(RimProject* project);
static int firstCaseId( RimProject* project );
static int firstGroupId( RimProject* project );
static int firstInputCaseId( RimProject* project );
static int firstOccurrenceId();
static int firstOccurrenceId();
private:
std::map<int, QString> m_caseIdToGridFileNameMap;
std::map<int, std::vector<QString> > m_groupIdToGridFileNamesMap;
std::map<int, QString> m_caseIdToPropertiesFolderMap;
std::map<int, QString> m_caseIdToGridFileNameMap;
std::map<int, std::vector<QString>> m_groupIdToGridFileNamesMap;
std::map<int, QString> m_caseIdToPropertiesFolderMap;
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,55 +25,53 @@
#include "cafAppEnum.h"
#include <cvfAssert.h>
#include <ctime>
#include <cmath>
#include <ctime>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DAY = DateTimeSpan(0, 0, 1);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_WEEK = DateTimeSpan(0, 0, 7);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_MONTH = DateTimeSpan(0, 1, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_QUARTER = DateTimeSpan(0, 3, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_HALFYEAR = DateTimeSpan(0, 6, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_YEAR = DateTimeSpan(1, 0, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DECADE = DateTimeSpan(10, 0, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DAY = DateTimeSpan( 0, 0, 1 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_WEEK = DateTimeSpan( 0, 0, 7 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_MONTH = DateTimeSpan( 0, 1, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_QUARTER = DateTimeSpan( 0, 3, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_HALFYEAR = DateTimeSpan( 0, 6, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_YEAR = DateTimeSpan( 1, 0, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DECADE = DateTimeSpan( 10, 0, 0 );
const QString RiaQDateTimeTools::TIMESPAN_DAY_NAME = "Day";
const QString RiaQDateTimeTools::TIMESPAN_WEEK_NAME = "Week";
const QString RiaQDateTimeTools::TIMESPAN_MONTH_NAME = "Month";
const QString RiaQDateTimeTools::TIMESPAN_QUARTER_NAME = "Quarter";
const QString RiaQDateTimeTools::TIMESPAN_DAY_NAME = "Day";
const QString RiaQDateTimeTools::TIMESPAN_WEEK_NAME = "Week";
const QString RiaQDateTimeTools::TIMESPAN_MONTH_NAME = "Month";
const QString RiaQDateTimeTools::TIMESPAN_QUARTER_NAME = "Quarter";
const QString RiaQDateTimeTools::TIMESPAN_HALFYEAR_NAME = "Half Year";
const QString RiaQDateTimeTools::TIMESPAN_YEAR_NAME = "Year";
const QString RiaQDateTimeTools::TIMESPAN_DECADE_NAME = "Decade";
const QString RiaQDateTimeTools::TIMESPAN_YEAR_NAME = "Year";
const QString RiaQDateTimeTools::TIMESPAN_DECADE_NAME = "Decade";
namespace caf
{
template<>
template <>
void caf::AppEnum<RiaQDateTimeTools::DateFormatComponents>::setUp()
{
addItem(RiaQDateTimeTools::DATE_FORMAT_NONE, "NO_DATE", "No Date");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR, "YEAR", "Year Only");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH, "YEAR_MONTH", "Year and Month");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY, "YEAR_MONTH_DAY", "Year, Month and Day");
setDefault(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY);
addItem( RiaQDateTimeTools::DATE_FORMAT_NONE, "NO_DATE", "No Date" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR, "YEAR", "Year Only" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH, "YEAR_MONTH", "Year and Month" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY, "YEAR_MONTH_DAY", "Year, Month and Day" );
setDefault( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY );
}
template<>
template <>
void caf::AppEnum<RiaQDateTimeTools::TimeFormatComponents>::setUp()
{
addItem(RiaQDateTimeTools::TIME_FORMAT_NONE, "NO_TIME", "No Time of Day");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR, "HOUR", "Hour Only");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE, "HOUR_MINUTE", "Hour and Minute");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND, "HOUR_MINUTE_SECONDS", "Hour, Minutes and Seconds");
setDefault(RiaQDateTimeTools::TIME_FORMAT_NONE);
}
addItem( RiaQDateTimeTools::TIME_FORMAT_NONE, "NO_TIME", "No Time of Day" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR, "HOUR", "Hour Only" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE, "HOUR_MINUTE", "Hour and Minute" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND, "HOUR_MINUTE_SECONDS", "Hour, Minutes and Seconds" );
setDefault( RiaQDateTimeTools::TIME_FORMAT_NONE );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
Qt::TimeSpec RiaQDateTimeTools::currentTimeSpec()
{
@@ -81,7 +79,7 @@ Qt::TimeSpec RiaQDateTimeTools::currentTimeSpec()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
quint64 RiaQDateTimeTools::secondsInDay()
{
@@ -89,7 +87,7 @@ quint64 RiaQDateTimeTools::secondsInDay()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
quint64 RiaQDateTimeTools::secondsInYear()
{
@@ -97,262 +95,276 @@ quint64 RiaQDateTimeTools::secondsInYear()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromString(const QString& dateString, const QString& format)
QDateTime RiaQDateTimeTools::fromString( const QString& dateString, const QString& format )
{
QDateTime dt = QDateTime::fromString(dateString, format);
dt.setTimeSpec(currentTimeSpec());
QDateTime dt = QDateTime::fromString( dateString, format );
dt.setTimeSpec( currentTimeSpec() );
return dt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromYears(double years)
QDateTime RiaQDateTimeTools::fromYears( double years )
{
double yearsAfterEpoch = years - 1970.0;
QDateTime dt = RiaQDateTimeTools::epoch();
return RiaQDateTimeTools::addYears(dt, yearsAfterEpoch);
return RiaQDateTimeTools::addYears( dt, yearsAfterEpoch );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromTime_t(time_t t)
QDateTime RiaQDateTimeTools::fromTime_t( time_t t )
{
auto qdt = createUtcDateTime();
qdt.setTime_t(t);
qdt.setTime_t( t );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addMSecs(const QDateTime& dt, double msecs)
QDateTime RiaQDateTimeTools::addMSecs( const QDateTime& dt, double msecs )
{
return dt.addMSecs(msecs);
return dt.addMSecs( msecs );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addDays(const QDateTime& dt, double days)
QDateTime RiaQDateTimeTools::addDays( const QDateTime& dt, double days )
{
double integerPart = 0.0;
double integerPart = 0.0;
double fractionPart = 0.0;
fractionPart = modf(days, &integerPart);
fractionPart = modf( days, &integerPart );
QDateTime tmp = dt.addDays(integerPart);
tmp = tmp.addSecs(fractionPart * RiaQDateTimeTools::secondsInDay());
QDateTime tmp = dt.addDays( integerPart );
tmp = tmp.addSecs( fractionPart * RiaQDateTimeTools::secondsInDay() );
return tmp;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addYears(const QDateTime& dt, double years)
QDateTime RiaQDateTimeTools::addYears( const QDateTime& dt, double years )
{
double integerPart = 0.0;
double integerPart = 0.0;
double fractionPart = 0.0;
fractionPart = modf(years, &integerPart);
fractionPart = modf( years, &integerPart );
QDateTime tmp = dt.addYears(integerPart);
tmp = tmp.addSecs(fractionPart * RiaQDateTimeTools::secondsInYear());
QDateTime tmp = dt.addYears( integerPart );
tmp = tmp.addSecs( fractionPart * RiaQDateTimeTools::secondsInYear() );
return tmp;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addSpan(const QDateTime& dt, DateTimeSpan span)
QDateTime RiaQDateTimeTools::addSpan( const QDateTime& dt, DateTimeSpan span )
{
return createUtcDateTime(dt)
.addYears(span.years())
.addMonths(span.months())
.addDays(span.days());
return createUtcDateTime( dt ).addYears( span.years() ).addMonths( span.months() ).addDays( span.days() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::subtractSpan(const QDateTime& dt, DateTimeSpan span)
QDateTime RiaQDateTimeTools::subtractSpan( const QDateTime& dt, DateTimeSpan span )
{
return createUtcDateTime(dt)
.addYears(-span.years())
.addMonths(-span.months())
.addDays(-span.days());
return createUtcDateTime( dt ).addYears( -span.years() ).addMonths( -span.months() ).addDays( -span.days() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addPeriod(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::addPeriod( const QDateTime& dt, DateTimePeriod period )
{
return addSpan(dt, timeSpan(period));
return addSpan( dt, timeSpan( period ) );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::subtractPeriod(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::subtractPeriod( const QDateTime& dt, DateTimePeriod period )
{
return subtractSpan(dt, timeSpan(period));
return subtractSpan( dt, timeSpan( period ) );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::epoch()
{
// NB: Not able to use QDateTime::fromMSecsSinceEpoch as this was introduced in Qt 4.7
QDateTime dt;
dt.setDate(QDate(1970, 1, 1));
dt.setTimeSpec(currentTimeSpec());
dt.setDate( QDate( 1970, 1, 1 ) );
dt.setTimeSpec( currentTimeSpec() );
return dt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime()
{
auto qdt = QDateTime();
qdt.setTimeSpec(currentTimeSpec());
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDate& date)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDate& date )
{
auto qdt = QDateTime(date);
qdt.setTimeSpec(currentTimeSpec());
auto qdt = QDateTime( date );
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDate& date, const QTime& time)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDate& date, const QTime& time )
{
auto qdt = QDateTime(date, time, currentTimeSpec());
auto qdt = QDateTime( date, time, currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDateTime& dt)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDateTime& dt )
{
auto qdt = QDateTime(dt);
qdt.setTimeSpec(currentTimeSpec());
auto qdt = QDateTime( dt );
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaQDateTimeTools::lessThan(const QDateTime& dt1, const QDateTime& dt2)
bool RiaQDateTimeTools::lessThan( const QDateTime& dt1, const QDateTime& dt2 )
{
// dt1 < dt2
return dt1.secsTo(dt2) > 0;
return dt1.secsTo( dt2 ) > 0;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const DateTimeSpan RiaQDateTimeTools::timeSpan(DateTimePeriod period)
const DateTimeSpan RiaQDateTimeTools::timeSpan( DateTimePeriod period )
{
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return TIMESPAN_DAY;
case DateTimePeriod::WEEK: return TIMESPAN_WEEK;
case DateTimePeriod::MONTH: return TIMESPAN_MONTH;
case DateTimePeriod::QUARTER: return TIMESPAN_QUARTER;
case DateTimePeriod::HALFYEAR: return TIMESPAN_HALFYEAR;
case DateTimePeriod::YEAR: return TIMESPAN_YEAR;
case DateTimePeriod::DECADE: return TIMESPAN_DECADE;
case DateTimePeriod::DAY:
return TIMESPAN_DAY;
case DateTimePeriod::WEEK:
return TIMESPAN_WEEK;
case DateTimePeriod::MONTH:
return TIMESPAN_MONTH;
case DateTimePeriod::QUARTER:
return TIMESPAN_QUARTER;
case DateTimePeriod::HALFYEAR:
return TIMESPAN_HALFYEAR;
case DateTimePeriod::YEAR:
return TIMESPAN_YEAR;
case DateTimePeriod::DECADE:
return TIMESPAN_DECADE;
}
CVF_ASSERT(false);
CVF_ASSERT( false );
return DateTimeSpan();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::truncateTime(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::truncateTime( const QDateTime& dt, DateTimePeriod period )
{
int y = dt.date().year();
int m = dt.date().month();
int d = dt.date().day();
int y = dt.date().year();
int m = dt.date().month();
int d = dt.date().day();
int dow = dt.date().dayOfWeek();
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return createUtcDateTime(QDate(y, m, d));
case DateTimePeriod::WEEK: return createUtcDateTime(QDate(y, m, d).addDays(-dow + 1));
case DateTimePeriod::MONTH: return createUtcDateTime(QDate(y, m, 1));
case DateTimePeriod::QUARTER: return createUtcDateTime(QDate(y, ((m - 1) / 3) * 3 + 1, 1));
case DateTimePeriod::HALFYEAR: return createUtcDateTime(QDate(y, ((m - 1) / 6) * 6 + 1, 1));
case DateTimePeriod::YEAR: return createUtcDateTime(QDate(y, 1, 1));
case DateTimePeriod::DECADE: return createUtcDateTime(QDate((y / 10) * 10, 1, 1));
case DateTimePeriod::DAY:
return createUtcDateTime( QDate( y, m, d ) );
case DateTimePeriod::WEEK:
return createUtcDateTime( QDate( y, m, d ).addDays( -dow + 1 ) );
case DateTimePeriod::MONTH:
return createUtcDateTime( QDate( y, m, 1 ) );
case DateTimePeriod::QUARTER:
return createUtcDateTime( QDate( y, ( ( m - 1 ) / 3 ) * 3 + 1, 1 ) );
case DateTimePeriod::HALFYEAR:
return createUtcDateTime( QDate( y, ( ( m - 1 ) / 6 ) * 6 + 1, 1 ) );
case DateTimePeriod::YEAR:
return createUtcDateTime( QDate( y, 1, 1 ) );
case DateTimePeriod::DECADE:
return createUtcDateTime( QDate( ( y / 10 ) * 10, 1, 1 ) );
}
CVF_ASSERT(false);
CVF_ASSERT( false );
return createUtcDateTime();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<DateTimePeriod> RiaQDateTimeTools::dateTimePeriods()
{
return std::vector<DateTimePeriod>(
{
DateTimePeriod::NONE,
DateTimePeriod::DAY,
DateTimePeriod::WEEK,
DateTimePeriod::MONTH,
DateTimePeriod::QUARTER,
DateTimePeriod::HALFYEAR,
DateTimePeriod::YEAR,
DateTimePeriod::DECADE,
});
return std::vector<DateTimePeriod>( {
DateTimePeriod::NONE,
DateTimePeriod::DAY,
DateTimePeriod::WEEK,
DateTimePeriod::MONTH,
DateTimePeriod::QUARTER,
DateTimePeriod::HALFYEAR,
DateTimePeriod::YEAR,
DateTimePeriod::DECADE,
} );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::dateTimePeriodName(DateTimePeriod period)
QString RiaQDateTimeTools::dateTimePeriodName( DateTimePeriod period )
{
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return TIMESPAN_DAY_NAME;
case DateTimePeriod::WEEK: return TIMESPAN_WEEK_NAME;
case DateTimePeriod::MONTH: return TIMESPAN_MONTH_NAME;
case DateTimePeriod::QUARTER: return TIMESPAN_QUARTER_NAME;
case DateTimePeriod::HALFYEAR: return TIMESPAN_HALFYEAR_NAME;
case DateTimePeriod::YEAR: return TIMESPAN_YEAR_NAME;
case DateTimePeriod::DECADE: return TIMESPAN_DECADE_NAME;
default: return "None";
case DateTimePeriod::DAY:
return TIMESPAN_DAY_NAME;
case DateTimePeriod::WEEK:
return TIMESPAN_WEEK_NAME;
case DateTimePeriod::MONTH:
return TIMESPAN_MONTH_NAME;
case DateTimePeriod::QUARTER:
return TIMESPAN_QUARTER_NAME;
case DateTimePeriod::HALFYEAR:
return TIMESPAN_HALFYEAR_NAME;
case DateTimePeriod::YEAR:
return TIMESPAN_YEAR_NAME;
case DateTimePeriod::DECADE:
return TIMESPAN_DECADE_NAME;
default:
return "None";
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::toStringUsingApplicationLocale(const QDateTime& dt, const QString& format)
QString RiaQDateTimeTools::toStringUsingApplicationLocale( const QDateTime& dt, const QString& format )
{
// Default application locale is set in RiaMain
// QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
@@ -361,47 +373,46 @@ QString RiaQDateTimeTools::toStringUsingApplicationLocale(const QDateTime& dt, c
QLocale defaultApplicationLocale;
return defaultApplicationLocale.toString(dt, format);
return defaultApplicationLocale.toString( dt, format );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::createTimeFormatStringFromDates(const std::vector<QDateTime>& dates)
QString RiaQDateTimeTools::createTimeFormatStringFromDates( const std::vector<QDateTime>& dates )
{
bool hasHoursAndMinutesInTimesteps = false;
bool hasSecondsInTimesteps = false;
bool hasMillisecondsInTimesteps = false;
for (size_t i = 0; i < dates.size(); i++)
for ( size_t i = 0; i < dates.size(); i++ )
{
if (dates[i].time().msec() != 0.0)
if ( dates[i].time().msec() != 0.0 )
{
hasMillisecondsInTimesteps = true;
hasSecondsInTimesteps = true;
hasHoursAndMinutesInTimesteps = true;
break;
}
else if (dates[i].time().second() != 0.0)
else if ( dates[i].time().second() != 0.0 )
{
hasHoursAndMinutesInTimesteps = true;
hasSecondsInTimesteps = true;
}
else if (dates[i].time().hour() != 0.0 || dates[i].time().minute() != 0.0)
else if ( dates[i].time().hour() != 0.0 || dates[i].time().minute() != 0.0 )
{
hasHoursAndMinutesInTimesteps = true;
}
}
QString formatString = dateFormatString();
if (hasHoursAndMinutesInTimesteps)
if ( hasHoursAndMinutesInTimesteps )
{
formatString += " - hh:mm";
if (hasSecondsInTimesteps)
if ( hasSecondsInTimesteps )
{
formatString += ":ss";
if (hasMillisecondsInTimesteps)
if ( hasMillisecondsInTimesteps )
{
formatString += ".zzz";
}
@@ -429,20 +440,20 @@ std::vector<QString> RiaQDateTimeTools::supportedDateFormats()
// See enum DateFormatComponents in header
// The semi-colon separated components are:
// DATE_FORMAT_YEAR, ..YEAR_MONTH, ..YEAR_MONTH_DAY
dateFormats.push_back("yyyy;yyyy-MM;yyyy-MM-dd");
dateFormats.push_back("yyyy;MMM yyyy;dd. MMM yyyy");
dateFormats.push_back("yyyy;MMM yyyy;MMM dd. yyyy");
dateFormats.push_back("yyyy;MM/yyyy;dd/MM/yyyy");
dateFormats.push_back("yyyy;M/yyyy;d/M/yyyy");
dateFormats.push_back("yyyy;M/yyyy;M/d/yyyy");
dateFormats.push_back("yy;M/yy;d/M/yy");
dateFormats.push_back("yy;M/yy;M/d/yy");
dateFormats.push_back("yyyy;MM-yyyy;dd-MM-yyyy");
dateFormats.push_back("yyyy;MM.yyyy;dd.MM.yyyy");
dateFormats.push_back("yyyy;MM-yyyy;MM-dd-yyyy");
dateFormats.push_back("yyyy;MM.yyyy;MM.dd.yyyy");
dateFormats.push_back("yy;MM-yy;dd-MM-yy");
dateFormats.push_back("yy;MM-yy;MM-dd-yy");
dateFormats.push_back( "yyyy;yyyy-MM;yyyy-MM-dd" );
dateFormats.push_back( "yyyy;MMM yyyy;dd. MMM yyyy" );
dateFormats.push_back( "yyyy;MMM yyyy;MMM dd. yyyy" );
dateFormats.push_back( "yyyy;MM/yyyy;dd/MM/yyyy" );
dateFormats.push_back( "yyyy;M/yyyy;d/M/yyyy" );
dateFormats.push_back( "yyyy;M/yyyy;M/d/yyyy" );
dateFormats.push_back( "yy;M/yy;d/M/yy" );
dateFormats.push_back( "yy;M/yy;M/d/yy" );
dateFormats.push_back( "yyyy;MM-yyyy;dd-MM-yyyy" );
dateFormats.push_back( "yyyy;MM.yyyy;dd.MM.yyyy" );
dateFormats.push_back( "yyyy;MM-yyyy;MM-dd-yyyy" );
dateFormats.push_back( "yyyy;MM.yyyy;MM.dd.yyyy" );
dateFormats.push_back( "yy;MM-yy;dd-MM-yy" );
dateFormats.push_back( "yy;MM-yy;MM-dd-yy" );
return dateFormats;
}
@@ -457,10 +468,10 @@ std::vector<QString> RiaQDateTimeTools::supportedTimeFormats()
// See enum TimeFormatComponents in header
// The semi-colon separated components are:
// TIME_FORMAT_HOUR, ..HOUR_MINUTE, ..HOUR_MINUTE_SECOND and ..HOUR_MINUTE_MILLISECOND
timeFormats.push_back("HH;HH:mm;HH:mm:ss;HH:mm:ss.zzz");
timeFormats.push_back("H;H:mm;H:mm:ss;H:mm:ss.zzz");
timeFormats.push_back("hh AP;hh:mm AP;hh:mm:ss AP;hh:mm:ss.zzz AP");
timeFormats.push_back("h AP;h:mm AP;h:mm:ss AP;h:mm:ss.zzz AP");
timeFormats.push_back( "HH;HH:mm;HH:mm:ss;HH:mm:ss.zzz" );
timeFormats.push_back( "H;H:mm;H:mm:ss;H:mm:ss.zzz" );
timeFormats.push_back( "hh AP;hh:mm AP;hh:mm:ss AP;hh:mm:ss.zzz AP" );
timeFormats.push_back( "h AP;h:mm AP;h:mm:ss AP;h:mm:ss.zzz AP" );
return timeFormats;
}
@@ -468,31 +479,31 @@ std::vector<QString> RiaQDateTimeTools::supportedTimeFormats()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::dateFormatString(const QString& fullDateFormat, DateFormatComponents dateComponents)
QString RiaQDateTimeTools::dateFormatString( const QString& fullDateFormat, DateFormatComponents dateComponents )
{
if (dateComponents == DATE_FORMAT_NONE) return "";
if ( dateComponents == DATE_FORMAT_NONE ) return "";
QStringList allVariants = fullDateFormat.split(";");
if (static_cast<int>(dateComponents) < allVariants.size())
QStringList allVariants = fullDateFormat.split( ";" );
if ( static_cast<int>( dateComponents ) < allVariants.size() )
{
return allVariants[dateComponents];
}
CVF_ASSERT(false && "Date format string is malformed");
CVF_ASSERT( false && "Date format string is malformed" );
return "";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::timeFormatString(const QString& fullTimeFormat, TimeFormatComponents timeComponents)
QString RiaQDateTimeTools::timeFormatString( const QString& fullTimeFormat, TimeFormatComponents timeComponents )
{
if (timeComponents == TIME_FORMAT_NONE) return "";
if ( timeComponents == TIME_FORMAT_NONE ) return "";
QStringList allVariants = fullTimeFormat.split(";");
if (static_cast<int>(timeComponents) < allVariants.size())
QStringList allVariants = fullTimeFormat.split( ";" );
if ( static_cast<int>( timeComponents ) < allVariants.size() )
{
return allVariants[timeComponents];
}
CVF_ASSERT(false && "Time format string is malformed");
CVF_ASSERT( false && "Time format string is malformed" );
return "";
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -36,7 +36,7 @@ class QTime;
class DateTimeSpan;
//==================================================================================================
//
//
//==================================================================================================
enum class DateTimePeriod
{
@@ -51,7 +51,7 @@ enum class DateTimePeriod
};
//==================================================================================================
//
//
//==================================================================================================
class RiaQDateTimeTools
{
@@ -66,9 +66,9 @@ class RiaQDateTimeTools
public:
enum DateFormatComponents
{
DATE_FORMAT_UNSPECIFIED = -2,
DATE_FORMAT_NONE = -1,
DATE_FORMAT_YEAR = 0,
DATE_FORMAT_UNSPECIFIED = -2,
DATE_FORMAT_NONE = -1,
DATE_FORMAT_YEAR = 0,
DATE_FORMAT_YEAR_MONTH,
DATE_FORMAT_YEAR_MONTH_DAY,
DATE_FORMAT_SIZE
@@ -76,8 +76,8 @@ public:
enum TimeFormatComponents
{
TIME_FORMAT_UNSPECIFIED = -2,
TIME_FORMAT_NONE = -1,
TIME_FORMAT_UNSPECIFIED = -2,
TIME_FORMAT_NONE = -1,
TIME_FORMAT_HOUR,
TIME_FORMAT_HOUR_MINUTE,
TIME_FORMAT_HOUR_MINUTE_SECOND,
@@ -95,66 +95,87 @@ public:
static Qt::TimeSpec currentTimeSpec();
static QDateTime fromString(const QString& dateString, const QString& format);
static QDateTime fromYears(double years);
static QDateTime fromTime_t(time_t t);
static QDateTime fromString( const QString& dateString, const QString& format );
static QDateTime fromYears( double years );
static QDateTime fromTime_t( time_t t );
static QDateTime addMSecs(const QDateTime& dt, double msecs);
static QDateTime addDays(const QDateTime& dt, double days);
static QDateTime addYears(const QDateTime& dt, double years);
static QDateTime addSpan(const QDateTime& dt, DateTimeSpan span);
static QDateTime subtractSpan(const QDateTime& dt, DateTimeSpan span);
static QDateTime addPeriod(const QDateTime& dt, DateTimePeriod period);
static QDateTime subtractPeriod(const QDateTime& dt, DateTimePeriod period);
static QDateTime addMSecs( const QDateTime& dt, double msecs );
static QDateTime addDays( const QDateTime& dt, double days );
static QDateTime addYears( const QDateTime& dt, double years );
static QDateTime addSpan( const QDateTime& dt, DateTimeSpan span );
static QDateTime subtractSpan( const QDateTime& dt, DateTimeSpan span );
static QDateTime addPeriod( const QDateTime& dt, DateTimePeriod period );
static QDateTime subtractPeriod( const QDateTime& dt, DateTimePeriod period );
static QDateTime epoch();
static QDateTime createUtcDateTime();
static QDateTime createUtcDateTime(const QDate& date);
static QDateTime createUtcDateTime(const QDate& date, const QTime& time);
static QDateTime createUtcDateTime(const QDateTime& dt);
static QDateTime createUtcDateTime( const QDate& date );
static QDateTime createUtcDateTime( const QDate& date, const QTime& time );
static QDateTime createUtcDateTime( const QDateTime& dt );
static bool lessThan(const QDateTime& dt1, const QDateTime& dt2);
static bool lessThan( const QDateTime& dt1, const QDateTime& dt2 );
static const DateTimeSpan timeSpan(DateTimePeriod period);
static QDateTime truncateTime(const QDateTime& dt, DateTimePeriod period);
static const DateTimeSpan timeSpan( DateTimePeriod period );
static QDateTime truncateTime( const QDateTime& dt, DateTimePeriod period );
static std::vector<DateTimePeriod> dateTimePeriods();
static QString dateTimePeriodName(DateTimePeriod period);
static std::vector<DateTimePeriod> dateTimePeriods();
static QString dateTimePeriodName( DateTimePeriod period );
// This function uses C locale to make sure the text representation of a date is stable, independent of the locale
// settings on local machine. Required for stable regression testing.
static QString toStringUsingApplicationLocale(const QDateTime& dt, const QString& format);
static QString toStringUsingApplicationLocale( const QDateTime& dt, const QString& format );
static QString createTimeFormatStringFromDates(const std::vector<QDateTime>& dates);
static QString createTimeFormatStringFromDates( const std::vector<QDateTime>& dates );
static QString dateFormatString();
static std::vector<QString> supportedDateFormats();
static std::vector<QString> supportedTimeFormats();
static QString dateFormatString(const QString& fullDateFormat, DateFormatComponents dateComponents);
static QString timeFormatString(const QString& fullTimeFormat, TimeFormatComponents timeComponents);
static QString dateFormatString( const QString& fullDateFormat, DateFormatComponents dateComponents );
static QString timeFormatString( const QString& fullTimeFormat, TimeFormatComponents timeComponents );
private:
static quint64 secondsInDay();
static quint64 secondsInYear();
static quint64 secondsInDay();
static quint64 secondsInYear();
};
//==================================================================================================
///
///
//==================================================================================================
class DateTimeSpan
{
public:
DateTimeSpan() : m_years(0), m_months(0), m_days(0) { }
DateTimeSpan(int years, int months, int days) : m_years(years), m_months(months), m_days(days) { }
DateTimeSpan()
: m_years( 0 )
, m_months( 0 )
, m_days( 0 )
{
}
DateTimeSpan( int years, int months, int days )
: m_years( years )
, m_months( months )
, m_days( days )
{
}
int years() const { return m_years; }
int months() const { return m_months; }
int days() const { return m_days; }
int years() const
{
return m_years;
}
int months() const
{
return m_months;
}
int days() const
{
return m_days;
}
bool isEmpty() { return m_years == 0 && m_months == 0 && m_days; }
bool isEmpty()
{
return m_years == 0 && m_months == 0 && m_days;
}
private:
int m_years;

View File

@@ -22,70 +22,80 @@
#include "cafPdmUiFilePathEditor.h"
#include "cafPdmUiTextEditor.h"
CAF_PDM_SOURCE_INIT(RiaRegressionTest, "RiaRegressionTest");
CAF_PDM_SOURCE_INIT( RiaRegressionTest, "RiaRegressionTest" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTest::RiaRegressionTest(void)
RiaRegressionTest::RiaRegressionTest( void )
{
CAF_PDM_InitFieldNoDefault(&folderContainingCompareTool,
"workingFolder",
"Folder containing <b>compare</b>",
"",
"Location of compare tool from Image Magic suite",
"");
folderContainingCompareTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingCompareTool,
"workingFolder",
"Folder containing <b>compare</b>",
"",
"Location of compare tool from Image Magic suite",
"" );
folderContainingCompareTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&folderContainingDiffTool,
"folderContainingDiffTool",
"Folder containing <b>diff</b>",
"",
"Location of diff tool used for text compare",
"");
folderContainingDiffTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingDiffTool,
"folderContainingDiffTool",
"Folder containing <b>diff</b>",
"",
"Location of diff tool used for text compare",
"" );
folderContainingDiffTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&folderContainingGitTool,
"folderContainingGitTool",
"Folder containing <b>git</b>",
"",
"Location of git tool used for text compare",
"");
folderContainingGitTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingGitTool,
"folderContainingGitTool",
"Folder containing <b>git</b>",
"",
"Location of git tool used for text compare",
"" );
folderContainingGitTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&regressionTestFolder, "regressionTestFolder", "Regression Test Folder", "", "", "");
regressionTestFolder.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &regressionTestFolder, "regressionTestFolder", "Regression Test Folder", "", "", "" );
regressionTestFolder.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitField(&showInteractiveDiffImages, "showInteractiveDiffImages", false, "Interactive Diff Images", "", "", "");
CAF_PDM_InitField(
&useOpenMPForGeometryCreation, "useOpenMPForGeometryCreation", true, "Use OpenMP For Geometry Creation", "", "", "");
CAF_PDM_InitField( &showInteractiveDiffImages, "showInteractiveDiffImages", false, "Interactive Diff Images", "", "", "" );
CAF_PDM_InitField( &useOpenMPForGeometryCreation,
"useOpenMPForGeometryCreation",
true,
"Use OpenMP For Geometry Creation",
"",
"",
"" );
CAF_PDM_InitField(&openReportInBrowser, "openReportInBrowser", false, "Open Generated Report in Browser", "", "", "");
CAF_PDM_InitField( &openReportInBrowser, "openReportInBrowser", false, "Open Generated Report in Browser", "", "", "" );
CAF_PDM_InitFieldNoDefault(
&testFilter,
"testFilter",
"Test Filter",
"",
"If empty, all tests are executed.\nTo execute a subset of tests, specify folder names separated by ;",
"");
testFilter.uiCapability()->setUiEditorTypeName(caf::PdmUiTextEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &testFilter,
"testFilter",
"Test Filter",
"",
"If empty, all tests are executed.\nTo execute a subset of tests, specify folder names "
"separated by ;",
"" );
testFilter.uiCapability()->setUiEditorTypeName( caf::PdmUiTextEditor::uiEditorTypeName() );
CAF_PDM_InitField(
&appendTestsAfterTestFilter, "appendTestsAfterTestFilter", false, "Append All Tests After Test Filter", "", "", "");
CAF_PDM_InitField( &appendTestsAfterTestFilter,
"appendTestsAfterTestFilter",
false,
"Append All Tests After Test Filter",
"",
"",
"" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTest::~RiaRegressionTest(void) {}
RiaRegressionTest::~RiaRegressionTest( void ) {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::writeSettingsToApplicationStore() const
{
caf::PdmSettings::writeFieldsToApplicationStore(this);
caf::PdmSettings::writeFieldsToApplicationStore( this );
}
//--------------------------------------------------------------------------------------------------
@@ -93,21 +103,21 @@ void RiaRegressionTest::writeSettingsToApplicationStore() const
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::readSettingsFromApplicationStore()
{
caf::PdmSettings::readFieldsFromApplicationStore(this);
caf::PdmSettings::readFieldsFromApplicationStore( this );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::defineEditorAttribute(const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute)
void RiaRegressionTest::defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute )
{
if (field == &folderContainingDiffTool || field == &folderContainingCompareTool || field == &regressionTestFolder ||
field == &folderContainingGitTool)
if ( field == &folderContainingDiffTool || field == &folderContainingCompareTool ||
field == &regressionTestFolder || field == &folderContainingGitTool )
{
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>(attribute);
if (myAttr)
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>( attribute );
if ( myAttr )
{
myAttr->m_selectDirectory = true;
}

View File

@@ -27,8 +27,8 @@ class RiaRegressionTest : public caf::PdmObject
CAF_PDM_HEADER_INIT;
public:
RiaRegressionTest(void);
~RiaRegressionTest(void) override;
RiaRegressionTest( void );
~RiaRegressionTest( void ) override;
void writeSettingsToApplicationStore() const;
void readSettingsFromApplicationStore();
@@ -45,7 +45,7 @@ public:
caf::PdmField<bool> appendTestsAfterTestFilter;
protected:
void defineEditorAttribute(const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute) override;
void defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute ) override;
};

View File

@@ -69,21 +69,21 @@ const QString commandFileFilter = "commandfile-*";
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void logInfoTextWithTimeInSeconds(const QTime& time, const QString& msg)
void logInfoTextWithTimeInSeconds( const QTime& time, const QString& msg )
{
double timeRunning = time.elapsed() / 1000.0;
QString timeText = QString("(%1 s) ").arg(timeRunning, 0, 'f', 1);
QString timeText = QString( "(%1 s) " ).arg( timeRunning, 0, 'f', 1 );
RiaLogging::info(timeText + msg);
RiaLogging::info( timeText + msg );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTestRunner::RiaRegressionTestRunner()
: m_runningRegressionTests(false)
, m_appendAllTestsAfterLastItemInFilter(false)
: m_runningRegressionTests( false )
, m_appendAllTestsAfterLastItemInFilter( false )
{
}
@@ -107,12 +107,12 @@ void RiaRegressionTestRunner::runRegressionTest()
RiaRegressionTest regressionTestConfig;
regressionTestConfig.readSettingsFromApplicationStore();
if (!regressionTestConfig.folderContainingCompareTool().isEmpty())
if ( !regressionTestConfig.folderContainingCompareTool().isEmpty() )
{
// Windows Only : The image compare tool requires current working directory to be at the folder
// containing the image compare tool
QDir::setCurrent(regressionTestConfig.folderContainingCompareTool());
QDir::setCurrent( regressionTestConfig.folderContainingCompareTool() );
}
QString generatedFolderName = RegTestNames::generatedFolderName;
@@ -121,78 +121,84 @@ void RiaRegressionTestRunner::runRegressionTest()
QString regTestProjectName = RegTestNames::testProjectName;
QString regTestFolderFilter = RegTestNames::testFolderFilter;
QDir testDir(m_rootPath); // If string is empty it will end up as cwd
testDir.setFilter(QDir::Dirs);
QDir testDir( m_rootPath ); // If string is empty it will end up as cwd
testDir.setFilter( QDir::Dirs );
QStringList dirNameFilter;
dirNameFilter.append(regTestFolderFilter);
testDir.setNameFilters(dirNameFilter);
dirNameFilter.append( regTestFolderFilter );
testDir.setNameFilters( dirNameFilter );
QFileInfoList folderList = subDirectoriesForTestExecution(testDir);
QFileInfoList folderList = subDirectoriesForTestExecution( testDir );
// delete diff and generated images
for (const QFileInfo& fi : folderList)
for ( const QFileInfo& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
{
QDir genDir(testCaseFolder.filePath(generatedFolderName));
removeDirectoryWithContent(genDir);
QDir genDir( testCaseFolder.filePath( generatedFolderName ) );
removeDirectoryWithContent( genDir );
}
{
QDir diffDir(testCaseFolder.filePath(diffFolderName));
removeDirectoryWithContent(diffDir);
QDir diffDir( testCaseFolder.filePath( diffFolderName ) );
removeDirectoryWithContent( diffDir );
}
{
QDir generatedFiles(testCaseFolder.filePath(RegTestNames::generatedFilesFolderName));
removeDirectoryWithContent(generatedFiles);
QDir generatedFiles( testCaseFolder.filePath( RegTestNames::generatedFilesFolderName ) );
removeDirectoryWithContent( generatedFiles );
}
}
QString htmlReportFileName = generateHtmlReport(folderList, baseFolderName, generatedFolderName, diffFolderName, testDir);
QString htmlReportFileName = generateHtmlReport( folderList,
baseFolderName,
generatedFolderName,
diffFolderName,
testDir );
if (regressionTestConfig.openReportInBrowser())
if ( regressionTestConfig.openReportInBrowser() )
{
QDesktopServices::openUrl(htmlReportFileName);
QDesktopServices::openUrl( htmlReportFileName );
}
RiaLogging::info("--------------------------------------------------");
RiaLogging::info(QTime::currentTime().toString() + ": Launching regression tests");
RiaLogging::info("--------------------------------------------------");
RiaLogging::info( "--------------------------------------------------" );
RiaLogging::info( QTime::currentTime().toString() + ": Launching regression tests" );
RiaLogging::info( "--------------------------------------------------" );
QTime timeStamp;
timeStamp.start();
logInfoTextWithTimeInSeconds(timeStamp, "Starting regression tests\n");
logInfoTextWithTimeInSeconds( timeStamp, "Starting regression tests\n" );
for (const QFileInfo& folderFileInfo : folderList)
for ( const QFileInfo& folderFileInfo : folderList )
{
QDir testCaseFolder(folderFileInfo.filePath());
QDir testCaseFolder( folderFileInfo.filePath() );
bool anyCommandFilesExecuted = findAndExecuteCommandFiles(testCaseFolder, regressionTestConfig, htmlReportFileName);
bool anyCommandFilesExecuted = findAndExecuteCommandFiles( testCaseFolder,
regressionTestConfig,
htmlReportFileName );
if (!anyCommandFilesExecuted)
if ( !anyCommandFilesExecuted )
{
QString projectFileName;
if (testCaseFolder.exists(regTestProjectName + ".rip"))
if ( testCaseFolder.exists( regTestProjectName + ".rip" ) )
{
projectFileName = regTestProjectName + ".rip";
}
if (testCaseFolder.exists(regTestProjectName + ".rsp"))
if ( testCaseFolder.exists( regTestProjectName + ".rsp" ) )
{
projectFileName = regTestProjectName + ".rsp";
}
if (!projectFileName.isEmpty())
if ( !projectFileName.isEmpty() )
{
logInfoTextWithTimeInSeconds(timeStamp, "Initializing test :" + testCaseFolder.absolutePath());
logInfoTextWithTimeInSeconds( timeStamp, "Initializing test :" + testCaseFolder.absolutePath() );
RiaApplication* app = RiaApplication::instance();
app->loadProject(testCaseFolder.filePath(projectFileName));
app->loadProject( testCaseFolder.filePath( projectFileName ) );
// Wait until all command objects have completed
app->waitUntilCommandObjectsHasBeenProcessed();
@@ -201,56 +207,57 @@ void RiaRegressionTestRunner::runRegressionTest()
resizePlotWindows();
QString fullPathGeneratedFolder = testCaseFolder.absoluteFilePath(generatedFolderName);
RicSnapshotAllViewsToFileFeature::exportSnapshotOfAllViewsIntoFolder(fullPathGeneratedFolder);
QString fullPathGeneratedFolder = testCaseFolder.absoluteFilePath( generatedFolderName );
RicSnapshotAllViewsToFileFeature::exportSnapshotOfAllViewsIntoFolder( fullPathGeneratedFolder );
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfAllPlotsIntoFolder(fullPathGeneratedFolder);
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfAllPlotsIntoFolder( fullPathGeneratedFolder );
app->closeProject();
}
else
{
RiaLogging::error("Could not find a regression test file named : " + testCaseFolder.absolutePath() + "/" +
regTestProjectName + ".rsp");
RiaLogging::error( "Could not find a regression test file named : " + testCaseFolder.absolutePath() +
"/" + regTestProjectName + ".rsp" );
}
}
QDir baseDir(testCaseFolder.filePath(baseFolderName));
QDir genDir(testCaseFolder.filePath(generatedFolderName));
QDir diffDir(testCaseFolder.filePath(diffFolderName));
if (!diffDir.exists()) testCaseFolder.mkdir(diffFolderName);
baseDir.setFilter(QDir::Files);
QDir baseDir( testCaseFolder.filePath( baseFolderName ) );
QDir genDir( testCaseFolder.filePath( generatedFolderName ) );
QDir diffDir( testCaseFolder.filePath( diffFolderName ) );
if ( !diffDir.exists() ) testCaseFolder.mkdir( diffFolderName );
baseDir.setFilter( QDir::Files );
QStringList baseImageFileNames = baseDir.entryList();
for (int fIdx = 0; fIdx < baseImageFileNames.size(); ++fIdx)
for ( int fIdx = 0; fIdx < baseImageFileNames.size(); ++fIdx )
{
QString fileName = baseImageFileNames[fIdx];
RiaImageFileCompare imgComparator(RegTestNames::imageCompareExeName);
bool ok =
imgComparator.runComparison(genDir.filePath(fileName), baseDir.filePath(fileName), diffDir.filePath(fileName));
if (!ok)
RiaImageFileCompare imgComparator( RegTestNames::imageCompareExeName );
bool ok = imgComparator.runComparison( genDir.filePath( fileName ),
baseDir.filePath( fileName ),
diffDir.filePath( fileName ) );
if ( !ok )
{
qDebug() << "Error comparing :" << imgComparator.errorMessage() << "\n" << imgComparator.errorDetails();
}
}
logInfoTextWithTimeInSeconds(timeStamp, "Completed test :" + testCaseFolder.absolutePath());
logInfoTextWithTimeInSeconds( timeStamp, "Completed test :" + testCaseFolder.absolutePath() );
}
// Invoke git diff
{
QString folderContainingGit = regressionTestConfig.folderContainingGitTool();
RiaGitDiff gitDiff(folderContainingGit);
gitDiff.executeDiff(m_rootPath);
RiaGitDiff gitDiff( folderContainingGit );
gitDiff.executeDiff( m_rootPath );
QString diffText = gitDiff.diffOutput();
if (!diffText.isEmpty())
if ( !diffText.isEmpty() )
{
QFile file(htmlReportFileName);
if (file.open(QIODevice::Append | QIODevice::Text))
QFile file( htmlReportFileName );
if ( file.open( QIODevice::Append | QIODevice::Text ) )
{
QTextStream stream(&file);
QTextStream stream( &file );
QString divSectionForDiff = R"(
<div id = "destination-elem-id"[innerHtml] = "outputHtml">
@@ -292,10 +299,10 @@ document.getElementById("destination-elem-id").innerHTML = diffHtml;
}
}
RiaLogging::info("\n");
logInfoTextWithTimeInSeconds(timeStamp, "Completed regression tests");
RiaLogging::info( "\n" );
logInfoTextWithTimeInSeconds( timeStamp, "Completed regression tests" );
QDir::setCurrent(currentApplicationPath);
QDir::setCurrent( currentApplicationPath );
m_runningRegressionTests = false;
}
@@ -303,15 +310,15 @@ document.getElementById("destination-elem-id").innerHTML = diffHtml;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName)
bool RiaRegressionTestRunner::findAndExecuteCommandFiles( const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName )
{
QStringList filterList;
filterList << RegTestNames::commandFileFilter;
QFileInfoList commandFileEntries = testCaseFolder.entryInfoList(filterList);
if (commandFileEntries.empty())
QFileInfoList commandFileEntries = testCaseFolder.entryInfoList( filterList );
if ( commandFileEntries.empty() )
{
return false;
}
@@ -320,53 +327,54 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
// Set current path to the folder containing the command file, as this is required when using file references
// in the command file
QDir::setCurrent(testCaseFolder.path());
QDir::setCurrent( testCaseFolder.path() );
for (const auto& fileInfo : commandFileEntries)
for ( const auto& fileInfo : commandFileEntries )
{
QString commandFile = fileInfo.absoluteFilePath();
QFile file(commandFile);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
QFile file( commandFile );
if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
RiaLogging::error("Failed to open command file : " + commandFile);
RiaLogging::error( "Failed to open command file : " + commandFile );
}
else
{
QTextStream in(&file);
RicfCommandFileExecutor::instance()->executeCommands(in);
QTextStream in( &file );
RicfCommandFileExecutor::instance()->executeCommands( in );
}
}
QDir::setCurrent(currentAbsolutePath);
QDir::setCurrent( currentAbsolutePath );
// Create diff based on generated folders
{
QString html;
RiaTextFileCompare textFileCompare(regressionTestConfig.folderContainingDiffTool());
RiaTextFileCompare textFileCompare( regressionTestConfig.folderContainingDiffTool() );
QString baseFilesFolderName = testCaseFolder.filePath(RegTestNames::baseFilesFolderName);
QString generatedFilesFolderName = testCaseFolder.filePath(RegTestNames::generatedFilesFolderName);
QString baseFilesFolderName = testCaseFolder.filePath( RegTestNames::baseFilesFolderName );
QString generatedFilesFolderName = testCaseFolder.filePath( RegTestNames::generatedFilesFolderName );
QFileInfo fib(baseFilesFolderName);
QFileInfo fig(generatedFilesFolderName);
QFileInfo fib( baseFilesFolderName );
QFileInfo fig( generatedFilesFolderName );
if (fib.exists() && fig.exists())
if ( fib.exists() && fig.exists() )
{
{
QString headerText = testCaseFolder.dirName();
html += "<table>\n";
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
headerText + " </font></b> </td>\n";
html +=
" <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
headerText + " </font></b> </td>\n";
html += " </tr>\n";
textFileCompare.runComparison(baseFilesFolderName, generatedFilesFolderName);
textFileCompare.runComparison( baseFilesFolderName, generatedFilesFolderName );
QString diff = textFileCompare.diffOutput();
if (diff.isEmpty())
if ( diff.isEmpty() )
{
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"lightgray\"> <font color=\"green\">No text diff "
@@ -384,16 +392,16 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
// Table end
html += "</table>\n";
if (!diff.isEmpty())
if ( !diff.isEmpty() )
{
html += QString("<code> %1 </code>").arg(diff);
html += QString( "<code> %1 </code>" ).arg( diff );
}
}
QFile file(htmlReportFileName);
if (file.open(QIODevice::Append | QIODevice::Text))
QFile file( htmlReportFileName );
if ( file.open( QIODevice::Append | QIODevice::Text ) )
{
QTextStream stream(&file);
QTextStream stream( &file );
stream << html;
}
@@ -406,11 +414,11 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir)
QString RiaRegressionTestRunner::generateHtmlReport( const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir )
{
RiaImageCompareReporter imageCompareReporter;
@@ -420,32 +428,32 @@ QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderL
{
QSettings settings;
bool useInteractiveDiff = settings.value("showInteractiveDiffImages").toBool();
if (useInteractiveDiff)
bool useInteractiveDiff = settings.value( "showInteractiveDiffImages" ).toBool();
if ( useInteractiveDiff )
{
imageCompareReporter.showInteractiveOnly();
}
}
for (const QFileInfo& fi : folderList)
for ( const QFileInfo& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
QString testFolderName = testCaseFolder.dirName();
QString reportBaseFolderName = testCaseFolder.filePath(baseFolderName);
QString reportGeneratedFolderName = testCaseFolder.filePath(generatedFolderName);
QString reportDiffFolderName = testCaseFolder.filePath(diffFolderName);
QString reportBaseFolderName = testCaseFolder.filePath( baseFolderName );
QString reportGeneratedFolderName = testCaseFolder.filePath( generatedFolderName );
QString reportDiffFolderName = testCaseFolder.filePath( diffFolderName );
imageCompareReporter.addImageDirectoryComparisonSet(testFolderName.toStdString(),
reportBaseFolderName.toStdString(),
reportGeneratedFolderName.toStdString(),
reportDiffFolderName.toStdString());
imageCompareReporter.addImageDirectoryComparisonSet( testFolderName.toStdString(),
reportBaseFolderName.toStdString(),
reportGeneratedFolderName.toStdString(),
reportDiffFolderName.toStdString() );
}
QString htmlReportFileName = testDir.filePath(RegTestNames::reportFileName);
QString htmlReportFileName = testDir.filePath( RegTestNames::reportFileName );
QString htmldiff2htmlText = diff2htmlHeaderText(m_rootPath);
imageCompareReporter.generateHTMLReport(htmlReportFileName.toStdString(), htmldiff2htmlText.toStdString());
QString htmldiff2htmlText = diff2htmlHeaderText( m_rootPath );
imageCompareReporter.generateHTMLReport( htmlReportFileName.toStdString(), htmldiff2htmlText.toStdString() );
return htmlReportFileName;
}
@@ -453,9 +461,9 @@ QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderL
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::removeDirectoryWithContent(QDir& dirToDelete)
void RiaRegressionTestRunner::removeDirectoryWithContent( QDir& dirToDelete )
{
caf::Utils::removeDirectoryAndFilesRecursively(dirToDelete.absolutePath());
caf::Utils::removeDirectoryAndFilesRecursively( dirToDelete.absolutePath() );
}
//--------------------------------------------------------------------------------------------------
@@ -464,33 +472,33 @@ void RiaRegressionTestRunner::removeDirectoryWithContent(QDir& dirToDelete)
void RiaRegressionTestRunner::regressionTestConfigureProject()
{
RiuMainWindow* mainWnd = RiuMainWindow::instance();
if (!mainWnd) return;
if ( !mainWnd ) return;
RimProject* proj = RiaApplication::instance()->project();
if (!proj) return;
if ( !proj ) return;
std::vector<RimCase*> projectCases;
proj->allCases(projectCases);
proj->allCases( projectCases );
for (RimCase* cas : projectCases)
for ( RimCase* cas : projectCases )
{
if (!cas) continue;
if ( !cas ) continue;
std::vector<Rim3dView*> views = cas->views();
for (Rim3dView* riv : views)
for ( Rim3dView* riv : views )
{
if (riv && riv->viewer())
if ( riv && riv->viewer() )
{
// Make sure all views are maximized for snapshotting
QMdiSubWindow* subWnd = mainWnd->findMdiSubWindow(riv->viewer()->layoutWidget());
if (subWnd)
QMdiSubWindow* subWnd = mainWnd->findMdiSubWindow( riv->viewer()->layoutWidget() );
if ( subWnd )
{
subWnd->showMaximized();
}
// This size is set to match the regression test reference images
riv->viewer()->setFixedSize(RiaRegressionTestRunner::regressionDefaultImageSize());
riv->viewer()->setFixedSize( RiaRegressionTestRunner::regressionDefaultImageSize() );
}
}
}
@@ -502,29 +510,29 @@ void RiaRegressionTestRunner::regressionTestConfigureProject()
void RiaRegressionTestRunner::resizePlotWindows()
{
RimProject* proj = RiaApplication::instance()->project();
if (!proj) return;
if ( !proj ) return;
RiuPlotMainWindow* plotMainWindow = RiaGuiApplication::instance()->mainPlotWindow();
if (!plotMainWindow) return;
if ( !plotMainWindow ) return;
std::vector<RimViewWindow*> viewWindows;
proj->mainPlotCollection()->descendantsIncludingThisOfType(viewWindows);
proj->mainPlotCollection()->descendantsIncludingThisOfType( viewWindows );
for (auto viewWindow : viewWindows)
for ( auto viewWindow : viewWindows )
{
if (viewWindow->isMdiWindow())
if ( viewWindow->isMdiWindow() )
{
QWidget* viewWidget = viewWindow->viewWidget();
if (viewWidget)
if ( viewWidget )
{
QMdiSubWindow* mdiWindow = plotMainWindow->findMdiSubWindow(viewWidget);
if (mdiWindow)
QMdiSubWindow* mdiWindow = plotMainWindow->findMdiSubWindow( viewWidget );
if ( mdiWindow )
{
mdiWindow->showNormal();
viewWidget->resize(RiaRegressionTestRunner::regressionDefaultImageSize());
viewWidget->resize( RiaRegressionTestRunner::regressionDefaultImageSize() );
}
}
}
@@ -536,23 +544,23 @@ void RiaRegressionTestRunner::resizePlotWindows()
//--------------------------------------------------------------------------------------------------
QSize RiaRegressionTestRunner::regressionDefaultImageSize()
{
return QSize(1000, 745);
return QSize( 1000, 745 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath)
QString RiaRegressionTestRunner::diff2htmlHeaderText( const QString& testRootPath )
{
QString html;
QString oldProjPath = QDir::fromNativeSeparators(testRootPath);
QStringList pathFolders = oldProjPath.split("/", QString::KeepEmptyParts);
QString oldProjPath = QDir::fromNativeSeparators( testRootPath );
QStringList pathFolders = oldProjPath.split( "/", QString::KeepEmptyParts );
QString path;
for (const auto& f : pathFolders)
for ( const auto& f : pathFolders )
{
if (f.compare("ProjectFiles", Qt::CaseInsensitive) == 0) break;
if ( f.compare( "ProjectFiles", Qt::CaseInsensitive ) == 0 ) break;
path += f;
path += "/";
}
@@ -568,7 +576,7 @@ QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath
)";
QString pathToDiff2html = path + "diff2html/dist/";
html = html.replace("dist/", pathToDiff2html);
html = html.replace( "dist/", pathToDiff2html );
}
return html;
@@ -577,9 +585,9 @@ QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution(const QDir& directory)
QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution( const QDir& directory )
{
if (m_testFilter.isEmpty())
if ( m_testFilter.isEmpty() )
{
QFileInfoList folderList = directory.entryInfoList();
@@ -591,17 +599,18 @@ QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution(const QDir
QFileInfoList foldersMatchingTestFilter;
QFileInfoList folderList = directory.entryInfoList();
for (const auto& fi : folderList)
for ( const auto& fi : folderList )
{
QString path = fi.path();
QString baseName = fi.baseName();
for (const auto& s : m_testFilter)
for ( const auto& s : m_testFilter )
{
QString trimmed = s.trimmed();
if ((m_appendAllTestsAfterLastItemInFilter && anyMatchFound) || baseName.contains(trimmed, Qt::CaseInsensitive))
if ( ( m_appendAllTestsAfterLastItemInFilter && anyMatchFound ) ||
baseName.contains( trimmed, Qt::CaseInsensitive ) )
{
foldersMatchingTestFilter.push_back(fi);
foldersMatchingTestFilter.push_back( fi );
anyMatchFound = true;
}
}
@@ -619,23 +628,23 @@ void RiaRegressionTestRunner::executeRegressionTests()
testConfig.readSettingsFromApplicationStore();
QString testPath = testConfig.regressionTestFolder();
QStringList testFilter = testConfig.testFilter().split(";", QString::SkipEmptyParts);
QStringList testFilter = testConfig.testFilter().split( ";", QString::SkipEmptyParts );
if (testConfig.appendTestsAfterTestFilter)
if ( testConfig.appendTestsAfterTestFilter )
{
m_appendAllTestsAfterLastItemInFilter = true;
}
executeRegressionTests(testPath, testFilter);
executeRegressionTests( testPath, testFilter );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::executeRegressionTests(const QString& regressionTestPath, const QStringList& testFilter)
void RiaRegressionTestRunner::executeRegressionTests( const QString& regressionTestPath, const QStringList& testFilter )
{
RiuMainWindow* mainWnd = RiuMainWindow::instance();
if (mainWnd)
if ( mainWnd )
{
mainWnd->hideAllDockWidgets();
mainWnd->statusBar()->close();
@@ -665,7 +674,7 @@ bool RiaRegressionTestRunner::isRunningRegressionTests() const
//--------------------------------------------------------------------------------------------------
bool RiaRegressionTestRunner::useOpenMPForGeometryCreation() const
{
if (!m_runningRegressionTests) return false;
if ( !m_runningRegressionTests ) return false;
return m_regressionTestSettings.useOpenMPForGeometryCreation;
}
@@ -673,34 +682,34 @@ bool RiaRegressionTestRunner::useOpenMPForGeometryCreation() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::updateRegressionTest(const QString& testRootPath)
void RiaRegressionTestRunner::updateRegressionTest( const QString& testRootPath )
{
// Find all sub folders
QDir testDir(testRootPath); // If string is empty it will end up as cwd
testDir.setFilter(QDir::Dirs);
QDir testDir( testRootPath ); // If string is empty it will end up as cwd
testDir.setFilter( QDir::Dirs );
QStringList dirNameFilter;
dirNameFilter.append(RegTestNames::testFolderFilter);
testDir.setNameFilters(dirNameFilter);
dirNameFilter.append( RegTestNames::testFolderFilter );
testDir.setNameFilters( dirNameFilter );
QFileInfoList folderList = testDir.entryInfoList();
for (const auto& fi : folderList)
for ( const auto& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
QDir baseDir(testCaseFolder.filePath(RegTestNames::baseFolderName));
removeDirectoryWithContent(baseDir);
testCaseFolder.mkdir(RegTestNames::baseFolderName);
QDir baseDir( testCaseFolder.filePath( RegTestNames::baseFolderName ) );
removeDirectoryWithContent( baseDir );
testCaseFolder.mkdir( RegTestNames::baseFolderName );
QDir genDir(testCaseFolder.filePath(RegTestNames::generatedFolderName));
QDir genDir( testCaseFolder.filePath( RegTestNames::generatedFolderName ) );
QStringList imageFileNames = genDir.entryList();
for (int fIdx = 0; fIdx < imageFileNames.size(); ++fIdx)
for ( int fIdx = 0; fIdx < imageFileNames.size(); ++fIdx )
{
QString fileName = imageFileNames[fIdx];
QFile::copy(genDir.filePath(fileName), baseDir.filePath(fileName));
QFile::copy( genDir.filePath( fileName ), baseDir.filePath( fileName ) );
}
}
}

View File

@@ -35,13 +35,13 @@ class RiaRegressionTestRunner
public:
static RiaRegressionTestRunner* instance();
void executeRegressionTests(const QString& regressionTestPath, const QStringList& testFilter);
void executeRegressionTests( const QString& regressionTestPath, const QStringList& testFilter );
void executeRegressionTests();
bool isRunningRegressionTests() const;
bool useOpenMPForGeometryCreation() const;
static void updateRegressionTest(const QString& testRootPath);
static void updateRegressionTest( const QString& testRootPath );
static void regressionTestConfigureProject();
private:
@@ -49,21 +49,21 @@ private:
void runRegressionTest();
bool findAndExecuteCommandFiles(const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName);
bool findAndExecuteCommandFiles( const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName );
QString generateHtmlReport(const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir);
QString generateHtmlReport( const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir );
static void removeDirectoryWithContent(QDir& dirToDelete);
static void removeDirectoryWithContent( QDir& dirToDelete );
static void resizePlotWindows();
static QSize regressionDefaultImageSize();
static QString diff2htmlHeaderText(const QString& testRootPath);
QFileInfoList subDirectoriesForTestExecution(const QDir& directory);
static QString diff2htmlHeaderText( const QString& testRootPath );
QFileInfoList subDirectoriesForTestExecution( const QDir& directory );
private:
QString m_rootPath;

View File

@@ -29,44 +29,45 @@
#include "cafPdmUiOrdering.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<const RigWellPath*> RiaSimWellBranchTools::simulationWellBranches(const QString& simWellName, bool useAutoDetectionOfBranches)
std::vector<const RigWellPath*> RiaSimWellBranchTools::simulationWellBranches( const QString& simWellName,
bool useAutoDetectionOfBranches )
{
RiaApplication* app = RiaApplication::instance();
RimProject* proj = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* proj = app->project();
// Find first case containing the specified simulation well
auto simCases = proj->eclipseCases();
auto caseItr = std::find_if(simCases.begin(), simCases.end(), [&simWellName](const RimEclipseCase* eclCase) {
auto caseItr = std::find_if( simCases.begin(), simCases.end(), [&simWellName]( const RimEclipseCase* eclCase ) {
const auto& eclData = eclCase->eclipseCaseData();
return eclData != nullptr && eclData->hasSimulationWell(simWellName);
});
RimEclipseCase* eclipseCase = caseItr != simCases.end() ? *caseItr : nullptr;
return eclData != nullptr && eclData->hasSimulationWell( simWellName );
} );
RimEclipseCase* eclipseCase = caseItr != simCases.end() ? *caseItr : nullptr;
RigEclipseCaseData* eclCaseData = eclipseCase != nullptr ? eclipseCase->eclipseCaseData() : nullptr;
return eclCaseData != nullptr ?
eclCaseData->simulationWellBranches(simWellName, false, useAutoDetectionOfBranches) :
std::vector<const RigWellPath*>();
return eclCaseData != nullptr ? eclCaseData->simulationWellBranches( simWellName, false, useAutoDetectionOfBranches )
: std::vector<const RigWellPath*>();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo>
RiaSimWellBranchTools::valueOptionsForBranchIndexField(const std::vector<const RigWellPath*>& simulationWellPaths)
RiaSimWellBranchTools::valueOptionsForBranchIndexField( const std::vector<const RigWellPath*>& simulationWellPaths )
{
QList<caf::PdmOptionItemInfo> options;
size_t branchCount = simulationWellPaths.size();
if (simulationWellPaths.size() == 0)
if ( simulationWellPaths.size() == 0 )
{
options.push_front(caf::PdmOptionItemInfo("None", -1));
options.push_front( caf::PdmOptionItemInfo( "None", -1 ) );
}
else
{
for (int bIdx = 0; bIdx < static_cast<int>(branchCount); ++bIdx)
for ( int bIdx = 0; bIdx < static_cast<int>( branchCount ); ++bIdx )
{
options.push_back(caf::PdmOptionItemInfo("Branch " + QString::number(bIdx + 1), QVariant::fromValue(bIdx)));
options.push_back(
caf::PdmOptionItemInfo( "Branch " + QString::number( bIdx + 1 ), QVariant::fromValue( bIdx ) ) );
}
}
@@ -76,35 +77,38 @@ QList<caf::PdmOptionItemInfo>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromWellName(caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField)
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromWellName( caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField )
{
if (!RimWellPlotTools::hasAssociatedWellPath(wellPathOrSimWellName))
if ( !RimWellPlotTools::hasAssociatedWellPath( wellPathOrSimWellName ) )
{
const QString simWellName = RimWellPlotTools::simWellName(wellPathOrSimWellName);
const QString simWellName = RimWellPlotTools::simWellName( wellPathOrSimWellName );
RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(uiOrdering, simWellName, branchDetectionField,
branchIndexField);
RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName( uiOrdering,
simWellName,
branchDetectionField,
branchIndexField );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField)
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(
caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField )
{
if (RiaSimWellBranchTools::simulationWellBranches(simWellName, true).size() > 1)
if ( RiaSimWellBranchTools::simulationWellBranches( simWellName, true ).size() > 1 )
{
uiOrdering->add(&branchDetectionField);
uiOrdering->add( &branchDetectionField );
if (RiaSimWellBranchTools::simulationWellBranches(simWellName, branchDetectionField).size() > 1)
if ( RiaSimWellBranchTools::simulationWellBranches( simWellName, branchDetectionField ).size() > 1 )
{
uiOrdering->add(&branchIndexField);
uiOrdering->add( &branchIndexField );
}
}
}
@@ -112,17 +116,17 @@ void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(c
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int RiaSimWellBranchTools::clampBranchIndex(const QString& simWellName, int branchIndexValue, bool branchDetection)
int RiaSimWellBranchTools::clampBranchIndex( const QString& simWellName, int branchIndexValue, bool branchDetection )
{
auto branches = RiaSimWellBranchTools::simulationWellBranches(simWellName, branchDetection);
auto branches = RiaSimWellBranchTools::simulationWellBranches( simWellName, branchDetection );
if (branches.size() == 0)
if ( branches.size() == 0 )
{
return -1;
}
int maxIndexValue = static_cast<int>(branches.size()) - 1;
if (branchIndexValue > maxIndexValue)
int maxIndexValue = static_cast<int>( branches.size() ) - 1;
if ( branchIndexValue > maxIndexValue )
{
branchIndexValue = maxIndexValue;
}

View File

@@ -39,19 +39,21 @@ class PdmUiOrdering;
class RiaSimWellBranchTools
{
public:
static std::vector<const RigWellPath*> simulationWellBranches(const QString& simWellName, bool useAutoDetectionOfBranches);
static std::vector<const RigWellPath*> simulationWellBranches( const QString& simWellName,
bool useAutoDetectionOfBranches );
static QList<caf::PdmOptionItemInfo>
valueOptionsForBranchIndexField(const std::vector<const RigWellPath*>& simulationWellPaths);
valueOptionsForBranchIndexField( const std::vector<const RigWellPath*>& simulationWellPaths );
static void appendSimWellBranchFieldsIfRequiredFromWellName(caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField);
static void appendSimWellBranchFieldsIfRequiredFromWellName( caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField );
static void appendSimWellBranchFieldsIfRequiredFromSimWellName(caf::PdmUiOrdering* uiOrdering, const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField);
static void appendSimWellBranchFieldsIfRequiredFromSimWellName( caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField );
static int clampBranchIndex(const QString& simWellName, int branchIndexValue, bool branchDetection);
static int clampBranchIndex( const QString& simWellName, int branchIndexValue, bool branchDetection );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,27 +25,27 @@
#include <QString>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QString RiaStatisticsTools::replacePercentileByPValueText(const QString& percentile)
const QString RiaStatisticsTools::replacePercentileByPValueText( const QString& percentile )
{
QString result = percentile;
if (result == ENSEMBLE_STAT_P10_QUANTITY_NAME)
if ( result == ENSEMBLE_STAT_P10_QUANTITY_NAME )
{
result = ENSEMBLE_STAT_P90_QUANTITY_NAME;
}
else if (result == ENSEMBLE_STAT_P90_QUANTITY_NAME)
else if ( result == ENSEMBLE_STAT_P90_QUANTITY_NAME )
{
result = ENSEMBLE_STAT_P10_QUANTITY_NAME;
}
else if (percentile.contains(QString("%1:").arg(ENSEMBLE_STAT_P10_QUANTITY_NAME)))
else if ( percentile.contains( QString( "%1:" ).arg( ENSEMBLE_STAT_P10_QUANTITY_NAME ) ) )
{
result.replace(ENSEMBLE_STAT_P10_QUANTITY_NAME, ENSEMBLE_STAT_P90_QUANTITY_NAME);
result.replace( ENSEMBLE_STAT_P10_QUANTITY_NAME, ENSEMBLE_STAT_P90_QUANTITY_NAME );
}
else if (percentile.contains(QString("%1:").arg(ENSEMBLE_STAT_P90_QUANTITY_NAME)))
else if ( percentile.contains( QString( "%1:" ).arg( ENSEMBLE_STAT_P90_QUANTITY_NAME ) ) )
{
result.replace(ENSEMBLE_STAT_P90_QUANTITY_NAME, ENSEMBLE_STAT_P10_QUANTITY_NAME);
result.replace( ENSEMBLE_STAT_P90_QUANTITY_NAME, ENSEMBLE_STAT_P10_QUANTITY_NAME );
}
return result;
}

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,26 +26,26 @@ class QString;
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaStatisticsTools
{
public:
static const QString replacePercentileByPValueText(const QString& percentile);
static const QString replacePercentileByPValueText( const QString& percentile );
template<class NumberType> static bool isInvalidNumber(NumberType value)
template <class NumberType>
static bool isInvalidNumber( NumberType value )
{
return !isValidNumber<NumberType>(value);
return !isValidNumber<NumberType>( value );
}
template<class NumberType> static bool isValidNumber(NumberType value)
template <class NumberType>
static bool isValidNumber( NumberType value )
{
if (std::isinf(value)) return false;
if (std::isnan(value)) return false;
if ( std::isinf( value ) ) return false;
if ( std::isnan( value ) ) return false;
return true;
}
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,52 +19,52 @@
#include "RiaStdStringTools.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaStdStringTools::trimString(const std::string& s)
std::string RiaStdStringTools::trimString( const std::string& s )
{
auto sCopy = s.substr(0, s.find_last_not_of(' ') + 1);
sCopy = sCopy.substr(sCopy.find_first_not_of(' '));
auto sCopy = s.substr( 0, s.find_last_not_of( ' ' ) + 1 );
sCopy = sCopy.substr( sCopy.find_first_not_of( ' ' ) );
return sCopy;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::isNumber(const std::string& s, char decimalPoint)
bool RiaStdStringTools::isNumber( const std::string& s, char decimalPoint )
{
if (s.size() == 0) return false;
if (findCharMatchCount(s, decimalPoint) > 1) return false;
if (findCharMatchCount(s, '-') > 1) return false;
if (findCharMatchCount(s, 'e') > 1) return false;
if (findCharMatchCount(s, 'E') > 1) return false;
if ( s.size() == 0 ) return false;
if ( findCharMatchCount( s, decimalPoint ) > 1 ) return false;
if ( findCharMatchCount( s, '-' ) > 1 ) return false;
if ( findCharMatchCount( s, 'e' ) > 1 ) return false;
if ( findCharMatchCount( s, 'E' ) > 1 ) return false;
std::string matchChars("0123456789eE-");
matchChars.append(1, decimalPoint);
return (s.find_first_not_of(matchChars) == std::string::npos);
std::string matchChars( "0123456789eE-" );
matchChars.append( 1, decimalPoint );
return ( s.find_first_not_of( matchChars ) == std::string::npos );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int16_t RiaStdStringTools::toInt16(const std::string& s)
int16_t RiaStdStringTools::toInt16( const std::string& s )
{
return (int16_t)toInt(s);
return (int16_t)toInt( s );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaStdStringTools::toInt(const std::string& s)
int RiaStdStringTools::toInt( const std::string& s )
{
int intValue = -1;
try
{
intValue = std::stoi(s);
intValue = std::stoi( s );
}
catch (...)
catch ( ... )
{
}
@@ -72,70 +72,70 @@ int RiaStdStringTools::toInt(const std::string& s)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaStdStringTools::toDouble(const std::string& s)
double RiaStdStringTools::toDouble( const std::string& s )
{
double doubleValue = -1.0;
char* end;
doubleValue = std::strtod(s.data(), &end);
doubleValue = std::strtod( s.data(), &end );
return doubleValue;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::containsAlphabetic(const std::string& s)
bool RiaStdStringTools::containsAlphabetic( const std::string& s )
{
return std::find_if(s.begin(), s.end(), [](char c) { return isalpha(c); }) != s.end();
return std::find_if( s.begin(), s.end(), []( char c ) { return isalpha( c ); } ) != s.end();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::startsWithAlphabetic(const std::string& s)
bool RiaStdStringTools::startsWithAlphabetic( const std::string& s )
{
if (s.empty()) return false;
if ( s.empty() ) return false;
return isalpha(s[0]) != 0;
return isalpha( s[0] ) != 0;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::endsWith(const std::string& mainStr, const std::string& toMatch)
bool RiaStdStringTools::endsWith( const std::string& mainStr, const std::string& toMatch )
{
if (mainStr.size() >= toMatch.size() && mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
if ( mainStr.size() >= toMatch.size() &&
mainStr.compare( mainStr.size() - toMatch.size(), toMatch.size(), toMatch ) == 0 )
return true;
else
return false;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<std::string> RiaStdStringTools::splitStringBySpace(const std::string& s)
std::vector<std::string> RiaStdStringTools::splitStringBySpace( const std::string& s )
{
std::vector<std::string> words;
splitByDelimiter(s, words);
splitByDelimiter( s, words );
return words;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
size_t RiaStdStringTools::findCharMatchCount(const std::string& s, char c)
size_t RiaStdStringTools::findCharMatchCount( const std::string& s, char c )
{
size_t count = 0;
size_t pos = 0;
while ((pos = s.find_first_of(c, pos + 1)) != std::string::npos)
size_t pos = 0;
while ( ( pos = s.find_first_of( c, pos + 1 ) ) != std::string::npos )
{
count++;
}
return count;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -30,39 +30,38 @@
class RiaStdStringTools
{
public:
static std::string trimString(const std::string& s);
static bool isNumber(const std::string& s, char decimalPoint);
static std::string trimString( const std::string& s );
static bool isNumber( const std::string& s, char decimalPoint );
static int16_t toInt16(const std::string& s);
static int toInt(const std::string& s);
static double toDouble(const std::string& s);
static bool containsAlphabetic(const std::string& s);
static bool startsWithAlphabetic(const std::string& s);
static int16_t toInt16( const std::string& s );
static int toInt( const std::string& s );
static double toDouble( const std::string& s );
static bool containsAlphabetic( const std::string& s );
static bool startsWithAlphabetic( const std::string& s );
static bool endsWith(const std::string& mainStr, const std::string& toMatch);
static bool endsWith( const std::string& mainStr, const std::string& toMatch );
static std::vector<std::string> splitStringBySpace(const std::string& s);
static std::vector<std::string> splitStringBySpace( const std::string& s );
private:
template <class Container>
static void splitByDelimiter(const std::string& str, Container& cont, char delimiter = ' ');
static size_t findCharMatchCount(const std::string& s, char c);
static void splitByDelimiter( const std::string& str, Container& cont, char delimiter = ' ' );
static size_t findCharMatchCount( const std::string& s, char c );
};
//==================================================================================================
//
//==================================================================================================
template <class Container>
void RiaStdStringTools::splitByDelimiter(const std::string& str, Container& cont, char delimiter)
void RiaStdStringTools::splitByDelimiter( const std::string& str, Container& cont, char delimiter )
{
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter))
std::stringstream ss( str );
std::string token;
while ( std::getline( ss, token, delimiter ) )
{
if (token.find_first_not_of(delimiter) != std::string::npos)
if ( token.find_first_not_of( delimiter ) != std::string::npos )
{
cont.push_back(token);
cont.push_back( token );
}
}
}

View File

@@ -3,41 +3,40 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaStringEncodingTools.h"
const std::string RiaStringEncodingTools::toNativeEncoded(const QString& qstring)
const std::string RiaStringEncodingTools::toNativeEncoded( const QString& qstring )
{
#ifdef WIN32
return std::string(qstring.toLatin1().data());
return std::string( qstring.toLatin1().data() );
#else
return std::string(qstring.toUtf8().data());
return std::string( qstring.toUtf8().data() );
#endif
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QString RiaStringEncodingTools::fromNativeEncoded(const char* native)
const QString RiaStringEncodingTools::fromNativeEncoded( const char* native )
{
#ifdef WIN32
return QString::fromLatin1(native);
return QString::fromLatin1( native );
#else
return QString::fromUtf8(native);
return QString::fromUtf8( native );
#endif
}

View File

@@ -3,36 +3,36 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <QString>
#include <QByteArray>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaStringEncodingTools
{
public:
static const std::string toNativeEncoded(const QString& qstring);
static const std::string toNativeEncoded( const QString& qstring );
static const QString fromNativeEncoded(const char* native);
static const QString fromNativeEncoded( const char* native );
};

View File

@@ -34,22 +34,22 @@ RiaSummaryCurveAnalyzer::RiaSummaryCurveAnalyzer() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::appendAdresses(const std::vector<RifEclipseSummaryAddress>& allAddresses)
void RiaSummaryCurveAnalyzer::appendAdresses( const std::vector<RifEclipseSummaryAddress>& allAddresses )
{
for (const auto& adr : allAddresses)
for ( const auto& adr : allAddresses )
{
analyzeSingleAddress(adr);
analyzeSingleAddress( adr );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::appendAdresses(const std::set<RifEclipseSummaryAddress>& allAddresses)
void RiaSummaryCurveAnalyzer::appendAdresses( const std::set<RifEclipseSummaryAddress>& allAddresses )
{
for (const auto& adr : allAddresses)
for ( const auto& adr : allAddresses )
{
analyzeSingleAddress(adr);
analyzeSingleAddress( adr );
}
}
@@ -86,12 +86,12 @@ std::set<std::string> RiaSummaryCurveAnalyzer::quantityNamesNoHistory() const
//--------------------------------------------------------------------------------------------------
std::string RiaSummaryCurveAnalyzer::quantityNameForTitle() const
{
if (quantityNamesWithHistory().size() == 1 && quantityNamesNoHistory().empty())
if ( quantityNamesWithHistory().size() == 1 && quantityNamesNoHistory().empty() )
{
return *quantityNamesWithHistory().begin();
}
if (quantityNamesNoHistory().size() == 1 && quantityNamesWithHistory().empty())
if ( quantityNamesNoHistory().size() == 1 && quantityNamesWithHistory().empty() )
{
return *quantityNamesNoHistory().begin();
}
@@ -126,15 +126,15 @@ std::set<int> RiaSummaryCurveAnalyzer::regionNumbers() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions(const std::string& wellName) const
std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions( const std::string& wellName ) const
{
std::set<std::string> connections;
for (const auto& conn : m_wellCompletions)
for ( const auto& conn : m_wellCompletions )
{
if (conn.first == wellName)
if ( conn.first == wellName )
{
connections.insert(conn.second);
connections.insert( conn.second );
}
}
@@ -144,15 +144,15 @@ std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions(const std::string
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::set<int> RiaSummaryCurveAnalyzer::wellSegmentNumbers(const std::string& wellName) const
std::set<int> RiaSummaryCurveAnalyzer::wellSegmentNumbers( const std::string& wellName ) const
{
std::set<int> segmentNumberForWell;
for (const auto& wellSegment : m_wellSegmentNumbers)
for ( const auto& wellSegment : m_wellSegmentNumbers )
{
if (wellName.empty() || std::get<0>(wellSegment) == wellName)
if ( wellName.empty() || std::get<0>( wellSegment ) == wellName )
{
segmentNumberForWell.insert(std::get<1>(wellSegment));
segmentNumberForWell.insert( std::get<1>( wellSegment ) );
}
}
@@ -178,53 +178,53 @@ std::set<RifEclipseSummaryAddress::SummaryVarCategory> RiaSummaryCurveAnalyzer::
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts(RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier) const
std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts( RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier ) const
{
std::vector<QString> identifierStrings;
if (category == RifEclipseSummaryAddress::SUMMARY_REGION)
if ( category == RifEclipseSummaryAddress::SUMMARY_REGION )
{
for (const auto& regionNumber : m_regionNumbers)
for ( const auto& regionNumber : m_regionNumbers )
{
identifierStrings.push_back(QString::number(regionNumber));
identifierStrings.push_back( QString::number( regionNumber ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL )
{
for (const auto& wellName : m_wellNames)
for ( const auto& wellName : m_wellNames )
{
identifierStrings.push_back(QString::fromStdString(wellName));
identifierStrings.push_back( QString::fromStdString( wellName ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_GROUP)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_GROUP )
{
for (const auto& wellGroupName : m_wellGroupNames)
for ( const auto& wellGroupName : m_wellGroupNames )
{
identifierStrings.push_back(QString::fromStdString(wellGroupName));
identifierStrings.push_back( QString::fromStdString( wellGroupName ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_BLOCK)
else if ( category == RifEclipseSummaryAddress::SUMMARY_BLOCK )
{
for (const auto& ijkBlock : m_blocks)
for ( const auto& ijkBlock : m_blocks )
{
identifierStrings.push_back(QString::fromStdString(ijkBlock));
identifierStrings.push_back( QString::fromStdString( ijkBlock ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT )
{
auto segmentNumbers = wellSegmentNumbers(secondaryIdentifier);
for (const auto& segment : segmentNumbers)
auto segmentNumbers = wellSegmentNumbers( secondaryIdentifier );
for ( const auto& segment : segmentNumbers )
{
identifierStrings.push_back(QString::number(segment));
identifierStrings.push_back( QString::number( segment ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION )
{
auto connections = wellCompletions(secondaryIdentifier);
for (const auto& conn : connections)
auto connections = wellCompletions( secondaryIdentifier );
for ( const auto& conn : connections )
{
identifierStrings.push_back(QString::fromStdString(conn));
identifierStrings.push_back( QString::fromStdString( conn ) );
}
}
@@ -235,16 +235,16 @@ std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts(RifEclipseSummaryA
///
//--------------------------------------------------------------------------------------------------
std::vector<RifEclipseSummaryAddress>
RiaSummaryCurveAnalyzer::addressesForCategory(const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category)
RiaSummaryCurveAnalyzer::addressesForCategory( const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category )
{
std::vector<RifEclipseSummaryAddress> filteredAddresses;
for (const auto& adr : addresses)
for ( const auto& adr : addresses )
{
if (adr.category() == category)
if ( adr.category() == category )
{
filteredAddresses.push_back(adr);
filteredAddresses.push_back( adr );
}
}
@@ -254,13 +254,13 @@ std::vector<RifEclipseSummaryAddress>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::string RiaSummaryCurveAnalyzer::correspondingHistorySummaryCurveName(const std::string& curveName)
std::string RiaSummaryCurveAnalyzer::correspondingHistorySummaryCurveName( const std::string& curveName )
{
static std::string historyIdentifier = "H";
if (RiaStdStringTools::endsWith(curveName, historyIdentifier))
if ( RiaStdStringTools::endsWith( curveName, historyIdentifier ) )
{
std::string candidate = curveName.substr(0, curveName.size() - 1);
std::string candidate = curveName.substr( 0, curveName.size() - 1 );
return candidate;
}
else
@@ -289,9 +289,9 @@ void RiaSummaryCurveAnalyzer::clear()
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::assignCategoryToQuantities() const
{
if (!m_quantities.empty())
if ( !m_quantities.empty() )
{
if (m_quantitiesWithMatchingHistory.empty() && m_quantitiesNoMatchingHistory.empty())
if ( m_quantitiesWithMatchingHistory.empty() && m_quantitiesNoMatchingHistory.empty() )
{
computeQuantityNamesWithHistory();
}
@@ -306,27 +306,27 @@ void RiaSummaryCurveAnalyzer::computeQuantityNamesWithHistory() const
m_quantitiesNoMatchingHistory.clear();
m_quantitiesWithMatchingHistory.clear();
const std::string historyIdentifier("H");
const std::string historyIdentifier( "H" );
for (const auto& s : m_quantities)
for ( const auto& s : m_quantities )
{
std::string correspondingHistoryCurve = correspondingHistorySummaryCurveName(s);
std::string correspondingHistoryCurve = correspondingHistorySummaryCurveName( s );
if (m_quantities.find(correspondingHistoryCurve) != m_quantities.end())
if ( m_quantities.find( correspondingHistoryCurve ) != m_quantities.end() )
{
// Insert the curve name without H
if (RiaStdStringTools::endsWith(s, historyIdentifier))
if ( RiaStdStringTools::endsWith( s, historyIdentifier ) )
{
m_quantitiesWithMatchingHistory.insert(correspondingHistoryCurve);
m_quantitiesWithMatchingHistory.insert( correspondingHistoryCurve );
}
else
{
m_quantitiesWithMatchingHistory.insert(s);
m_quantitiesWithMatchingHistory.insert( s );
}
}
else
{
m_quantitiesNoMatchingHistory.insert(s);
m_quantitiesNoMatchingHistory.insert( s );
}
}
}
@@ -334,48 +334,48 @@ void RiaSummaryCurveAnalyzer::computeQuantityNamesWithHistory() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::analyzeSingleAddress(const RifEclipseSummaryAddress& address)
void RiaSummaryCurveAnalyzer::analyzeSingleAddress( const RifEclipseSummaryAddress& address )
{
const std::string& wellName = address.wellName();
if (!wellName.empty())
if ( !wellName.empty() )
{
m_wellNames.insert(wellName);
m_wellNames.insert( wellName );
}
if (!address.quantityName().empty())
if ( !address.quantityName().empty() )
{
m_quantities.insert(address.quantityName());
m_quantities.insert( address.quantityName() );
}
if (!address.wellGroupName().empty())
if ( !address.wellGroupName().empty() )
{
m_wellGroupNames.insert(address.wellGroupName());
m_wellGroupNames.insert( address.wellGroupName() );
}
if (address.regionNumber() != -1)
if ( address.regionNumber() != -1 )
{
m_regionNumbers.insert(address.regionNumber());
m_regionNumbers.insert( address.regionNumber() );
}
if (address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION)
if ( address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION )
{
auto wellNameAndCompletion = std::make_pair(wellName, address.blockAsString());
m_wellCompletions.insert(wellNameAndCompletion);
auto wellNameAndCompletion = std::make_pair( wellName, address.blockAsString() );
m_wellCompletions.insert( wellNameAndCompletion );
}
else if (address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT)
else if ( address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT )
{
auto wellNameAndSegment = std::make_pair(wellName, address.wellSegmentNumber());
m_wellSegmentNumbers.insert(wellNameAndSegment);
auto wellNameAndSegment = std::make_pair( wellName, address.wellSegmentNumber() );
m_wellSegmentNumbers.insert( wellNameAndSegment );
}
else if (address.category() == RifEclipseSummaryAddress::SUMMARY_BLOCK)
else if ( address.category() == RifEclipseSummaryAddress::SUMMARY_BLOCK )
{
auto text = address.blockAsString();
m_blocks.insert(text);
m_blocks.insert( text );
}
if (address.category() != RifEclipseSummaryAddress::SUMMARY_INVALID)
if ( address.category() != RifEclipseSummaryAddress::SUMMARY_INVALID )
{
m_categories.insert(address.category());
m_categories.insert( address.category() );
}
}

View File

@@ -37,8 +37,8 @@ class RiaSummaryCurveAnalyzer
public:
RiaSummaryCurveAnalyzer();
void appendAdresses(const std::set<RifEclipseSummaryAddress>& allAddresses);
void appendAdresses(const std::vector<RifEclipseSummaryAddress>& allAddresses);
void appendAdresses( const std::set<RifEclipseSummaryAddress>& allAddresses );
void appendAdresses( const std::vector<RifEclipseSummaryAddress>& allAddresses );
void clear();
@@ -52,25 +52,26 @@ public:
std::set<std::string> wellGroupNames() const;
std::set<int> regionNumbers() const;
std::set<std::string> wellCompletions(const std::string& wellName) const;
std::set<int> wellSegmentNumbers(const std::string& wellName) const;
std::set<std::string> wellCompletions( const std::string& wellName ) const;
std::set<int> wellSegmentNumbers( const std::string& wellName ) const;
std::set<std::string> blocks() const;
std::set<RifEclipseSummaryAddress::SummaryVarCategory> categories() const;
std::vector<QString> identifierTexts(RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier) const;
std::vector<QString> identifierTexts( RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier ) const;
static std::vector<RifEclipseSummaryAddress> addressesForCategory(const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category);
static std::vector<RifEclipseSummaryAddress>
addressesForCategory( const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category );
static std::string correspondingHistorySummaryCurveName(const std::string& curveName);
static std::string correspondingHistorySummaryCurveName( const std::string& curveName );
private:
void assignCategoryToQuantities() const;
void computeQuantityNamesWithHistory() const;
void analyzeSingleAddress(const RifEclipseSummaryAddress& address);
void analyzeSingleAddress( const RifEclipseSummaryAddress& address );
private:
std::set<std::string> m_quantities;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,8 +22,8 @@
#include "RifEclipseSummaryAddress.h"
#include "RimOilField.h"
#include "RimMainPlotCollection.h"
#include "RimOilField.h"
#include "RimProject.h"
#include "RimSummaryCaseMainCollection.h"
#include "RimSummaryCrossPlot.h"
@@ -31,11 +31,11 @@
#include "RimSummaryPlot.h"
#include "RimSummaryPlotCollection.h"
#include "cafPdmObject.h"
#include "RimSummaryCrossPlotCollection.h"
#include "cafPdmObject.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlotCollection* RiaSummaryTools::summaryPlotCollection()
{
@@ -49,30 +49,32 @@ RimSummaryPlotCollection* RiaSummaryTools::summaryPlotCollection()
//--------------------------------------------------------------------------------------------------
RimSummaryCaseMainCollection* RiaSummaryTools::summaryCaseMainCollection()
{
RimProject* project = RiaApplication::instance()->project();
RimProject* project = RiaApplication::instance()->project();
RimSummaryCaseMainCollection* summaryCaseMainCollection = project->activeOilField()->summaryCaseMainCollection();
CVF_ASSERT(summaryCaseMainCollection);
CVF_ASSERT( summaryCaseMainCollection );
return summaryCaseMainCollection;
}
//--------------------------------------------------------------------------------------------------
/// Update the summary curves referencing this curve, as the curve is identified by the name
//--------------------------------------------------------------------------------------------------
void RiaSummaryTools::notifyCalculatedCurveNameHasChanged(const QString& previousCurveName, const QString& currentCurveName)
void RiaSummaryTools::notifyCalculatedCurveNameHasChanged( const QString& previousCurveName,
const QString& currentCurveName )
{
RimSummaryPlotCollection* summaryPlotColl = RiaSummaryTools::summaryPlotCollection();
for (RimSummaryPlot* plot : summaryPlotColl->summaryPlots())
for ( RimSummaryPlot* plot : summaryPlotColl->summaryPlots() )
{
for (RimSummaryCurve* curve : plot->summaryCurves())
for ( RimSummaryCurve* curve : plot->summaryCurves() )
{
RifEclipseSummaryAddress adr = curve->summaryAddressY();
if (adr.category() == RifEclipseSummaryAddress::SUMMARY_CALCULATED)
if ( adr.category() == RifEclipseSummaryAddress::SUMMARY_CALCULATED )
{
if (adr.quantityName() == previousCurveName.toStdString())
if ( adr.quantityName() == previousCurveName.toStdString() )
{
RifEclipseSummaryAddress updatedAdr = RifEclipseSummaryAddress::calculatedAddress(currentCurveName.toStdString());
curve->setSummaryAddressYAndApplyInterpolation(updatedAdr);
RifEclipseSummaryAddress updatedAdr = RifEclipseSummaryAddress::calculatedAddress(
currentCurveName.toStdString() );
curve->setSummaryAddressYAndApplyInterpolation( updatedAdr );
}
}
}
@@ -80,74 +82,74 @@ void RiaSummaryTools::notifyCalculatedCurveNameHasChanged(const QString& previou
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlot* RiaSummaryTools::parentSummaryPlot(caf::PdmObject* object)
RimSummaryPlot* RiaSummaryTools::parentSummaryPlot( caf::PdmObject* object )
{
if (parentCrossPlot(object))
if ( parentCrossPlot( object ) )
{
return nullptr;
}
RimSummaryPlot* summaryPlot = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(summaryPlot);
object->firstAncestorOrThisOfType( summaryPlot );
}
return summaryPlot;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlotCollection* RiaSummaryTools::parentSummaryPlotCollection(caf::PdmObject* object)
RimSummaryPlotCollection* RiaSummaryTools::parentSummaryPlotCollection( caf::PdmObject* object )
{
RimSummaryPlotCollection* summaryPlotColl = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(summaryPlotColl);
object->firstAncestorOrThisOfType( summaryPlotColl );
}
return summaryPlotColl;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryCrossPlot* RiaSummaryTools::parentCrossPlot(caf::PdmObject* object)
RimSummaryCrossPlot* RiaSummaryTools::parentCrossPlot( caf::PdmObject* object )
{
RimSummaryCrossPlot* crossPlot = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(crossPlot);
object->firstAncestorOrThisOfType( crossPlot );
}
return crossPlot;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryCrossPlotCollection* RiaSummaryTools::parentCrossPlotCollection(caf::PdmObject* object)
RimSummaryCrossPlotCollection* RiaSummaryTools::parentCrossPlotCollection( caf::PdmObject* object )
{
RimSummaryCrossPlotCollection* crossPlotColl = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(crossPlotColl);
object->firstAncestorOrThisOfType( crossPlotColl );
}
return crossPlotColl;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaSummaryTools::isSummaryCrossPlot(const RimSummaryPlot* plot)
bool RiaSummaryTools::isSummaryCrossPlot( const RimSummaryPlot* plot )
{
return dynamic_cast<const RimSummaryCrossPlot*>(plot);
return dynamic_cast<const RimSummaryCrossPlot*>( plot );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,25 +26,25 @@ class RimSummaryCaseMainCollection;
class QString;
namespace caf {
class PdmObject;
namespace caf
{
class PdmObject;
}
//==================================================================================================
//
//
//==================================================================================================
class RiaSummaryTools
{
public:
static RimSummaryPlotCollection* summaryPlotCollection();
static RimSummaryCaseMainCollection* summaryCaseMainCollection();
static void notifyCalculatedCurveNameHasChanged(const QString& previousCurveName,
const QString& currentCurveName);
static RimSummaryPlotCollection* summaryPlotCollection();
static RimSummaryCaseMainCollection* summaryCaseMainCollection();
static void notifyCalculatedCurveNameHasChanged( const QString& previousCurveName, const QString& currentCurveName );
static RimSummaryPlot* parentSummaryPlot(caf::PdmObject* object);
static RimSummaryPlotCollection* parentSummaryPlotCollection(caf::PdmObject* object);
static RimSummaryPlot* parentSummaryPlot( caf::PdmObject* object );
static RimSummaryPlotCollection* parentSummaryPlotCollection( caf::PdmObject* object );
static RimSummaryCrossPlot* parentCrossPlot(caf::PdmObject* object);
static RimSummaryCrossPlotCollection* parentCrossPlotCollection(caf::PdmObject* object);
static bool isSummaryCrossPlot(const RimSummaryPlot* plot);
static RimSummaryCrossPlot* parentCrossPlot( caf::PdmObject* object );
static RimSummaryCrossPlotCollection* parentCrossPlotCollection( caf::PdmObject* object );
static bool isSummaryCrossPlot( const RimSummaryPlot* plot );
};

View File

@@ -25,8 +25,8 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaTextFileCompare::RiaTextFileCompare(const QString& pathToDiffTool)
: m_pathToDiffTool(pathToDiffTool)
RiaTextFileCompare::RiaTextFileCompare( const QString& pathToDiffTool )
: m_pathToDiffTool( pathToDiffTool )
{
reset();
}
@@ -50,12 +50,12 @@ void RiaTextFileCompare::reset()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString& generatedFolder)
bool RiaTextFileCompare::runComparison( const QString& baseFolder, const QString& generatedFolder )
{
reset();
QString fullFilePath = "diff";
if (!m_pathToDiffTool.isEmpty())
if ( !m_pathToDiffTool.isEmpty() )
{
fullFilePath = m_pathToDiffTool + "/" + fullFilePath;
}
@@ -64,15 +64,16 @@ bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString&
// See https://docs.freebsd.org/info/diff/diff.info.diff_Options.html
QString args = "-r -u --strip-trailing-cr";
QString completeCommand = QString("\"%1\" %2 %3 %4").arg(fullFilePath).arg(baseFolder).arg(generatedFolder).arg(args);
QString completeCommand =
QString( "\"%1\" %2 %3 %4" ).arg( fullFilePath ).arg( baseFolder ).arg( generatedFolder ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running 'diff' tool process";
@@ -83,11 +84,11 @@ bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString&
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if (procExitCode == 0)
if ( procExitCode == 0 )
{
return true;
}
else if (procExitCode == 1)
else if ( procExitCode == 1 )
{
QByteArray stdOut = proc.readAllStandardOutput();
m_diffOutput = stdOut;

View File

@@ -36,10 +36,10 @@ public:
};
public:
explicit RiaTextFileCompare(const QString& pathToDiffTool);
explicit RiaTextFileCompare( const QString& pathToDiffTool );
~RiaTextFileCompare();
bool runComparison(const QString& baseFolder, const QString& generatedFolder);
bool runComparison( const QString& baseFolder, const QString& generatedFolder );
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;

View File

@@ -20,18 +20,17 @@
#include <QString>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaTextStringTools::compare(const QString& expected, const QString& actual)
bool RiaTextStringTools::compare( const QString& expected, const QString& actual )
{
// Suggestions for improvement
// 1. report line number for first change
// 2. report line numbers for all changes
// 3. add support for compare with content of a text file on disk
if (expected.compare(actual) == 0)
if ( expected.compare( actual ) == 0 )
{
return true;
}
@@ -40,19 +39,18 @@ bool RiaTextStringTools::compare(const QString& expected, const QString& actual)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaTextStringTools::trimAndRemoveDoubleSpaces(const QString& s)
QString RiaTextStringTools::trimAndRemoveDoubleSpaces( const QString& s )
{
int length;
int length;
QString trimmed = s.trimmed();
do
do
{
length = trimmed.size();
trimmed = trimmed.replace(" ", " ");
} while (trimmed.size() < length);
length = trimmed.size();
trimmed = trimmed.replace( " ", " " );
} while ( trimmed.size() < length );
return trimmed;
}

View File

@@ -21,10 +21,10 @@
class QString;
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
namespace RiaTextStringTools
{
bool compare(const QString& expected, const QString& actual);
QString trimAndRemoveDoubleSpaces(const QString& s);
}
bool compare( const QString& expected, const QString& actual );
QString trimAndRemoveDoubleSpaces( const QString& s );
} // namespace RiaTextStringTools

View File

@@ -1,29 +1,29 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include <cvfConfigCore.h>
#include <cvfAssert.h>
#include <cvfConfigCore.h>
#include "RiaTimeHistoryCurveResampler.h"
#include <limits>
//QString tostring(const QDateTime& dt)
// QString tostring(const QDateTime& dt)
//{
// int y = dt.date().year();
// int m = dt.date().month();
@@ -39,45 +39,42 @@
//--------------------------------------------------------------------------------------------------
/// Internal constants
//--------------------------------------------------------------------------------------------------
#define DOUBLE_INF std::numeric_limits<double>::infinity()
#define DOUBLE_INF std::numeric_limits<double>::infinity()
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaTimeHistoryCurveResampler::RiaTimeHistoryCurveResampler()
RiaTimeHistoryCurveResampler::RiaTimeHistoryCurveResampler() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::setCurveData( const std::vector<double>& values, const std::vector<time_t>& timeSteps )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::setCurveData(const std::vector<double>& values, const std::vector<time_t>& timeSteps)
{
CVF_ASSERT(values.size() == timeSteps.size());
CVF_ASSERT( values.size() == timeSteps.size() );
clearData();
m_originalValues = std::make_pair(values, timeSteps);
m_originalValues = std::make_pair( values, timeSteps );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::resampleAndComputePeriodEndValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::resampleAndComputePeriodEndValues( DateTimePeriod period )
{
computePeriodEndValues(period);
computePeriodEndValues( period );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::resampleAndComputeWeightedMeanValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::resampleAndComputeWeightedMeanValues( DateTimePeriod period )
{
computeWeightedMeanValues(period);
computeWeightedMeanValues( period );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const std::vector<time_t>& RiaTimeHistoryCurveResampler::resampledTimeSteps() const
{
@@ -85,7 +82,7 @@ const std::vector<time_t>& RiaTimeHistoryCurveResampler::resampledTimeSteps() co
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const std::vector<double>& RiaTimeHistoryCurveResampler::resampledValues() const
{
@@ -93,70 +90,71 @@ const std::vector<double>& RiaTimeHistoryCurveResampler::resampledValues() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<time_t> RiaTimeHistoryCurveResampler::timeStepsFromTimeRange(DateTimePeriod period, time_t minTime, time_t maxTime)
std::vector<time_t>
RiaTimeHistoryCurveResampler::timeStepsFromTimeRange( DateTimePeriod period, time_t minTime, time_t maxTime )
{
if(minTime > maxTime) return std::vector<time_t>();
if ( minTime > maxTime ) return std::vector<time_t>();
auto firstOriginalTimeStep = QDT::fromTime_t(minTime);
auto lastOriginalTimeStep = QDT::fromTime_t(maxTime);
auto firstOriginalTimeStep = QDT::fromTime_t( minTime );
auto lastOriginalTimeStep = QDT::fromTime_t( maxTime );
auto currTimeStep = firstResampledTimeStep(firstOriginalTimeStep, period);
auto currTimeStep = firstResampledTimeStep( firstOriginalTimeStep, period );
std::vector<time_t> timeSteps;
while (QDT::lessThan(currTimeStep, lastOriginalTimeStep))
while ( QDT::lessThan( currTimeStep, lastOriginalTimeStep ) )
{
timeSteps.push_back(currTimeStep.toTime_t());
currTimeStep = QDT::addPeriod(currTimeStep, period);
timeSteps.push_back( currTimeStep.toTime_t() );
currTimeStep = QDT::addPeriod( currTimeStep, period );
}
timeSteps.push_back(currTimeStep.toTime_t());
timeSteps.push_back( currTimeStep.toTime_t() );
return timeSteps;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computeWeightedMeanValues( DateTimePeriod period )
{
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
computeResampledTimeSteps(period);
computeResampledTimeSteps( period );
m_values.reserve(m_timeSteps.size());
for (size_t i = 0; i < m_timeSteps.size(); i++)
m_values.reserve( m_timeSteps.size() );
for ( size_t i = 0; i < m_timeSteps.size(); i++ )
{
double wMean = 0.0;
time_t periodStart = i > 0 ? m_timeSteps[i - 1] :
QDT::subtractPeriod(QDT::fromTime_t(m_timeSteps[0]), period).toTime_t();
time_t periodEnd = m_timeSteps[i];
double wMean = 0.0;
time_t periodStart = i > 0 ? m_timeSteps[i - 1]
: QDT::subtractPeriod( QDT::fromTime_t( m_timeSteps[0] ), period ).toTime_t();
time_t periodEnd = m_timeSteps[i];
time_t periodLength = periodEnd - periodStart;
while(true)
while ( true )
{
time_t origTimeStep = 0;
double origValue = 0.0;
double origValue = 0.0;
if (oi > origDataSize) break;
if ( oi > origDataSize ) break;
if (oi < origDataSize)
if ( oi < origDataSize )
{
origTimeStep = origTimeSteps[oi];
origValue = origValues[oi] != DOUBLE_INF ? origValues[oi] : 0.0;
origValue = origValues[oi] != DOUBLE_INF ? origValues[oi] : 0.0;
}
else
{
origTimeStep = periodEnd;
origValue = 0.0;
origValue = 0.0;
}
if (oi == 0)
if ( oi == 0 )
{
if (origTimeStep == m_timeSteps[i])
if ( origTimeStep == m_timeSteps[i] )
{
wMean += origValue;
oi++;
@@ -165,13 +163,13 @@ void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod peri
origValue = 0.0;
}
time_t startTime = oi > 0 ? std::max(origTimeSteps[oi - 1], periodStart) : periodStart;
time_t endTime = std::min(origTimeStep, periodEnd);
wMean += origValue * (endTime - startTime) / periodLength;
time_t startTime = oi > 0 ? std::max( origTimeSteps[oi - 1], periodStart ) : periodStart;
time_t endTime = std::min( origTimeStep, periodEnd );
if (origTimeStep > m_timeSteps[i]) break;
if (origTimeStep == m_timeSteps[i])
wMean += origValue * ( endTime - startTime ) / periodLength;
if ( origTimeStep > m_timeSteps[i] ) break;
if ( origTimeStep == m_timeSteps[i] )
{
oi++;
break;
@@ -179,46 +177,47 @@ void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod peri
oi++;
}
m_values.push_back(wMean);
m_values.push_back( wMean );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computePeriodEndValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computePeriodEndValues( DateTimePeriod period )
{
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
computeResampledTimeSteps(period);
computeResampledTimeSteps( period );
m_values.reserve(m_timeSteps.size());
for (size_t i = 0; i < m_timeSteps.size(); i++)
m_values.reserve( m_timeSteps.size() );
for ( size_t i = 0; i < m_timeSteps.size(); i++ )
{
while (oi < origDataSize && origTimeSteps[oi] < m_timeSteps[i]) oi++;
while ( oi < origDataSize && origTimeSteps[oi] < m_timeSteps[i] )
oi++;
time_t origTimeStep = oi < origDataSize ? origTimeSteps[oi] : m_timeSteps[i];
double origValue = oi < origDataSize ? origValues[oi] : origValues[oi - 1];
double origValue = oi < origDataSize ? origValues[oi] : origValues[oi - 1];
double value;
if (oi > 0 && origTimeStep >= m_timeSteps[i])
if ( oi > 0 && origTimeStep >= m_timeSteps[i] )
{
value = interpolatedValue(m_timeSteps[i], origTimeSteps[oi - 1], origValues[oi - 1], origTimeStep, origValue);
value = interpolatedValue( m_timeSteps[i], origTimeSteps[oi - 1], origValues[oi - 1], origTimeStep, origValue );
}
else
{
value = origValue;
}
m_values.push_back(value);
m_values.push_back( value );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::clearData()
{
@@ -227,48 +226,48 @@ void RiaTimeHistoryCurveResampler::clearData()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computeResampledTimeSteps(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computeResampledTimeSteps( DateTimePeriod period )
{
CVF_ASSERT(period != DateTimePeriod::NONE && m_originalValues.second.size() > 0);
CVF_ASSERT( period != DateTimePeriod::NONE && m_originalValues.second.size() > 0 );
auto firstOriginalTimeStep = QDT::fromTime_t(m_originalValues.second.front());
auto lastOriginalTimeStep = QDT::fromTime_t(m_originalValues.second.back());
auto firstOriginalTimeStep = QDT::fromTime_t( m_originalValues.second.front() );
auto lastOriginalTimeStep = QDT::fromTime_t( m_originalValues.second.back() );
clearData();
auto currTimeStep = firstResampledTimeStep(firstOriginalTimeStep, period);
auto currTimeStep = firstResampledTimeStep( firstOriginalTimeStep, period );
while (QDT::lessThan(currTimeStep, lastOriginalTimeStep))
while ( QDT::lessThan( currTimeStep, lastOriginalTimeStep ) )
{
m_timeSteps.push_back(currTimeStep.toTime_t());
currTimeStep = QDT::addPeriod(currTimeStep, period);
m_timeSteps.push_back( currTimeStep.toTime_t() );
currTimeStep = QDT::addPeriod( currTimeStep, period );
}
// Add last time step
m_timeSteps.push_back(currTimeStep.toTime_t());
m_timeSteps.push_back( currTimeStep.toTime_t() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaTimeHistoryCurveResampler::firstResampledTimeStep(const QDateTime& firstTimeStep, DateTimePeriod period)
QDateTime RiaTimeHistoryCurveResampler::firstResampledTimeStep( const QDateTime& firstTimeStep, DateTimePeriod period )
{
QDateTime truncatedTime = QDT::truncateTime(firstTimeStep, period);
QDateTime truncatedTime = QDT::truncateTime( firstTimeStep, period );
if (QDT::lessThan(truncatedTime, firstTimeStep)) return QDT::addPeriod(truncatedTime, period);
if ( QDT::lessThan( truncatedTime, firstTimeStep ) ) return QDT::addPeriod( truncatedTime, period );
return truncatedTime;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaTimeHistoryCurveResampler::interpolatedValue(time_t t, time_t t1, double v1, time_t t2, double v2)
double RiaTimeHistoryCurveResampler::interpolatedValue( time_t t, time_t t1, double v1, time_t t2, double v2 )
{
CVF_ASSERT(t2 >= t1);
CVF_ASSERT( t2 >= t1 );
if (t <= t1) return v1;
if (t >= t2) return v2;
if ( t <= t1 ) return v1;
if ( t >= t2 ) return v2;
return (v2 - v1) * (double)(t - t1) / (double)(t2 - t1) + v1;
return ( v2 - v1 ) * (double)( t - t1 ) / (double)( t2 - t1 ) + v1;
}

Some files were not shown because too many files have changed in this diff Show More