Merge branch 'dev' into feature-analysis-plots-initial

This commit is contained in:
Magne Sjaastad
2020-03-06 08:06:48 +01:00
114 changed files with 2465 additions and 1025 deletions

View File

@@ -11,20 +11,19 @@ jobs:
include:
- os: windows-latest
triplet: x64-windows
vcpkgGitCommitId: '6282cab61d175974b1af06473db584b9b80dcd48'
vcpkgPackages: 'grpc'
- os: ubuntu-latest
triplet: x64-linux
vcpkgGitCommitId: '6282cab61d175974b1af06473db584b9b80dcd48'
vcpkgPackages: 'grpc'
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v1
with:
submodules: true
- name: Install Qt
uses: ouuan/install-qt-action@v2.3.1
uses: jurplel/install-qt-action@v2.5.0
with:
version: 5.9
modules: qtscript
mirror: 'http://mirrors.ocf.berkeley.edu/qt/'
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
@@ -36,36 +35,39 @@ jobs:
- name: Cache vcpkg artifacts
uses: actions/cache@v1
env:
cache-name: cache-vcpkg-modules
vcpkgResponseFile: '${{ github.workspace }}/vcpkg_${{ matrix.triplet }}.txt'
with:
path: ${{ github.workspace }}/vcpkg/
key: ${{ env.cache-name }}-${{ runner.os }}
# Ensure the cache is invalidated any time vcpkg version changes, or a different set of packages is being used.
key: ${{ hashFiles( env.vcpkgResponseFile ) }}-${{ hashFiles('.git/modules/vcpkg/HEAD') }}-${{ runner.os }}
- name: Run vcpkg
uses: lukka/run-vcpkg@v0.10
uses: lukka/run-vcpkg@v0
id: runvcpkg
env:
vcpkgResponseFile: '${{ github.workspace }}/vcpkg_${{ matrix.triplet }}.txt'
with:
vcpkgArguments: '${{ matrix.vcpkgPackages }}'
vcpkgTriplet: '${{ matrix.triplet }}'
vcpkgGitCommitId: '${{ matrix.vcpkgGitCommitId }}'
vcpkgArguments: '@${{ env.vcpkgResponseFile }}'
vcpkgDirectory: '${{ github.workspace }}/vcpkg'
- name: Prints outputs of run-vcpkg task
run: echo "'${{ steps.runvcpkg.outputs.RUNVCPKG_VCPKG_ROOT_OUT }}' '${{ steps.runvcpkg.outputs.RUNVCPKG_VCPKG_TRIPLET_OUT }}' "
- name: Build ResInsight-x64 Windows
if: "contains( matrix.os, 'windows')"
- name: Build ResInsight-x64
uses: lukka/run-cmake@v0
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeAppendedArgs: -DRESINSIGHT_ENABLE_GRPC=true -DRESINSIGHT_GRPC_PYTHON_EXECUTABLE=python -DRESINSIGHT_ENABLE_PRECOMPILED_HEADERS=true -DRESINSIGHT_ENABLE_UNITY_BUILD=true
buildDirectory: ${{ github.workspace }}/cmakebuild
buildWithCMakeArgs: '--config Release --target package'
useVcpkgToolchainFile: true
- name: Remove packages/_CPack_Packages
shell: bash
run: |
mkdir cmakebuild
cd cmakebuild
cmake .. -DRESINSIGHT_ENABLE_GRPC=true -DRESINSIGHT_GRPC_PYTHON_EXECUTABLE=python -DRESINSIGHT_ENABLE_PRECOMPILED_HEADERS=true -DRESINSIGHT_ENABLE_UNITY_BUILD=true -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -A x64
cmake --build . --config Release --target PACKAGE
rd packages/_CPack_Packages -Recurse
- name: Build ResInsight-x64 Linux
if: "contains( matrix.os, 'ubuntu')"
run: |
mkdir cmakebuild
cd cmakebuild
cmake .. -DRESINSIGHT_ENABLE_GRPC=true -DRESINSIGHT_GRPC_PYTHON_EXECUTABLE=python -DRESINSIGHT_ENABLE_PRECOMPILED_HEADERS=true -DRESINSIGHT_ENABLE_UNITY_BUILD=true -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake
cmake --build . --config Release
make package
rm -rf packages/_CPack_Packages
- name: dir
run: find ${{ runner.workspace }}
if: "!contains( matrix.os, 'windows')"
- name: dir
run: gci -recurse ${{ runner.workspace }}
if: contains( matrix.os, 'windows')
- name: Test with pytest
if: "contains( matrix.os, 'windows')" # To be used when RESINSIGHT_GRPC_PYTHON_EXECUTABLE can be 'python' without extention in PATH
env:

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "vcpkg"]
path = vcpkg
url = https://github.com/microsoft/vcpkg

View File

@@ -36,7 +36,6 @@
#include "RicImportGeneralDataFeature.h"
#include "RicfCommandFileExecutor.h"
#include "RicfFieldHandle.h"
#include "RicfMessages.h"
#include "RicfObjectCapability.h"
#include "Rim2dIntersectionViewCollection.h"
@@ -97,7 +96,10 @@
#include "RiuViewer.h"
#include "RiuViewerCommands.h"
#include "cafPdmCodeGenerator.h"
#include "cafPdmDataValueField.h"
#include "cafPdmDefaultObjectFactory.h"
#include "cafPdmScriptIOMessages.h"
#include "cafPdmSettings.h"
#include "cafPdmUiModelChangeDetector.h"
#include "cafProgressInfo.h"
@@ -1261,7 +1263,7 @@ QVariant RiaApplication::cacheDataObject( const QString& key ) const
void RiaApplication::executeCommandFile( const QString& commandFile )
{
QFile file( commandFile );
RicfMessages messages;
caf::PdmScriptIOMessages messages;
if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
// TODO : Error logging?
@@ -1717,180 +1719,26 @@ void RiaApplication::resetProject()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaApplication::generatePythonClasses( const QString& fileName )
bool RiaApplication::generateCode( const QString& fileName, QString* errMsg )
{
auto factory = caf::PdmDefaultObjectFactory::instance();
CAF_ASSERT( errMsg );
QFile pythonFile( fileName );
if ( !pythonFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
return;
}
QTextStream out( &pythonFile );
std::vector<QString> classKeywords = factory->classKeywords();
std::vector<std::shared_ptr<const caf::PdmObject>> dummyObjects;
for ( QString classKeyword : classKeywords )
{
auto objectHandle = factory->create( classKeyword );
const caf::PdmObject* object = dynamic_cast<const caf::PdmObject*>( objectHandle );
CAF_ASSERT( object );
std::shared_ptr<const caf::PdmObject> sharedObject( object );
if ( RicfObjectCapability::isScriptable( sharedObject.get() ) )
{
dummyObjects.push_back( sharedObject );
}
}
// Sort to make sure super classes get created before sub classes
std::sort( dummyObjects.begin(),
dummyObjects.end(),
[]( std::shared_ptr<const caf::PdmObject> lhs, std::shared_ptr<const caf::PdmObject> rhs ) {
if ( lhs->inheritsClassWithKeyword( rhs->classKeyword() ) )
QFile outputFile( fileName );
if ( !outputFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
*errMsg = QString( "Could not open file %1 for writing" ).arg( fileName );
return false;
}
return lhs->classKeyword() < rhs->classKeyword();
} );
QTextStream out( &outputFile );
std::map<QString, std::map<QString, std::pair<QString, QString>>> classesGenerated;
std::map<QString, QString> classCommentsGenerated;
std::string fileExt = QFileInfo( fileName ).suffix().toStdString();
// First generate all attributes and comments to go into each object
for ( std::shared_ptr<const caf::PdmObject> object : dummyObjects )
std::unique_ptr<caf::PdmCodeGenerator> generator( caf::PdmCodeGeneratorFactory::instance()->create( fileExt ) );
if ( !generator )
{
const std::list<QString>& classInheritanceStack = object->classInheritanceStack();
for ( auto it = classInheritanceStack.begin(); it != classInheritanceStack.end(); ++it )
{
const QString& classKeyword = *it;
QString scriptClassComment = RicfObjectCapability::scriptClassComment( classKeyword );
std::map<QString, QString> attributesGenerated;
if ( !scriptClassComment.isEmpty() ) classCommentsGenerated[classKeyword] = scriptClassComment;
if ( classKeyword == object->classKeyword() )
{
std::vector<caf::PdmFieldHandle*> fields;
object->fields( fields );
for ( auto field : fields )
{
auto pdmValueField = dynamic_cast<const caf::PdmValueField*>( field );
if ( pdmValueField )
{
QString keyword = pdmValueField->keyword();
auto ricfHandle = field->template capability<RicfFieldHandle>();
if ( ricfHandle != nullptr )
{
QString snake_field_name = RiaTextStringTools::camelToSnakeCase( ricfHandle->fieldName() );
if ( classesGenerated[field->ownerClass()].count( snake_field_name ) ) continue;
QString fieldPythonCode = QString( " self.%1 = None\n" ).arg( snake_field_name );
QString comment;
{
QStringList commentComponents;
commentComponents << pdmValueField->capability<caf::PdmUiFieldHandle>()->uiName();
commentComponents << pdmValueField->capability<caf::PdmUiFieldHandle>()->uiWhatsThis();
commentComponents.removeAll( QString( "" ) );
comment = commentComponents.join( ". " );
*errMsg = QString( "No code generator matches the provided file extension" );
return false;
}
QVariant valueVariant = pdmValueField->toQVariant();
QString dataTypeString = valueVariant.typeName();
classesGenerated[field->ownerClass()][snake_field_name].first = fieldPythonCode;
classesGenerated[field->ownerClass()][snake_field_name].second =
QString( "%1 (%2): %3\n" ).arg( snake_field_name ).arg( dataTypeString ).arg( comment );
}
}
}
}
}
}
// Write out classes
std::set<QString> classesWritten;
for ( std::shared_ptr<const caf::PdmObject> object : dummyObjects )
{
const std::list<QString>& classInheritanceStack = object->classInheritanceStack();
std::list<QString> scriptSuperClassNames;
for ( auto it = classInheritanceStack.begin(); it != classInheritanceStack.end(); ++it )
{
const QString& classKeyword = *it;
QString scriptClassName = RicfObjectCapability::scriptClassNameFromClassKeyword( classKeyword );
if ( scriptClassName.isEmpty() ) scriptClassName = classKeyword;
if ( !classesWritten.count( scriptClassName ) )
{
QString classCode;
if ( scriptSuperClassNames.empty() )
{
classCode = QString( "class %1:\n" ).arg( scriptClassName );
}
else
{
classCode = QString( "class %1(%2):\n" ).arg( scriptClassName ).arg( scriptSuperClassNames.back() );
}
if ( !classCommentsGenerated[classKeyword].isEmpty() || !classesGenerated[classKeyword].empty() )
{
classCode += " \"\"\"\n";
if ( !classCommentsGenerated[classKeyword].isEmpty() )
{
classCode += QString( " %1\n\n" ).arg( classCommentsGenerated[classKeyword] );
}
classCode += " Attributes\n";
classCode += " class_keyword (string): the class keyword that uniquely defines a class\n";
for ( auto keyWordValuePair : classesGenerated[classKeyword] )
{
classCode += " " + keyWordValuePair.second.second;
}
classCode += " \"\"\"\n";
}
classCode +=
QString( " __custom_init__ = None #: Assign a custom init routine to be run at __init__\n\n" );
classCode += QString( " def __init__(self, pb2_object=None, channel=None):\n" );
classCode += QString( " self.class_keyword = \"%1\"\n" ).arg( scriptClassName );
if ( !scriptSuperClassNames.empty() )
{
// Own attributes. This initializes a lot of attributes to None.
// This means it has to be done before we set any values.
for ( auto keyWordValuePair : classesGenerated[classKeyword] )
{
classCode += keyWordValuePair.second.first;
}
// Parent constructor
classCode +=
QString( " %1.__init__(self, pb2_object, channel)\n" ).arg( scriptSuperClassNames.back() );
}
classCode += QString( " if %1.__custom_init__ is not None:\n" ).arg( scriptClassName );
classCode += QString( " %1.__custom_init__(self, pb2_object=pb2_object, channel=channel)\n" )
.arg( scriptClassName );
out << classCode << "\n";
classesWritten.insert( scriptClassName );
}
scriptSuperClassNames.push_back( scriptClassName );
}
}
out << "def class_dict():\n";
out << " classes = {}\n";
for ( QString classKeyword : classesWritten )
{
out << QString( " classes['%1'] = %1\n" ).arg( classKeyword );
}
out << " return classes\n\n";
out << "def class_from_keyword(class_keyword):\n";
out << " all_classes = class_dict()\n";
out << " if class_keyword in all_classes.keys():\n";
out << " return all_classes[class_keyword]\n";
out << " return None\n";
out << generator->generate( caf::PdmDefaultObjectFactory::instance() );
return true;
}

View File

@@ -226,7 +226,7 @@ protected:
friend class RiaRegressionTestRunner;
void resetProject();
void generatePythonClasses( const QString& outputPath );
bool generateCode( const QString& outputPath, QString* errMsg );
protected:
cvf::ref<cvf::Font> m_defaultSceneFont;

View File

@@ -137,7 +137,12 @@ RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments( cvf::P
CVF_ASSERT( o.valueCount() == 1 );
QString outputFile = cvfqt::Utils::toQString( o.value( 0 ) );
RiaApplication::generatePythonClasses( outputFile );
QString errMsg;
if ( !RiaApplication::generateCode( outputFile, &errMsg ) )
{
RiaLogging::error( QString( "Error: %1" ).arg( errMsg ) );
return RiaApplication::EXIT_WITH_ERROR;
}
return RiaApplication::EXIT_COMPLETED;
}

View File

@@ -457,7 +457,12 @@ RiaApplication::ApplicationStatus RiaGuiApplication::handleArguments( cvf::Progr
CVF_ASSERT( o.valueCount() == 1 );
QString outputFile = cvfqt::Utils::toQString( o.value( 0 ) );
RiaApplication::generatePythonClasses( outputFile );
QString errMsg;
if ( !RiaApplication::generateCode( outputFile, &errMsg ) )
{
RiaLogging::error( QString( "Error: %1" ).arg( errMsg ) );
return RiaApplication::EXIT_WITH_ERROR;
}
return RiaApplication::EXIT_COMPLETED;
}

View File

@@ -31,13 +31,13 @@
#include "RiuPlotMainWindow.h"
#include "RicfCommandFileExecutor.h"
#include "RicfMessages.h"
#include "ExportCommands/RicSnapshotAllPlotsToFileFeature.h"
#include "ExportCommands/RicSnapshotAllViewsToFileFeature.h"
#include "ExportCommands/RicSnapshotViewToFileFeature.h"
#include "RicImportSummaryCasesFeature.h"
#include "cafPdmScriptIOMessages.h"
#include "cvfProgramOptions.h"
#include "cvfqtUtils.h"

View File

@@ -55,17 +55,3 @@ QString RiaTextStringTools::trimAndRemoveDoubleSpaces( const QString& s )
return trimmed;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaTextStringTools::camelToSnakeCase( const QString& camelString )
{
static QRegularExpression re1( "(.)([A-Z][a-z]+)" );
static QRegularExpression re2( "([a-z0-9])([A-Z])" );
QString snake_case = camelString;
snake_case.replace( re1, "\\1_\\2" );
snake_case.replace( re2, "\\1_\\2" );
return snake_case.toLower();
}

View File

@@ -27,5 +27,4 @@ namespace RiaTextStringTools
{
bool compare( const QString& expected, const QString& actual );
QString trimAndRemoveDoubleSpaces( const QString& s );
QString camelToSnakeCase( const QString& camelString );
} // namespace RiaTextStringTools

View File

@@ -6,7 +6,6 @@ ${CMAKE_CURRENT_LIST_DIR}/RicfFieldCapability.h
${CMAKE_CURRENT_LIST_DIR}/RicfFieldHandle.h
${CMAKE_CURRENT_LIST_DIR}/RicfObjectCapability.h
${CMAKE_CURRENT_LIST_DIR}/RifcCommandFileReader.h
${CMAKE_CURRENT_LIST_DIR}/RicfMessages.h
)
set (SOURCE_GROUP_SOURCE_FILES
@@ -16,7 +15,6 @@ ${CMAKE_CURRENT_LIST_DIR}/RicfFieldCapability.cpp
${CMAKE_CURRENT_LIST_DIR}/RicfFieldHandle.cpp
${CMAKE_CURRENT_LIST_DIR}/RicfObjectCapability.cpp
${CMAKE_CURRENT_LIST_DIR}/RifcCommandFileReader.cpp
${CMAKE_CURRENT_LIST_DIR}/RicfMessages.cpp
)
list(APPEND CODE_HEADER_FILES

View File

@@ -18,7 +18,7 @@
#include "RicfCommandObject.h"
#include "RiaTextStringTools.h"
#include "cafPdmPythonGenerator.h"
//--------------------------------------------------------------------------------------------------
///
@@ -34,16 +34,3 @@ RicfCommandObject::RicfCommandObject()
RicfCommandObject::~RicfCommandObject()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RicfCommandObject::pythonHelpString( const QString& existingTooltip, const QString& keyword )
{
QString snake_case = RiaTextStringTools::camelToSnakeCase( keyword );
QString helpString = QString( "Available through python/rips as the attribute '%1'" ).arg( snake_case );
if ( !existingTooltip.isEmpty() ) return existingTooltip + "\n\n" + helpString;
return helpString;
}

View File

@@ -20,8 +20,11 @@
#include "RicfCommandResponse.h"
#include "RicfFieldCapability.h"
#include "RicfObjectCapability.h"
#include "cafCmdFeature.h"
#include "cafPdmObject.h"
#include "cafPdmObjectScriptabilityRegister.h"
#include "cafPdmPythonGenerator.h"
//==================================================================================================
//
@@ -35,8 +38,6 @@ public:
~RicfCommandObject() override;
virtual RicfCommandResponse execute() = 0;
static QString pythonHelpString( const QString& existingTooltip, const QString& keyword );
};
#define RICF_InitField( field, keyword, default, uiName, iconResourceName, toolTip, whatsThis ) \
@@ -45,7 +46,7 @@ public:
default, \
uiName, \
iconResourceName, \
RicfCommandObject::pythonHelpString( toolTip, keyword ), \
caf::PdmPythonGenerator::pythonHelpString( toolTip, keyword ), \
whatsThis ); \
AddRicfCapabilityToField( field, keyword )
@@ -54,7 +55,7 @@ public:
keyword, \
uiName, \
iconResourceName, \
RicfCommandObject::pythonHelpString( toolTip, keyword ), \
caf::PdmPythonGenerator::pythonHelpString( toolTip, keyword ), \
whatsThis ); \
AddRicfCapabilityToField( field, keyword )
@@ -64,7 +65,7 @@ public:
default, \
uiName, \
iconResourceName, \
RicfCommandObject::pythonHelpString( toolTip, scriptKeyword ), \
caf::PdmPythonGenerator::pythonHelpString( toolTip, scriptKeyword ), \
whatsThis ); \
AddRicfCapabilityToField( field, scriptKeyword )
@@ -73,18 +74,10 @@ public:
keyword, \
uiName, \
iconResourceName, \
RicfCommandObject::pythonHelpString( toolTip, scriptKeyword ), \
caf::PdmPythonGenerator::pythonHelpString( toolTip, scriptKeyword ), \
whatsThis ); \
AddRicfCapabilityToField( field, scriptKeyword )
#define RICF_InitObject( uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitObject( uiName, iconResourceName, toolTip, whatsThis ); \
RicfObjectCapability::addCapabilityToObject( this, classKeyword(), whatsThis );
#define RICF_InitObjectWithScriptNameAndComment( uiName, iconResourceName, toolTip, whatsThis, scriptClassName, scriptComment ) \
CAF_PDM_InitObject( uiName, iconResourceName, toolTip, whatsThis ); \
RicfObjectCapability::addCapabilityToObject( this, scriptClassName, scriptComment );
#define RICF_HEADER_INIT \
CAF_CMD_HEADER_INIT; \
CAF_PDM_HEADER_INIT

View File

@@ -17,7 +17,6 @@
/////////////////////////////////////////////////////////////////////////////////
#include "RicfFieldCapability.h"
#include "RicfMessages.h"
#include "RiaColorTools.h"
@@ -26,9 +25,9 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldReader<QString>::readFieldData( QString& fieldValue,
void RicfFieldIOHandler<QString>::writeToField( QString& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted )
{
fieldValue = "";
@@ -99,7 +98,10 @@ void RicfFieldReader<QString>::readFieldData( QString& fieldValue,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldWriter<QString>::writeFieldData( const QString& fieldValue, QTextStream& outputStream, bool quoteStrings )
void RicfFieldIOHandler<QString>::readFromField( const QString& fieldValue,
QTextStream& outputStream,
bool quoteStrings,
bool quoteNonBuiltin )
{
outputStream << "\"";
for ( int i = 0; i < fieldValue.size(); ++i )
@@ -116,9 +118,9 @@ void RicfFieldWriter<QString>::writeFieldData( const QString& fieldValue, QTextS
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldReader<bool>::readFieldData( bool& fieldValue,
void RicfFieldIOHandler<bool>::writeToField( bool& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted )
{
errorMessageContainer->skipWhiteSpaceWithLineNumberCount( inputStream );
@@ -155,7 +157,10 @@ void RicfFieldReader<bool>::readFieldData( bool& fieldValue,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldWriter<bool>::writeFieldData( const bool& fieldValue, QTextStream& outputStream, bool quoteStrings )
void RicfFieldIOHandler<bool>::readFromField( const bool& fieldValue,
QTextStream& outputStream,
bool quoteStrings,
bool quoteNonBuiltin )
{
// Lower-case true/false is used in the documentation.
outputStream << ( fieldValue ? "true" : "false" );
@@ -164,13 +169,13 @@ void RicfFieldWriter<bool>::writeFieldData( const bool& fieldValue, QTextStream&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldReader<cvf::Color3f>::readFieldData( cvf::Color3f& fieldValue,
void RicfFieldIOHandler<cvf::Color3f>::writeToField( cvf::Color3f& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted )
{
QString fieldStringValue;
RicfFieldReader<QString>::readFieldData( fieldStringValue, inputStream, errorMessageContainer, stringsAreQuoted );
RicfFieldIOHandler<QString>::writeToField( fieldStringValue, inputStream, errorMessageContainer, stringsAreQuoted );
QColor qColor( fieldStringValue );
if ( qColor.isValid() )
@@ -182,9 +187,12 @@ void RicfFieldReader<cvf::Color3f>::readFieldData( cvf::Color3f& fieldValue,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfFieldWriter<cvf::Color3f>::writeFieldData( const cvf::Color3f& fieldValue, QTextStream& outputStream, bool quoteStrings )
void RicfFieldIOHandler<cvf::Color3f>::readFromField( const cvf::Color3f& fieldValue,
QTextStream& outputStream,
bool quoteStrings,
bool quoteNonBuiltin )
{
QColor qColor = RiaColorTools::toQColor( fieldValue );
QString fieldStringValue = qColor.name();
RicfFieldWriter<QString>::writeFieldData( fieldStringValue, outputStream, quoteStrings );
RicfFieldIOHandler<QString>::readFromField( fieldStringValue, outputStream, quoteStrings );
}

View File

@@ -19,9 +19,9 @@
#pragma once
#include "RicfFieldHandle.h"
#include "RicfMessages.h"
#include "cafAppEnum.h"
#include "cafPdmScriptIOMessages.h"
#include "cvfColor3.h"
@@ -29,11 +29,11 @@
#include <QTextStream>
template <typename DataType>
struct RicfFieldReader
struct RicfFieldIOHandler
{
static void readFieldData( DataType& fieldValue,
static void writeToField( DataType& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true )
{
inputStream >> fieldValue;
@@ -46,68 +46,61 @@ struct RicfFieldReader
inputStream.setStatus( QTextStream::Ok );
}
}
};
template <typename DataType>
struct RicfFieldWriter
{
static void writeFieldData( const DataType& fieldValue, QTextStream& outputStream, bool quoteStrings = true )
static void readFromField( const DataType& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false )
{
outputStream << fieldValue;
}
};
template <>
struct RicfFieldReader<QString>
struct RicfFieldIOHandler<QString>
{
static void readFieldData( QString& fieldValue,
static void writeToField( QString& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true );
static void readFromField( const QString& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false );
};
template <>
struct RicfFieldWriter<QString>
struct RicfFieldIOHandler<bool>
{
static void writeFieldData( const QString& fieldValue, QTextStream& outputStream, bool quoteStrings = true );
};
template <>
struct RicfFieldReader<bool>
{
static void readFieldData( bool& fieldValue,
static void writeToField( bool& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true );
static void readFromField( const bool& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false );
};
template <>
struct RicfFieldWriter<bool>
struct RicfFieldIOHandler<cvf::Color3f>
{
static void writeFieldData( const bool& fieldValue, QTextStream& outputStream, bool quoteStrings = true );
};
template <>
struct RicfFieldReader<cvf::Color3f>
{
static void readFieldData( cvf::Color3f& fieldValue,
static void writeToField( cvf::Color3f& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true );
};
template <>
struct RicfFieldWriter<cvf::Color3f>
{
static void writeFieldData( const cvf::Color3f& fieldValue, QTextStream& outputStream, bool quoteStrings = true );
static void readFromField( const cvf::Color3f& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false );
};
template <typename T>
struct RicfFieldReader<caf::AppEnum<T>>
struct RicfFieldIOHandler<caf::AppEnum<T>>
{
static void readFieldData( caf::AppEnum<T>& fieldValue,
static void writeToField( caf::AppEnum<T>& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true )
{
errorMessageContainer->skipWhiteSpaceWithLineNumberCount( inputStream );
@@ -136,23 +129,29 @@ struct RicfFieldReader<caf::AppEnum<T>>
errorMessageContainer->currentCommand + "\"" );
}
}
};
template <typename T>
struct RicfFieldWriter<caf::AppEnum<T>>
{
static void writeFieldData( const caf::AppEnum<T>& fieldValue, QTextStream& outputStream, bool quoteStrings = true )
static void readFromField( const caf::AppEnum<T>& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false )
{
if ( quoteNonBuiltins )
{
outputStream << "\"" << fieldValue << "\"";
}
else
{
outputStream << fieldValue;
}
}
};
template <typename T>
struct RicfFieldReader<std::vector<T>>
struct RicfFieldIOHandler<std::vector<T>>
{
static void readFieldData( std::vector<T>& fieldValue,
static void writeToField( std::vector<T>& fieldValue,
QTextStream& inputStream,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true )
{
errorMessageContainer->skipWhiteSpaceWithLineNumberCount( inputStream );
@@ -175,7 +174,7 @@ struct RicfFieldReader<std::vector<T>>
}
T value;
RicfFieldReader<T>::readFieldData( value, inputStream, errorMessageContainer, true );
RicfFieldIOHandler<T>::writeToField( value, inputStream, errorMessageContainer, true );
fieldValue.push_back( value );
}
}
@@ -186,17 +185,16 @@ struct RicfFieldReader<std::vector<T>>
errorMessageContainer->currentCommand + "\"" );
}
}
};
template <typename T>
struct RicfFieldWriter<std::vector<T>>
{
static void writeFieldData( const std::vector<T>& fieldValue, QTextStream& outputStream, bool quoteStrings = true )
static void readFromField( const std::vector<T>& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false )
{
outputStream << "[";
for ( size_t i = 0; i < fieldValue.size(); ++i )
{
RicfFieldWriter<T>::writeFieldData( fieldValue[i], outputStream );
RicfFieldIOHandler<T>::readFromField( fieldValue[i], outputStream, quoteNonBuiltins );
if ( i < fieldValue.size() - 1 )
{
outputStream << ", ";
@@ -223,13 +221,13 @@ public:
// Xml Serializing
public:
void readFieldData( QTextStream& inputStream,
void writeToField( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
RicfMessages* errorMessageContainer,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true ) override
{
typename FieldType::FieldDataType value;
RicfFieldReader<typename FieldType::FieldDataType>::readFieldData( value,
RicfFieldIOHandler<typename FieldType::FieldDataType>::writeToField( value,
inputStream,
errorMessageContainer,
stringsAreQuoted );
@@ -240,9 +238,12 @@ public:
}
}
void writeFieldData( QTextStream& outputStream, bool quoteStrings = true ) const override
void readFromField( QTextStream& outputStream, bool quoteStrings = true, bool quoteNonBuiltins = false ) const override
{
RicfFieldWriter<typename FieldType::FieldDataType>::writeFieldData( m_field->value(), outputStream, quoteStrings );
RicfFieldIOHandler<typename FieldType::FieldDataType>::readFromField( m_field->value(),
outputStream,
quoteStrings,
quoteNonBuiltins );
}
private:

View File

@@ -22,12 +22,9 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RicfFieldHandle::RicfFieldHandle( caf::PdmFieldHandle* owner, const QString& fieldName, bool giveOwnership )
RicfFieldHandle::RicfFieldHandle( caf::PdmFieldHandle* owner, const QString& scriptFieldName, bool giveOwnership )
: caf::PdmFieldScriptability( owner, scriptFieldName, giveOwnership )
{
m_IOWriteable = true;
m_owner = owner;
m_fieldName = fieldName;
owner->addCapability( this, giveOwnership );
}
//--------------------------------------------------------------------------------------------------
@@ -36,11 +33,3 @@ RicfFieldHandle::RicfFieldHandle( caf::PdmFieldHandle* owner, const QString& fie
RicfFieldHandle::~RicfFieldHandle()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
const QString& RicfFieldHandle::fieldName() const
{
return m_fieldName;
}

View File

@@ -17,7 +17,7 @@
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "cafPdmFieldCapability.h"
#include "cafPdmFieldScriptability.h"
#include <QString>
@@ -25,10 +25,9 @@ namespace caf
{
class PdmObjectFactory;
class PdmFieldHandle;
class PdmScriptIOMessages;
} // namespace caf
class RicfMessages;
class QTextStream;
//==================================================================================================
@@ -36,24 +35,12 @@ class QTextStream;
//
//
//==================================================================================================
class RicfFieldHandle : public caf::PdmFieldCapability
class RicfFieldHandle : public caf::PdmFieldScriptability
{
public:
RicfFieldHandle( caf::PdmFieldHandle* owner, const QString& fieldName, bool giveOwnership );
RicfFieldHandle( caf::PdmFieldHandle* owner, const QString& scriptFieldName, bool giveOwnership );
~RicfFieldHandle() override;
const QString& fieldName() const;
bool isIOWriteable() const { return m_IOWriteable; }
void setIOWriteable( bool writeable ) { m_IOWriteable = writeable; }
virtual void readFieldData( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
RicfMessages* errorMessageContainer,
bool stringsAreQuoted = true ) = 0;
virtual void writeFieldData( QTextStream& outputStream, bool quoteStrings = true ) const = 0;
private:
caf::PdmFieldHandle* m_owner;
QString m_fieldName;

View File

@@ -1,90 +0,0 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RicfMessages.h"
#include <QTextStream>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfMessages::addWarning( const QString& message )
{
m_messages.push_back(
std::make_pair( MESSAGE_WARNING, "Line " + QString::number( m_currentLineNumber ) + ": " + message ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfMessages::addError( const QString& message )
{
m_messages.push_back(
std::make_pair( MESSAGE_ERROR, "Line " + QString::number( m_currentLineNumber ) + ": " + message ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfMessages::skipWhiteSpaceWithLineNumberCount( QTextStream& inputStream )
{
while ( !inputStream.atEnd() )
{
QChar ch = readCharWithLineNumberCount( inputStream );
if ( !ch.isSpace() )
{
inputStream.seek( inputStream.pos() - 1 );
break;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QChar RicfMessages::readCharWithLineNumberCount( QTextStream& inputStream )
{
QChar ch;
inputStream >> ch;
if ( ch == QChar( '\n' ) )
{
m_currentLineNumber++;
}
return ch;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QChar RicfMessages::peekNextChar( QTextStream& inputStream )
{
QChar ch;
if ( !inputStream.atEnd() )
{
inputStream >> ch;
inputStream.seek( inputStream.pos() - 1 );
}
return ch;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfMessages::skipLineWithLineNumberCount( QTextStream& inputStream )
{
inputStream.readLine();
m_currentLineNumber++;
}

View File

@@ -1,54 +0,0 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <QString>
#include <vector>
class QTextStream;
class RicfMessages
{
public:
RicfMessages()
: m_currentLineNumber( 1 )
{
}
enum MessageType
{
MESSAGE_WARNING,
MESSAGE_ERROR
};
void addWarning( const QString& message );
void addError( const QString& message );
void skipWhiteSpaceWithLineNumberCount( QTextStream& inputStream );
void skipLineWithLineNumberCount( QTextStream& inputStream );
QChar readCharWithLineNumberCount( QTextStream& inputStream );
QChar peekNextChar( QTextStream& inputStream );
QString currentCommand;
QString currentArgument;
std::vector<std::pair<MessageType, QString>> m_messages;
private:
int m_currentLineNumber;
};

View File

@@ -18,18 +18,14 @@
#include "RicfObjectCapability.h"
#include "RicfFieldHandle.h"
#include "RicfMessages.h"
#include "cafPdmObject.h"
#include "cafPdmObjectHandle.h"
#include "cafPdmScriptIOMessages.h"
#include "cafPdmXmlFieldHandle.h"
#include <QTextStream>
std::map<QString, QString> RicfObjectCapability::s_classKeywordToScriptClassName;
std::map<QString, QString> RicfObjectCapability::s_scriptClassNameToClassKeyword;
std::map<QString, QString> RicfObjectCapability::s_scriptClassComments;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -51,7 +47,7 @@ RicfObjectCapability::~RicfObjectCapability()
//--------------------------------------------------------------------------------------------------
void RicfObjectCapability::readFields( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
RicfMessages* errorMessageContainer )
caf::PdmScriptIOMessages* errorMessageContainer )
{
std::set<QString> readFields;
bool isLastArgumentRead = false;
@@ -140,7 +136,7 @@ void RicfObjectCapability::readFields( QTextStream& inputStream,
if ( xmlFieldHandle->isIOReadable() )
{
errorMessageContainer->currentArgument = keyword;
rcfField->readFieldData( inputStream, objectFactory, errorMessageContainer );
rcfField->writeToField( inputStream, objectFactory, errorMessageContainer );
errorMessageContainer->currentArgument = keyword;
}
}
@@ -217,82 +213,9 @@ void RicfObjectCapability::writeFields( QTextStream& outputStream ) const
}
outputStream << keyword << " = ";
rcfField->writeFieldData( outputStream );
rcfField->readFromField( outputStream );
writtenFieldCount++;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfObjectCapability::registerScriptClassNameAndComment( const QString& classKeyword,
const QString& scriptClassName,
const QString& scriptClassComment )
{
s_classKeywordToScriptClassName[classKeyword] = scriptClassName;
s_scriptClassNameToClassKeyword[scriptClassName] = classKeyword;
s_scriptClassComments[classKeyword] = scriptClassComment;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RicfObjectCapability::scriptClassNameFromClassKeyword( const QString& classKeyword )
{
auto it = s_classKeywordToScriptClassName.find( classKeyword );
if ( it != s_classKeywordToScriptClassName.end() )
{
return it->second;
}
return classKeyword;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RicfObjectCapability::classKeywordFromScriptClassName( const QString& scriptClassName )
{
auto it = s_scriptClassNameToClassKeyword.find( scriptClassName );
if ( it != s_scriptClassNameToClassKeyword.end() )
{
return it->second;
}
return scriptClassName;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RicfObjectCapability::scriptClassComment( const QString& classKeyword )
{
auto it = s_scriptClassComments.find( classKeyword );
if ( it != s_scriptClassComments.end() )
{
return it->second;
}
return "";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RicfObjectCapability::isScriptable( const caf::PdmObject* object )
{
return s_classKeywordToScriptClassName.find( object->classKeyword() ) != s_classKeywordToScriptClassName.end();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicfObjectCapability::addCapabilityToObject( caf::PdmObject* object,
const QString& scriptClassName,
const QString& scriptClassComment )
{
if ( !object->capability<RicfObjectCapability>() )
{
new RicfObjectCapability( object, true );
}
RicfObjectCapability::registerScriptClassNameAndComment( object->classKeyword(), scriptClassName, scriptClassComment );
}

View File

@@ -28,10 +28,10 @@ namespace caf
class PdmObject;
class PdmObjectHandle;
class PdmObjectFactory;
class PdmScriptIOMessages;
} // namespace caf
class QTextStream;
class RicfMessages;
//==================================================================================================
//
@@ -45,24 +45,11 @@ public:
~RicfObjectCapability() override;
void readFields( QTextStream& inputStream, caf::PdmObjectFactory* objectFactory, RicfMessages* errorMessageContainer );
void readFields( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
caf::PdmScriptIOMessages* errorMessageContainer );
void writeFields( QTextStream& outputStream ) const;
static void registerScriptClassNameAndComment( const QString& classKeyword,
const QString& scriptClassName,
const QString& scriptClassComment );
static QString scriptClassNameFromClassKeyword( const QString& classKeyword );
static QString classKeywordFromScriptClassName( const QString& scriptClassName );
static QString scriptClassComment( const QString& classKeyword );
static bool isScriptable( const caf::PdmObject* object );
static void
addCapabilityToObject( caf::PdmObject* object, const QString& scriptClassName, const QString& scriptClassComment );
private:
caf::PdmObjectHandle* m_owner;
static std::map<QString, QString> s_classKeywordToScriptClassName;
static std::map<QString, QString> s_scriptClassNameToClassKeyword;
static std::map<QString, QString> s_scriptClassComments;
};

View File

@@ -19,10 +19,10 @@
#include "RifcCommandFileReader.h"
#include "RicfCommandObject.h"
#include "RicfMessages.h"
#include "RicfObjectCapability.h"
#include "cafPdmObjectFactory.h"
#include "cafPdmScriptIOMessages.h"
#include <QTextStream>
@@ -31,7 +31,7 @@
//--------------------------------------------------------------------------------------------------
std::vector<RicfCommandObject*> RicfCommandFileReader::readCommands( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
RicfMessages* errorMessageContainer )
caf::PdmScriptIOMessages* errorMessageContainer )
{
std::vector<RicfCommandObject*> readCommands;

View File

@@ -26,9 +26,8 @@ class QTextStream;
namespace caf
{
class PdmObjectFactory;
}
class RicfMessages;
class PdmScriptIOMessages;
} // namespace caf
//==================================================================================================
//
@@ -40,7 +39,7 @@ class RicfCommandFileReader
public:
static std::vector<RicfCommandObject*> readCommands( QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
RicfMessages* errorMessageContainer );
caf::PdmScriptIOMessages* errorMessageContainer );
static void writeCommands( QTextStream& outputStream, const std::vector<RicfCommandObject*>& commandsToWrite );
};

View File

@@ -61,7 +61,7 @@ RicfCommandFileExecutor::~RicfCommandFileExecutor()
//--------------------------------------------------------------------------------------------------
void RicfCommandFileExecutor::executeCommands( QTextStream& stream )
{
RicfMessages messages;
caf::PdmScriptIOMessages messages;
std::vector<RicfCommandObject*> executableCommands;
{
clearCachedData();
@@ -70,7 +70,7 @@ void RicfCommandFileExecutor::executeCommands( QTextStream& stream )
RicfCommandFileReader::readCommands( stream, caf::PdmDefaultObjectFactory::instance(), &messages );
for ( auto message : messages.m_messages )
{
if ( message.first == RicfMessages::MESSAGE_WARNING )
if ( message.first == caf::PdmScriptIOMessages::MESSAGE_WARNING )
{
RiaLogging::warning( QString( "Command file parsing warning: %1" ).arg( message.second ) );
}

View File

@@ -18,9 +18,8 @@
#pragma once
#include "RicfMessages.h"
#include "cafAppEnum.h"
#include "cafPdmScriptIOMessages.h"
#include <map>
#include <vector>

View File

@@ -27,6 +27,7 @@
#include "RimMultiPlot.h"
#include "RimPlotWindow.h"
#include "RimWellLogPlot.h"
#include "RimWellLogTrack.h"
#include "cafSelectionManager.h"
@@ -51,8 +52,10 @@ bool RicDeleteSubPlotFeature::isCommandEnabled()
for ( caf::PdmObject* object : selection )
{
RimMultiPlot* multiPlot = nullptr;
RimWellLogPlot* wellLogPlot = nullptr;
object->firstAncestorOrThisOfType( multiPlot );
if ( dynamic_cast<RimPlotWindow*>( object ) && multiPlot )
object->firstAncestorOrThisOfType( wellLogPlot );
if ( dynamic_cast<RimPlotWindow*>( object ) && ( multiPlot || wellLogPlot ) )
{
plotsSelected++;
}
@@ -72,26 +75,34 @@ void RicDeleteSubPlotFeature::onActionTriggered( bool isChecked )
std::vector<RimPlot*> selection;
caf::SelectionManager::instance()->objectsByType( &selection );
std::set<RimMultiPlot*> alteredPlotWindows;
std::set<RimPlotWindow*> alteredPlotWindows;
for ( RimPlot* plot : selection )
{
RimMultiPlot* plotWindow = nullptr;
plot->firstAncestorOrThisOfType( plotWindow );
if ( plot && plotWindow )
if ( !plot ) continue;
RimMultiPlot* multiPlot = nullptr;
RimWellLogPlot* wellLogPlot = nullptr;
plot->firstAncestorOrThisOfType( multiPlot );
plot->firstAncestorOrThisOfType( wellLogPlot );
if ( multiPlot )
{
alteredPlotWindows.insert( plotWindow );
plotWindow->removePlot( plot );
alteredPlotWindows.insert( multiPlot );
multiPlot->removePlot( plot );
caf::SelectionManager::instance()->removeObjectFromAllSelections( plot );
plotWindow->updateConnectedEditors();
multiPlot->updateConnectedEditors();
delete plot;
}
}
for ( RimMultiPlot* plotWindow : alteredPlotWindows )
else if ( wellLogPlot )
{
plotWindow->uiCapability()->updateConnectedEditors();
alteredPlotWindows.insert( wellLogPlot );
wellLogPlot->removePlot( plot );
caf::SelectionManager::instance()->removeObjectFromAllSelections( plot );
wellLogPlot->updateConnectedEditors();
delete plot;
}
}
}

View File

@@ -78,6 +78,7 @@ RimWellBoreStabilityPlot*
RimWellBoreStabilityPlot* plot =
RicNewWellLogPlotFeatureImpl::createWellBoreStabilityPlot( false, "Well Bore Stability", parameters );
plot->setCaseWellPathAndTimeStep( geoMechCase, wellPath, timeStep );
{
auto task = progInfo.task( "Creating formation track", 2 );

View File

@@ -385,8 +385,8 @@ bool RifEclipseInputFileTools::exportGrid( const QString& fileName,
}
// Do not perform the transformation (applyMapaxes == false):
// The coordinates have been transformed to the mapaxes coordinate system already.
// However, send the mapaxes data in to libecl so that the coordinate system description is saved.
// The coordinates have been transformed to the map axes coordinate system already.
// However, send the map axes data in to libecl so that the coordinate system description is saved.
bool applyMapaxes = false;
ecl_grid_type* mainEclGrid = ecl_grid_alloc_GRID_data( (int)ecl_coords.size(),
ecl_nx,
@@ -473,6 +473,12 @@ bool RifEclipseInputFileTools::exportKeywords( const QString& resul
CVF_ASSERT( !resultValues.empty() );
if ( resultValues.empty() ) continue;
double defaultExportValue = 0.0;
if ( keyword.endsWith( "NUM" ) )
{
defaultExportValue = 1.0;
}
std::vector<double> filteredResults;
filteredResults.reserve( resultValues.size() );
@@ -493,6 +499,10 @@ bool RifEclipseInputFileTools::exportKeywords( const QString& resul
{
filteredResults.push_back( resultValues[resIndex] );
}
else
{
filteredResults.push_back( defaultExportValue );
}
}
}
}

View File

@@ -83,6 +83,7 @@ RifEclipseSummaryAddress::RifEclipseSummaryAddress( SummaryVarCategory
case SUMMARY_WELL_SEGMENT:
m_wellName = identifiers[INPUT_WELL_NAME];
m_wellSegmentNumber = RiaStdStringTools::toInt( identifiers[INPUT_SEGMENT_NUMBER] );
break;
case SUMMARY_BLOCK:
ijkTuple = ijkTupleFromUiText( identifiers[INPUT_CELL_IJK] );
m_cellI = std::get<0>( ijkTuple );

View File

@@ -182,15 +182,13 @@ if (RESINSIGHT_GRPC_PYTHON_EXECUTABLE)
"rips/contour_map.py"
"rips/grid.py"
"rips/gridcasegroup.py"
"rips/project.py"
"rips/instance.py"
"rips/pdmobject.py"
"rips/plot.py"
"rips/project.py"
"rips/simulation_well.py"
"rips/view.py"
"rips/wellpath.py"
"rips/well_log_plot.py"
"rips/well_bore_stability_plot.py"
"rips/PythonExamples/instance_example.py"
"rips/PythonExamples/command_example.py"
"rips/PythonExamples/case_grid_group.py"

View File

@@ -11,6 +11,8 @@ service PdmObjectService
rpc GetAncestorPdmObject(PdmParentObjectRequest) returns (PdmObject) {}
rpc CreateChildPdmObject(CreatePdmChildObjectRequest) returns (PdmObject) {}
rpc UpdateExistingPdmObject(PdmObject) returns (Empty) {}
rpc CallPdmObjectGetMethod(PdmObjectMethodRequest) returns (stream PdmObjectGetMethodReply) {}
rpc CallPdmObjectSetMethod(stream PdmObjectSetMethodChunk) returns (ClientToServerStreamReply) {}
}
message PdmDescendantObjectRequest
@@ -49,3 +51,52 @@ message PdmObjectArray
{
repeated PdmObject objects = 1;
}
message PdmObjectMethodRequest
{
PdmObject object = 1;
string method = 2;
}
message PdmObjectSetMethodRequest
{
PdmObjectMethodRequest request = 1;
int32 data_count = 2;
}
message PdmObjectSetMethodChunk
{
oneof data
{
PdmObjectSetMethodRequest set_request = 1;
DoubleArray doubles = 2;
IntArray ints = 3;
StringArray strings = 4;
}
}
message DoubleArray
{
repeated double data = 1;
}
message IntArray
{
repeated int32 data = 1;
}
message StringArray
{
repeated string data = 1;
}
message PdmObjectGetMethodReply
{
oneof data
{
DoubleArray doubles = 1;
IntArray ints = 2;
StringArray strings = 3;
}
}

View File

@@ -16,7 +16,7 @@ if resinsight is not None:
for case in cases:
print("Case id: " + str(case.id))
print("Case name: " + case.name)
print("Case type: " + case.class_keyword)
print("Case type: " + case.__class__.__name__)
print("Case file name: " + case.file_path)
print("Case reservoir bounding box:", case.reservoir_boundingbox())

View File

@@ -0,0 +1,28 @@
# Load ResInsight Processing Server Client Library
import rips
# Connect to ResInsight instance
resinsight = rips.Instance.find()
# Get the project
project = resinsight.project
# Find all the well bore stability plots in the project
wbsplots = project.descendants(rips.WellBoreStabilityPlot)
# Chose a sensible output folder
dirname = "C:/temp"
# Loop through all Well Bore Stability plots
for wbsplot in wbsplots:
# Set depth type a parameter and export snapshot
wbsplot.depth_type = "TRUE_VERTICAL_DEPTH_RKB"
# Example of setting parameters for existing plots
params = wbsplot.parameters()
params.user_poisson_ratio = 0.12345
params.update()
wbsplot.update()
wbsplot.export_snapshot(export_folder=dirname)

View File

@@ -0,0 +1,17 @@
######################################################################
# This script retrieves cell result data and alters it
######################################################################
import rips
resinsight = rips.Instance.find()
view = resinsight.project.views()[0]
results = view.cell_result_data()
print ("Number of result values: ", len(results))
newresults = []
for i in range(0, len(results)):
newresults.append(results[i] * -1.0)
view.set_cell_result_data(newresults)

View File

@@ -6,60 +6,38 @@ import rips
# Connect to ResInsight instance
resInsight = rips.Instance.find()
cases = resInsight.project.cases()
well_paths = resInsight.project.import_well_paths(well_path_folder='D:/Projects/ResInsight-regression-test/ModelData/Norne_WellPaths')
well_log_files = resInsight.project.import_well_log_files(well_log_folder='D:/Projects/ResInsight-regression-test/ModelData/Norne_PLT_LAS')
# Get all GeoMech cases
cases = resInsight.project.descendants(rips.GeoMechCase)
# Get all well paths
well_paths = resInsight.project.well_paths()
# Ensure there's at least one well path
if len(well_paths) < 1:
print("No well paths in project")
exit(1)
well_paths = well_paths[0:4]
print(well_paths)
# Example of creating parameters for new plots
wbs_parameters = rips.WbsParameters()
wbs_parameters.user_poisson_ratio = 0.412347
wbs_parameters.pore_pressure_outside_reservoir_source = "USER_DEFINED"
wbs_parameters.user_pp_outside_reservoir = 1.1
wbs_parameters.fg_shale_source = "PROPORTIONAL_TO_SH"
wbs_parameters.user_fg_shale = 1.13
# Create a set of WbsParameters
params = rips.WbsParameters()
params.user_poisson_ratio = 0.23456
params.user_ucs = 123
# Loop through all cases
for case in cases:
if case.type == "GeoMechCase":
assert(isinstance(case, rips.GeoMechCase))
min_res_depth, max_res_depth = case.reservoir_depth_range()
print (case.id)
# Find a good output path
case_path = case.file_path
folder_name = os.path.dirname(case_path)
# Import formation names
case.import_formation_names(formation_files=['D:/Projects/ResInsight-regression-test/ModelData/norne/Norne_ATW2013.lyr'])
# create a folder to hold the snapshots
dirname = os.path.join(folder_name, 'snapshots')
print("Exporting to: " + dirname)
for well_path in well_paths:
try:
for well_path in well_paths[0:4]: # Loop through the first five well paths
# Create plot with parameters
wbsplot = case.create_well_bore_stability_plot(well_path=well_path.name, time_step=0, wbs_parameters=wbs_parameters)
# Example of setting parameters for existing plots
replace_params = wbsplot.parameters()
replace_params.user_poisson_ratio = 0.654321
replace_params.user_fg_shale = 1.0321
wbsplot.set_parameters(replace_params)
# Demonstrate altering general well log plot settings
min_depth = max(wbsplot.minimum_depth, min_res_depth)
max_depth = min(wbsplot.maximum_depth, max_res_depth)
wbsplot.minimum_depth = min_depth
wbsplot.maximum_depth = max_depth
wbsplot.update()
#wbsplot.depth_type = "TRUE_VERTICAL_DEPTH_RKB"
wbsplot.export_snapshot(export_folder=dirname)
except grpc.RpcError as e:
print("Error: ", e.details())
wbsplot = case.create_well_bore_stability_plot(well_path=well_path.name, time_step=0, parameters=params)

View File

@@ -15,7 +15,6 @@ print("Exporting to: " + export_folder)
for plot in plots:
plot.export_snapshot(export_folder=export_folder)
plot.export_snapshot(export_folder=export_folder, output_format='PDF')
well_log_plot = plot.cast(rips.WellLogPlot)
if well_log_plot is not None:
well_log_plot.export_data_as_las(export_folder=export_folder)
well_log_plot.export_data_as_ascii(export_folder=export_folder)
if isinstance(plot, rips.WellLogPlot):
plot.export_data_as_las(export_folder=export_folder)
plot.export_data_as_ascii(export_folder=export_folder)

View File

@@ -8,4 +8,4 @@ cases = resinsight.project.cases()
print ("Got " + str(len(cases)) + " cases: ")
for case in cases:
print("Case name: " + case.name)
print("Case grid path: " + case.grid_path())
print("Case grid path: " + case.file_path)

View File

@@ -13,6 +13,6 @@ from rips.project import Project
from rips.plot import Plot, PlotWindow
from rips.contour_map import EclipseContourMap, GeoMechContourMap
from rips.well_log_plot import WellLogPlot
from rips.well_bore_stability_plot import WellBoreStabilityPlot, WbsParameters
from rips.simulation_well import SimulationWell
from rips.wellpath import WellPathBase
from rips.generated.pdm_objects import *

View File

@@ -26,7 +26,7 @@ import rips.project
from rips.grid import Grid
from rips.pdmobject import add_method, PdmObject
from rips.view import View
from rips.well_bore_stability_plot import WellBoreStabilityPlot, WbsParameters
from rips.generated.pdm_objects import WellBoreStabilityPlot, WbsParameters
from rips.simulation_well import SimulationWell
"""ResInsight case class
@@ -245,11 +245,6 @@ def days_since_start(self):
"""Get a list of decimal values representing days since the start of the simulation"""
return self.__case_stub.GetDaysSinceStart(self.__request()).day_decimals
@add_method(Case)
def views(self):
"""Get a list of views belonging to a case"""
return self.descendants(View)
@add_method(Case)
def view(self, view_id):
"""Get a particular view belonging to a case by providing view id
@@ -826,7 +821,7 @@ def export_property(
))
@add_method(Case)
def create_well_bore_stability_plot(self, well_path, time_step, wbs_parameters=None):
def create_well_bore_stability_plot(self, well_path, time_step, parameters=None):
""" Create a new well bore stability plot
Arguments:
@@ -837,9 +832,9 @@ def create_well_bore_stability_plot(self, well_path, time_step, wbs_parameters=N
A new plot object
"""
pb2_parameters = None
if wbs_parameters is not None:
assert(isinstance(wbs_parameters, WbsParameters))
pb2_parameters = wbs_parameters.pb2_object()
if parameters is not None:
assert(isinstance(parameters, WbsParameters))
pb2_parameters = parameters.pb2_object()
plot_result = self._execute_command(createWellBoreStabilityPlot=Cmd.CreateWbsPlotRequest(caseId=self.id,
wellPath=well_path,
@@ -847,8 +842,7 @@ def create_well_bore_stability_plot(self, well_path, time_step, wbs_parameters=N
wbsParameters=pb2_parameters))
project = self.ancestor(rips.project.Project)
plot = project.plot(view_id=plot_result.createWbsPlotResult.viewId)
assert(plot)
return plot.cast(WellBoreStabilityPlot)
return plot
@add_method(Case)
def import_formation_names(self, formation_files=None):

View File

@@ -21,6 +21,9 @@ def camel_to_snake(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def snake_to_camel(name):
return ''.join(word.title() for word in name.split('_'))
def add_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
@@ -51,24 +54,26 @@ def _execute_command(self, **command_params):
@add_method(PdmObject)
def __custom_init__(self, pb2_object, channel):
self.__warnings = []
self.__keyword_translation = {}
self.__chunk_size = 8160
if pb2_object is not None:
self._pb2_object = pb2_object
else:
self._pb2_object = PdmObject_pb2.PdmObject(class_keyword=self.__class__.__name__)
self.class_keyword = self._pb2_object.class_keyword
self._channel = channel
if self.pb2_object() is not None and self.channel() is not None:
if self.channel() is not None:
self._pdm_object_stub = PdmObject_pb2_grpc.PdmObjectServiceStub(self.channel())
self._commands = CmdRpc.CommandsStub(self.channel())
# Create stubs
if self._channel:
self._pdm_object_stub = PdmObject_pb2_grpc.PdmObjectServiceStub(self._channel)
self._commands = CmdRpc.CommandsStub(self._channel)
if pb2_object is not None:
# Copy parameters from ResInsight
assert(not isinstance(pb2_object, PdmObject))
self._pb2_object = pb2_object
for camel_keyword in self._pb2_object.parameters:
snake_keyword = camel_to_snake(camel_keyword)
setattr(self, snake_keyword, self.__get_grpc_value(camel_keyword))
self.__keyword_translation[snake_keyword] = camel_keyword
else:
# Copy parameters from PdmObject defaults
self._pb2_object = PdmObject_pb2.PdmObject(class_keyword=self.__class__.__name__)
self.__copy_to_pb2()
@add_method(PdmObject)
def copy_from(self, object):
@@ -82,16 +87,27 @@ def copy_from(self, object):
setattr(self, attribute, value)
if self.__custom_init__ is not None:
self.__custom_init__(self._pb2_object, self._channel)
self.update()
@add_method(PdmObject)
def warnings(self):
return self.__warnings
@add_method(PdmObject)
def has_warnings(self):
return len(self.__warnings) > 0
@add_method(PdmObject)
def __copy_to_pb2(self):
if self._pb2_object is not None:
for snake_kw in dir(self):
if not snake_kw.startswith('_'):
value = getattr(self, snake_kw)
# This is crucial to avoid overwriting methods
if not callable(value):
camel_kw = snake_to_camel(snake_kw)
self.__set_grpc_value(camel_kw, value)
@add_method(PdmObject)
def pb2_object(self):
""" Private method"""
@@ -125,15 +141,17 @@ def visible(self):
@add_method(PdmObject)
def print_object_info(self):
"""Print the structure and data content of the PdmObject"""
print("=========== " + self.class_keyword + " =================")
print("=========== " + self.__class__.__name__ + " =================")
print("Object Attributes: ")
for snake_kw, camel_kw in self.__keyword_translation.items():
for snake_kw in dir(self):
if not snake_kw.startswith("_") and not callable(getattr(self, snake_kw)):
camel_kw = snake_to_camel(snake_kw)
print(" " + snake_kw + " [" + type(getattr(self, snake_kw)).__name__ +
"]: " + str(getattr(self, snake_kw)))
print("Object Methods:")
for method in dir(self):
if not method.startswith("_") and callable(getattr(self, method)):
print (" " + method)
for snake_kw in dir(self):
if not snake_kw.startswith("_") and callable(getattr(self, snake_kw)):
print (" " + snake_kw)
@add_method(PdmObject)
def __convert_from_grpc_value(self, value):
@@ -281,13 +299,66 @@ def ancestor(self, class_definition):
return None
raise e
@add_method(PdmObject)
def _call_get_method_async(self, method_name):
request = PdmObject_pb2.PdmObjectMethodRequest(object=self._pb2_object, method=method_name)
for chunk in self._pdm_object_stub.CallPdmObjectGetMethod(request):
yield chunk
@add_method(PdmObject)
def _call_get_method(self, method_name):
all_values = []
generator = self._call_get_method_async(method_name)
for chunk in generator:
data = getattr(chunk, chunk.WhichOneof('data'))
for value in data.data:
all_values.append(value)
return all_values
@add_method(PdmObject)
def __generate_set_method_chunks(self, array, method_request):
index = -1
while index < len(array):
chunk = PdmObject_pb2.PdmObjectSetMethodChunk()
if index is -1:
chunk.set_request.CopyFrom(PdmObject_pb2.PdmObjectSetMethodRequest(request=method_request, data_count=len(array)))
index += 1
else:
actual_chunk_size = min(len(array) - index + 1, self.__chunk_size)
if isinstance(array[0], float):
chunk.CopyFrom(
PdmObject_pb2.PdmObjectSetMethodChunk(doubles=PdmObject_pb2.DoubleArray(data=array[index:index +
actual_chunk_size])))
elif isinstance(array[0], int):
chunk.CopyFrom(
PdmObject_pb2.PdmObjectSetMethodChunk(ints=PdmObject_pb2.IntArray(data=array[index:index +
actual_chunk_size])))
elif isinstance(array[0], str):
chunk.CopyFrom(
PdmObject_pb2.PdmObjectSetMethodChunk(strings=PdmObject_pb2.StringArray(data=array[index:index +
actual_chunk_size])))
else:
raise Exception("Wrong data type for set method")
index += actual_chunk_size
yield chunk
# Final empty message to signal completion
chunk = PdmObject_pb2.PdmObjectSetMethodChunk()
yield chunk
@add_method(PdmObject)
def _call_set_method(self, method_name, values):
method_request = PdmObject_pb2.PdmObjectMethodRequest(object=self._pb2_object, method=method_name)
request_iterator = self.__generate_set_method_chunks(values, method_request)
reply = self._pdm_object_stub.CallPdmObjectSetMethod(request_iterator)
if reply.accepted_value_count < len(values):
raise IndexError
@add_method(PdmObject)
def update(self):
"""Sync all fields from the Python Object to ResInsight"""
if self._pdm_object_stub is not None and self._pb2_object is not None:
for snake_kw, camel_kw in self.__keyword_translation.items():
self.__set_grpc_value(camel_kw, getattr(self, snake_kw))
self.__copy_to_pb2()
if self._pdm_object_stub is not None:
self._pdm_object_stub.UpdateExistingPdmObject(self._pb2_object)
else:
raise Exception("Object is not connected to GRPC service so cannot update ResInsight")

View File

@@ -11,14 +11,13 @@ from rips.gridcasegroup import GridCaseGroup
from rips.pdmobject import PdmObject, add_method, add_static_method
from rips.plot import Plot
from rips.view import View
from rips.wellpath import WellPathBase
import rips.generated.Commands_pb2 as Cmd
from rips.generated.Definitions_pb2 import Empty
import rips.generated.Project_pb2_grpc as Project_pb2_grpc
import rips.generated.Project_pb2 as Project_pb2
import rips.generated.PdmObject_pb2 as PdmObject_pb2
from rips.generated.pdm_objects import Project, PlotWindow
from rips.generated.pdm_objects import Project, PlotWindow, WellPath
@add_method(Project)
@@ -277,7 +276,7 @@ def import_well_paths(self, well_path_files=None, well_path_folder=''):
well_path_folder(str): A folder path containing files to import
Returns:
A list of WellPathBase objects
A list of WellPath objects
"""
if well_path_files is None:
well_path_files = []
@@ -294,16 +293,16 @@ def well_paths(self):
"""Get a list of all well paths in the project
Returns:
A list of rips WellPathBase objects
A list of rips WellPath objects
"""
return self.descendants(WellPathBase)
return self.descendants(WellPath)
@add_method(Project)
def well_path_by_name(self, well_path_name):
"""Get a specific well path by name from the project
Returns:
A WellPathBase object
A WellPath object
"""
all_well_paths = self.well_paths()
for well_path in all_well_paths:

View File

@@ -122,7 +122,7 @@ def test_PdmObject(rips_instance, initialize_test):
case = rips_instance.project.load_case(path=case_path)
assert(case.id == 0)
assert(case.address() is not 0)
assert(case.class_keyword == "EclipseCase")
assert(case.__class__.__name__ == "EclipseCase")
@pytest.mark.skipif(sys.platform.startswith('linux'), reason="Brugge is currently exceptionally slow on Linux")
def test_brugge_0010(rips_instance, initialize_test):

View File

@@ -9,19 +9,6 @@ import rips.case # Circular import of Case, which already imports View. Use ful
from rips.pdmobject import add_method
from rips.generated.pdm_objects import View, ViewWindow, EclipseView, GeoMechView
@add_method(View)
def is_eclipse_view(self):
return isinstance(self, EclipseView)
@add_method(View)
def is_geomech_view(self):
return isinstance(self, GeoMechView)
@add_method(View)
def cell_result(self):
"""Retrieve the current cell results"""
return self.children("GridCellResult")[0]
@add_method(View)
def apply_cell_result(self, result_type, result_variable):
"""Apply a regular cell result

View File

@@ -1,45 +0,0 @@
"""
ResInsight Well Bore Stability Plot module
"""
from rips.pdmobject import PdmObject, add_method
from rips.well_log_plot import WellLogPlot
from rips.generated.pdm_objects import WellBoreStabilityPlot, WbsParameters
@add_method(WbsParameters)
def __custom_init__(self, pb2_object=None, channel=None):
self.pore_pressure_reservoir_source = "UNDEFINED"
self.pore_pressure_non_reservoir_source = "UNDEFINED"
self.poisson_ratio_source = "UNDEFINED"
self.ucs_source = "UNDEFINED"
self.obg0_source = "UNDEFINED"
self.df_source = "UNDEFINED"
self.k0sh_source = "UNDEFINED"
self.fg_shale_source = "UNDEFINED"
self.k0fg_source = "UNDEFINED"
self.user_pp_non_reservoir = 1.05
self.user_poission_ratio = 0.35
self.user_ucs = 100
self.user_df = 0.7
self.user_k0sh = 0.65
self.fg_multiplier = 1.05
self.user_k0fg = 0.75
@add_method(WellBoreStabilityPlot)
def parameters(self):
"""Retrieve the parameters of the Plot
"""
children = self.children("WbsParameters", WbsParameters)
if len(children) == 1:
child = children[0]
return child
return None
@add_method(WellBoreStabilityPlot)
def set_parameters(self, wbs_parameters):
children = self.children("WbsParameters", WbsParameters)
if len(children) == 1:
pdm_params = children[0]
pdm_params.copy_from(wbs_parameters)

View File

@@ -1,6 +0,0 @@
"""
ResInsight Well
"""
import rips.generated.Commands_pb2 as Cmd
from rips.generated.pdm_objects import WellPathBase

View File

@@ -348,8 +348,8 @@ void RiaGrpcClientToServerStreamCallback<ServiceT, RequestT, ReplyT, StateHandle
}
else
{
CAF_ASSERT( m_stateHandler->streamedValueCount() <= m_stateHandler->cellCount() );
if ( m_stateHandler->streamedValueCount() == m_stateHandler->cellCount() )
CAF_ASSERT( m_stateHandler->streamedValueCount() <= m_stateHandler->totalValueCount() );
if ( m_stateHandler->streamedValueCount() == m_stateHandler->totalValueCount() )
{
this->setNextCallState( RiaGrpcCallbackInterface::FINISH_REQUEST );
m_reader.Finish( this->m_reply, grpc::Status::OK, this );

View File

@@ -337,7 +337,6 @@ grpc::Status RiaNNCInputValuesStateHandler::init( const NNCValuesInputRequest* r
{
auto caseData = m_eclipseCase->eclipseCaseData();
auto m_porosityModel = static_cast<RiaDefines::PorosityModelType>( request->porosity_model() );
auto resultData = caseData->results( m_porosityModel );
m_timeStep = request->time_step();
m_propertyName = QString::fromStdString( request->property_name() );
@@ -423,7 +422,7 @@ grpc::Status RiaNNCInputValuesStateHandler::receiveStreamRequest( const NNCValue
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RiaNNCInputValuesStateHandler::cellCount() const
size_t RiaNNCInputValuesStateHandler::totalValueCount() const
{
return m_cellCount;
}

View File

@@ -84,7 +84,7 @@ public:
grpc::Status init( const rips::NNCValuesInputRequest* request );
grpc::Status receiveStreamRequest( const rips::NNCValuesChunk* request, rips::ClientToServerStreamReply* reply );
size_t cellCount() const;
size_t totalValueCount() const;
size_t streamedValueCount() const;
void finish();

View File

@@ -24,10 +24,311 @@
#include "RimEclipseResultDefinition.h"
#include "RimProject.h"
#include "cafPdmFieldScriptability.h"
#include "cafPdmObject.h"
#include "cafPdmObjectScriptabilityRegister.h"
using namespace rips;
template <typename DataType>
struct DataHolder : public AbstractDataHolder
{
DataHolder( const DataType& data )
: data( data )
{
}
size_t dataCount() const override { return data.size(); }
size_t dataSizeOf() const override { return sizeof( typename DataType::value_type ); }
void reserveReplyStorage( rips::PdmObjectGetMethodReply* reply ) const;
void addValueToReply( size_t valueIndex, rips::PdmObjectGetMethodReply* reply ) const;
size_t getValuesFromChunk( size_t startIndex, const rips::PdmObjectSetMethodChunk* chunk );
void applyValuesToProxyField( caf::PdmProxyFieldHandle* proxyField );
DataType data;
};
template <>
void DataHolder<std::vector<int>>::reserveReplyStorage( rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_ints()->mutable_data()->Reserve( data.size() );
}
template <>
void DataHolder<std::vector<int>>::addValueToReply( size_t valueIndex, rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_ints()->add_data( data[valueIndex] );
}
template <>
size_t DataHolder<std::vector<int>>::getValuesFromChunk( size_t startIndex, const rips::PdmObjectSetMethodChunk* chunk )
{
size_t chunkSize = chunk->ints().data_size();
size_t currentIndex = startIndex;
size_t chunkIndex = 0u;
for ( ; chunkIndex < chunkSize && currentIndex < data.size(); ++currentIndex, ++chunkIndex )
{
data[currentIndex] = chunk->ints().data()[chunkIndex];
}
return chunkSize;
}
template <>
void DataHolder<std::vector<int>>::applyValuesToProxyField( caf::PdmProxyFieldHandle* proxyField )
{
auto proxyValueField = dynamic_cast<caf::PdmProxyValueField<std::vector<int>>*>( proxyField );
CAF_ASSERT( proxyValueField );
if ( proxyValueField )
{
proxyValueField->setValue( data );
}
}
template <>
void DataHolder<std::vector<double>>::reserveReplyStorage( rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_doubles()->mutable_data()->Reserve( data.size() );
}
template <>
void DataHolder<std::vector<double>>::addValueToReply( size_t valueIndex, rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_doubles()->add_data( data[valueIndex] );
}
template <>
size_t DataHolder<std::vector<double>>::getValuesFromChunk( size_t startIndex, const rips::PdmObjectSetMethodChunk* chunk )
{
size_t chunkSize = chunk->doubles().data_size();
size_t currentIndex = startIndex;
size_t chunkIndex = 0u;
for ( ; chunkIndex < chunkSize && currentIndex < data.size(); ++currentIndex, ++chunkIndex )
{
data[currentIndex] = chunk->doubles().data()[chunkIndex];
}
return chunkSize;
}
template <>
void DataHolder<std::vector<double>>::applyValuesToProxyField( caf::PdmProxyFieldHandle* proxyField )
{
auto proxyValueField = dynamic_cast<caf::PdmProxyValueField<std::vector<double>>*>( proxyField );
CAF_ASSERT( proxyValueField );
if ( proxyValueField )
{
proxyValueField->setValue( data );
}
}
template <>
void DataHolder<std::vector<QString>>::reserveReplyStorage( rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_strings()->mutable_data()->Reserve( data.size() );
}
template <>
void DataHolder<std::vector<QString>>::addValueToReply( size_t valueIndex, rips::PdmObjectGetMethodReply* reply ) const
{
reply->mutable_strings()->add_data( data[valueIndex].toStdString() );
}
template <>
size_t DataHolder<std::vector<QString>>::getValuesFromChunk( size_t startIndex, const rips::PdmObjectSetMethodChunk* chunk )
{
size_t chunkSize = chunk->strings().data_size();
size_t currentIndex = startIndex;
size_t chunkIndex = 0u;
for ( ; chunkIndex < chunkSize && currentIndex < data.size(); ++currentIndex, ++chunkIndex )
{
data[currentIndex] = QString::fromStdString( chunk->strings().data()[chunkIndex] );
}
return chunkSize;
}
template <>
void DataHolder<std::vector<QString>>::applyValuesToProxyField( caf::PdmProxyFieldHandle* proxyField )
{
auto proxyValueField = dynamic_cast<caf::PdmProxyValueField<std::vector<QString>>*>( proxyField );
CAF_ASSERT( proxyValueField );
if ( proxyValueField )
{
proxyValueField->setValue( data );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaPdmObjectMethodStateHandler::RiaPdmObjectMethodStateHandler( bool clientToServerStreamer )
: m_fieldOwner( nullptr )
, m_proxyField( nullptr )
, m_currentDataIndex( 0u )
, m_clientToServerStreamer( clientToServerStreamer )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectMethodRequest* request )
{
CAF_ASSERT( !m_clientToServerStreamer );
m_fieldOwner = RiaGrpcPdmObjectService::findCafObjectFromRipsObject( request->object() );
QString fieldName = QString::fromStdString( request->method() );
std::vector<caf::PdmFieldHandle*> fields;
m_fieldOwner->fields( fields );
for ( auto field : fields )
{
auto scriptability = field->capability<caf::PdmFieldScriptability>();
if ( scriptability && scriptability->scriptFieldName() == fieldName )
{
caf::PdmProxyFieldHandle* proxyField = dynamic_cast<caf::PdmProxyFieldHandle*>( field );
if ( proxyField )
{
m_proxyField = proxyField;
if ( dynamic_cast<caf::PdmProxyValueField<std::vector<int>>*>( field ) )
{
auto dataField = dynamic_cast<caf::PdmProxyValueField<std::vector<int>>*>( field );
m_dataHolder.reset( new DataHolder<std::vector<int>>( dataField->value() ) );
return grpc::Status::OK;
}
else if ( dynamic_cast<caf::PdmProxyValueField<std::vector<double>>*>( field ) )
{
auto dataField = dynamic_cast<caf::PdmProxyValueField<std::vector<double>>*>( field );
m_dataHolder.reset( new DataHolder<std::vector<double>>( dataField->value() ) );
return grpc::Status::OK;
}
else if ( dynamic_cast<caf::PdmProxyValueField<std::vector<QString>>*>( field ) )
{
auto dataField = dynamic_cast<caf::PdmProxyValueField<std::vector<QString>>*>( field );
m_dataHolder.reset( new DataHolder<std::vector<QString>>( dataField->value() ) );
return grpc::Status::OK;
}
else
{
CAF_ASSERT( false && "The proxy field data type is not yet supported for streaming fields" );
}
}
}
}
return grpc::Status( grpc::NOT_FOUND, "Proxy field not found" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectSetMethodChunk* chunk )
{
CAF_ASSERT( m_clientToServerStreamer );
CAF_ASSERT( chunk->has_set_request() );
auto setRequest = chunk->set_request();
auto methodRequest = setRequest.request();
m_fieldOwner = RiaGrpcPdmObjectService::findCafObjectFromRipsObject( methodRequest.object() );
QString fieldName = QString::fromStdString( methodRequest.method() );
int valueCount = setRequest.data_count();
std::vector<caf::PdmFieldHandle*> fields;
m_fieldOwner->fields( fields );
for ( auto field : fields )
{
auto scriptability = field->capability<caf::PdmFieldScriptability>();
if ( scriptability && scriptability->scriptFieldName() == fieldName )
{
caf::PdmProxyFieldHandle* proxyField = dynamic_cast<caf::PdmProxyFieldHandle*>( field );
if ( proxyField )
{
m_proxyField = proxyField;
if ( dynamic_cast<caf::PdmProxyValueField<std::vector<int>>*>( field ) )
{
m_dataHolder.reset( new DataHolder<std::vector<int>>( std::vector<int>( valueCount ) ) );
return grpc::Status::OK;
}
else if ( dynamic_cast<caf::PdmProxyValueField<std::vector<double>>*>( field ) )
{
m_dataHolder.reset( new DataHolder<std::vector<double>>( std::vector<double>( valueCount ) ) );
return grpc::Status::OK;
}
else if ( dynamic_cast<caf::PdmProxyValueField<std::vector<QString>>*>( field ) )
{
m_dataHolder.reset( new DataHolder<std::vector<QString>>( std::vector<QString>( valueCount ) ) );
return grpc::Status::OK;
}
else
{
CAF_ASSERT( false && "The proxy field data type is not yet supported for streaming fields" );
}
}
}
}
return grpc::Status( grpc::NOT_FOUND, "Proxy field not found" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Status RiaPdmObjectMethodStateHandler::assignReply( rips::PdmObjectGetMethodReply* reply )
{
CAF_ASSERT( m_dataHolder );
const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( m_dataHolder->dataSizeOf() );
size_t indexInPackage = 0u;
m_dataHolder->reserveReplyStorage( reply );
for ( ; indexInPackage < packageSize && m_currentDataIndex < m_dataHolder->dataCount(); ++indexInPackage )
{
m_dataHolder->addValueToReply( m_currentDataIndex, reply );
m_currentDataIndex++;
}
if ( indexInPackage > 0u )
{
return grpc::Status::OK;
}
return grpc::Status( grpc::OUT_OF_RANGE,
"We've reached the end. This is not an error but means transmission is finished" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Status RiaPdmObjectMethodStateHandler::receiveRequest( const rips::PdmObjectSetMethodChunk* chunk,
rips::ClientToServerStreamReply* reply )
{
size_t valuesWritten = m_dataHolder->getValuesFromChunk( m_currentDataIndex, chunk );
m_currentDataIndex += valuesWritten;
if ( m_currentDataIndex > totalValueCount() )
{
return grpc::Status( grpc::OUT_OF_RANGE, "Attempting to write out of bounds" );
}
reply->set_accepted_value_count( static_cast<int64_t>( m_currentDataIndex ) );
return grpc::Status::OK;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RiaPdmObjectMethodStateHandler::streamedValueCount() const
{
return m_currentDataIndex;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RiaPdmObjectMethodStateHandler::totalValueCount() const
{
return m_dataHolder->dataCount();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaPdmObjectMethodStateHandler::finish()
{
if ( m_proxyField )
{
QVariant before = m_proxyField->toQVariant();
m_dataHolder->applyValuesToProxyField( m_proxyField );
QVariant after = m_proxyField->toQVariant();
m_fieldOwner->fieldChangedByUi( m_proxyField, before, after );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -39,7 +340,7 @@ grpc::Status RiaGrpcPdmObjectService::GetAncestorPdmObject( grpc::ServerContext*
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( request->object().class_keyword() );
QString classKeyword = RicfObjectCapability::classKeywordFromScriptClassName( scriptClassName );
QString classKeyword = caf::PdmObjectScriptabilityRegister::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
@@ -56,7 +357,8 @@ grpc::Status RiaGrpcPdmObjectService::GetAncestorPdmObject( grpc::ServerContext*
{
caf::PdmObject* parentObject = nullptr;
QString ancestorScriptName = QString::fromStdString( request->parent_keyword() );
QString ancestorClassKeyword = RicfObjectCapability::classKeywordFromScriptClassName( ancestorScriptName );
QString ancestorClassKeyword =
caf::PdmObjectScriptabilityRegister::classKeywordFromScriptClassName( ancestorScriptName );
matchingObject->firstAncestorOrThisFromClassKeyword( ancestorClassKeyword, parentObject );
if ( parentObject )
{
@@ -74,28 +376,13 @@ grpc::Status RiaGrpcPdmObjectService::GetDescendantPdmObjects( grpc::ServerConte
const rips::PdmDescendantObjectRequest* request,
rips::PdmObjectArray* reply )
{
RimProject* project = RiaApplication::instance()->project();
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( request->object().class_keyword() );
QString classKeyword = RicfObjectCapability::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
caf::PdmObject* matchingObject = nullptr;
for ( caf::PdmObject* testObject : objectsOfCurrentClass )
{
if ( reinterpret_cast<uint64_t>( testObject ) == request->object().address() )
{
matchingObject = testObject;
}
}
auto matchingObject = findCafObjectFromRipsObject( request->object() );
if ( matchingObject )
{
std::vector<caf::PdmObject*> childObjects;
QString childClassKeyword =
RicfObjectCapability::classKeywordFromScriptClassName( QString::fromStdString( request->child_keyword() ) );
QString childClassKeyword = caf::PdmObjectScriptabilityRegister::classKeywordFromScriptClassName(
QString::fromStdString( request->child_keyword() ) );
matchingObject->descendantsIncludingThisFromClassKeyword( childClassKeyword, childObjects );
for ( auto pdmChild : childObjects )
{
@@ -114,23 +401,7 @@ grpc::Status RiaGrpcPdmObjectService::GetChildPdmObjects( grpc::ServerContext*
const rips::PdmChildObjectRequest* request,
rips::PdmObjectArray* reply )
{
RimProject* project = RiaApplication::instance()->project();
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( request->object().class_keyword() );
QString classKeyword = RicfObjectCapability::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
caf::PdmObject* matchingObject = nullptr;
for ( caf::PdmObject* testObject : objectsOfCurrentClass )
{
if ( reinterpret_cast<uint64_t>( testObject ) == request->object().address() )
{
matchingObject = testObject;
}
}
auto matchingObject = findCafObjectFromRipsObject( request->object() );
if ( matchingObject )
{
QString fieldName = QString::fromStdString( request->child_field() );
@@ -138,7 +409,8 @@ grpc::Status RiaGrpcPdmObjectService::GetChildPdmObjects( grpc::ServerContext*
matchingObject->fields( fields );
for ( auto field : fields )
{
if ( field->keyword() == fieldName )
auto scriptability = field->capability<caf::PdmFieldScriptability>();
if ( scriptability && scriptability->scriptFieldName() == fieldName )
{
std::vector<caf::PdmObjectHandle*> childObjects;
field->childObjects( &childObjects );
@@ -162,22 +434,7 @@ grpc::Status RiaGrpcPdmObjectService::UpdateExistingPdmObject( grpc::ServerConte
const rips::PdmObject* request,
rips::Empty* response )
{
RimProject* project = RiaApplication::instance()->project();
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( request->class_keyword() );
QString classKeyword = RicfObjectCapability::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
caf::PdmObject* matchingObject = nullptr;
for ( caf::PdmObject* pdmObject : objectsOfCurrentClass )
{
if ( reinterpret_cast<uint64_t>( pdmObject ) == request->address() )
{
matchingObject = pdmObject;
}
}
auto matchingObject = findCafObjectFromRipsObject( *request );
if ( matchingObject )
{
@@ -191,7 +448,8 @@ grpc::Status RiaGrpcPdmObjectService::UpdateExistingPdmObject( grpc::ServerConte
}
matchingObject->updateAllRequiredEditors();
project->scheduleCreateDisplayModelAndRedrawAllViews();
RiaApplication::instance()->project()->scheduleCreateDisplayModelAndRedrawAllViews();
Rim3dView* view = dynamic_cast<Rim3dView*>( matchingObject );
if ( view )
{
@@ -209,22 +467,7 @@ grpc::Status RiaGrpcPdmObjectService::CreateChildPdmObject( grpc::ServerContext*
const rips::CreatePdmChildObjectRequest* request,
rips::PdmObject* reply )
{
RimProject* project = RiaApplication::instance()->project();
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( request->object().class_keyword() );
QString classKeyword = RicfObjectCapability::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
caf::PdmObject* matchingObject = nullptr;
for ( caf::PdmObject* testObject : objectsOfCurrentClass )
{
if ( reinterpret_cast<uint64_t>( testObject ) == request->object().address() )
{
matchingObject = testObject;
}
}
auto matchingObject = findCafObjectFromRipsObject( request->object() );
if ( matchingObject )
{
@@ -242,6 +485,28 @@ grpc::Status RiaGrpcPdmObjectService::CreateChildPdmObject( grpc::ServerContext*
return grpc::Status( grpc::NOT_FOUND, "Could not find PdmObject" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaGrpcPdmObjectService::CallPdmObjectGetMethod( grpc::ServerContext* context,
const rips::PdmObjectMethodRequest* request,
rips::PdmObjectGetMethodReply* reply,
RiaPdmObjectMethodStateHandler* stateHandler )
{
return stateHandler->assignReply( reply );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaGrpcPdmObjectService::CallPdmObjectSetMethod( grpc::ServerContext* context,
const rips::PdmObjectSetMethodChunk* chunk,
rips::ClientToServerStreamReply* reply,
RiaPdmObjectMethodStateHandler* stateHandler )
{
return stateHandler->receiveRequest( chunk, reply );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -262,7 +527,47 @@ std::vector<RiaGrpcCallbackInterface*> RiaGrpcPdmObjectService::createCallbacks(
&Self::RequestUpdateExistingPdmObject ),
new RiaGrpcUnaryCallback<Self, CreatePdmChildObjectRequest, PdmObject>( this,
&Self::CreateChildPdmObject,
&Self::RequestCreateChildPdmObject )};
&Self::RequestCreateChildPdmObject ),
new RiaGrpcServerToClientStreamCallback<Self,
PdmObjectMethodRequest,
PdmObjectGetMethodReply,
RiaPdmObjectMethodStateHandler>( this,
&Self::CallPdmObjectGetMethod,
&Self::RequestCallPdmObjectGetMethod,
new RiaPdmObjectMethodStateHandler ),
new RiaGrpcClientToServerStreamCallback<Self,
PdmObjectSetMethodChunk,
ClientToServerStreamReply,
RiaPdmObjectMethodStateHandler>( this,
&Self::CallPdmObjectSetMethod,
&Self::RequestCallPdmObjectSetMethod,
new RiaPdmObjectMethodStateHandler(
true ) )};
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmObject* RiaGrpcPdmObjectService::findCafObjectFromRipsObject( const rips::PdmObject& ripsObject )
{
RimProject* project = RiaApplication::instance()->project();
std::vector<caf::PdmObject*> objectsOfCurrentClass;
QString scriptClassName = QString::fromStdString( ripsObject.class_keyword() );
QString classKeyword = caf::PdmObjectScriptabilityRegister::classKeywordFromScriptClassName( scriptClassName );
project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass );
caf::PdmObject* matchingObject = nullptr;
for ( caf::PdmObject* testObject : objectsOfCurrentClass )
{
if ( reinterpret_cast<uint64_t>( testObject ) == ripsObject.address() )
{
matchingObject = testObject;
}
}
return matchingObject;
}
static bool RiaGrpcPdmObjectService_init = RiaGrpcServiceFactory::instance()->registerCreator<RiaGrpcPdmObjectService>(

View File

@@ -23,6 +23,50 @@
#include <grpcpp/grpcpp.h>
#include <vector>
namespace caf
{
class PdmProxyFieldHandle;
}
struct AbstractDataHolder
{
virtual size_t dataCount() const = 0;
virtual size_t dataSizeOf() const = 0;
virtual void reserveReplyStorage( rips::PdmObjectGetMethodReply* reply ) const = 0;
virtual void addValueToReply( size_t valueIndex, rips::PdmObjectGetMethodReply* reply ) const = 0;
virtual size_t getValuesFromChunk( size_t startIndex, const rips::PdmObjectSetMethodChunk* chunk ) = 0;
virtual void applyValuesToProxyField( caf::PdmProxyFieldHandle* proxyField ) = 0;
};
//==================================================================================================
//
// State handler for streaming of active cell info
//
//==================================================================================================
class RiaPdmObjectMethodStateHandler
{
typedef grpc::Status Status;
public:
RiaPdmObjectMethodStateHandler( bool clientToServerStreamer = false );
Status init( const rips::PdmObjectMethodRequest* request );
Status init( const rips::PdmObjectSetMethodChunk* chunk );
Status assignReply( rips::PdmObjectGetMethodReply* reply );
Status receiveRequest( const rips::PdmObjectSetMethodChunk* chunk, rips::ClientToServerStreamReply* reply );
size_t streamedValueCount() const;
size_t totalValueCount() const;
void finish();
protected:
caf::PdmObject* m_fieldOwner;
caf::PdmProxyFieldHandle* m_proxyField;
std::unique_ptr<AbstractDataHolder> m_dataHolder;
size_t m_currentDataIndex;
bool m_clientToServerStreamer;
};
//==================================================================================================
//
// gRPC-service answering request searching for PdmObjects in property tree
@@ -49,5 +93,16 @@ public:
const rips::PdmObject* request,
rips::Empty* response ) override;
grpc::Status CallPdmObjectGetMethod( grpc::ServerContext* context,
const rips::PdmObjectMethodRequest* request,
rips::PdmObjectGetMethodReply* reply,
RiaPdmObjectMethodStateHandler* stateHandler );
grpc::Status CallPdmObjectSetMethod( grpc::ServerContext* context,
const rips::PdmObjectSetMethodChunk* chunk,
rips::ClientToServerStreamReply* reply,
RiaPdmObjectMethodStateHandler* stateHandler );
std::vector<RiaGrpcCallbackInterface*> createCallbacks() override;
static caf::PdmObject* findCafObjectFromRipsObject( const rips::PdmObject& ripsObject );
};

View File

@@ -70,7 +70,7 @@ public:
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t cellCount() const { return m_cellCount; }
size_t totalValueCount() const { return m_cellCount; }
//--------------------------------------------------------------------------------------------------
///

View File

@@ -22,13 +22,15 @@
#include "RimProject.h"
#include "RicfFieldHandle.h"
#include "RicfMessages.h"
#include "RicfObjectCapability.h"
#include "cafPdmChildArrayField.h"
#include "cafPdmChildField.h"
#include "cafPdmDataValueField.h"
#include "cafPdmObject.h"
#include "cafPdmObjectScriptabilityRegister.h"
#include "cafPdmProxyValueField.h"
#include "cafPdmScriptIOMessages.h"
#include "cafPdmXmlFieldHandle.h"
#include <grpcpp/grpcpp.h>
@@ -71,7 +73,7 @@ void RiaGrpcServiceInterface::copyPdmObjectFromCafToRips( const caf::PdmObjectHa
CAF_ASSERT( source && destination && source->xmlCapability() );
QString classKeyword = source->xmlCapability()->classKeyword();
QString scriptName = RicfObjectCapability::scriptClassNameFromClassKeyword( classKeyword );
QString scriptName = caf::PdmObjectScriptabilityRegister::scriptClassNameFromClassKeyword( classKeyword );
destination->set_class_keyword( scriptName.toStdString() );
destination->set_address( reinterpret_cast<uint64_t>( source ) );
@@ -99,11 +101,15 @@ void RiaGrpcServiceInterface::copyPdmObjectFromCafToRips( const caf::PdmObjectHa
QString keyword = pdmValueField->keyword();
auto ricfHandle = field->template capability<RicfFieldHandle>();
if ( ricfHandle != nullptr )
{
auto pdmProxyField = dynamic_cast<const caf::PdmProxyFieldHandle*>( field );
if ( !( pdmProxyField && pdmProxyField->isStreamingField() ) )
{
QString text;
QTextStream outStream( &text );
ricfHandle->writeFieldData( outStream, false );
( *parametersMap )[ricfHandle->fieldName().toStdString()] = text.toStdString();
ricfHandle->readFromField( outStream, false );
( *parametersMap )[ricfHandle->scriptFieldName().toStdString()] = text.toStdString();
}
}
}
}
@@ -141,7 +147,7 @@ void RiaGrpcServiceInterface::copyPdmObjectFromRipsToCaf( const rips::PdmObject*
auto ricfHandle = pdmValueField->template capability<RicfFieldHandle>();
if ( ricfHandle )
{
QString keyword = ricfHandle->fieldName();
QString keyword = ricfHandle->scriptFieldName();
QString value = QString::fromStdString( parametersMap[keyword.toStdString()] );
QVariant oldValue, newValue;
@@ -168,9 +174,9 @@ bool RiaGrpcServiceInterface::assignFieldValue( const QString& stringValue,
if ( field && ricfHandle != nullptr )
{
QTextStream stream( stringValue.toLatin1() );
RicfMessages messages;
caf::PdmScriptIOMessages messages;
*oldValue = field->toQVariant();
ricfHandle->readFieldData( stream, nullptr, &messages, false );
ricfHandle->writeToField( stream, nullptr, &messages, false );
*newValue = field->toQVariant();
return true;
}
@@ -206,7 +212,7 @@ caf::PdmObjectHandle* RiaGrpcServiceInterface::emplaceChildField( caf::PdmObject
//--------------------------------------------------------------------------------------------------
caf::PdmObjectHandle* RiaGrpcServiceInterface::emplaceChildField( caf::PdmChildFieldHandle* childField )
{
QString childClassKeyword = childField->xmlCapability()->childClassKeyword();
QString childClassKeyword = childField->xmlCapability()->dataTypeName();
auto pdmObjectHandle = caf::PdmDefaultObjectFactory::instance()->create( childClassKeyword );
CAF_ASSERT( pdmObjectHandle );
@@ -219,7 +225,7 @@ caf::PdmObjectHandle* RiaGrpcServiceInterface::emplaceChildField( caf::PdmChildF
//--------------------------------------------------------------------------------------------------
caf::PdmObjectHandle* RiaGrpcServiceInterface::emplaceChildArrayField( caf::PdmChildArrayFieldHandle* childArrayField )
{
QString childClassKeyword = childArrayField->xmlCapability()->childClassKeyword();
QString childClassKeyword = childArrayField->xmlCapability()->dataTypeName();
auto pdmObjectHandle = caf::PdmDefaultObjectFactory::instance()->create( childClassKeyword );
CAF_ASSERT( pdmObjectHandle );

View File

@@ -456,7 +456,7 @@ void RivSurfacePartMgr::calculateVertexTextureCoordinates( cvf::Vec2fArray*
cvf::Vec2f* rawPtr = textureCoords->ptr();
#pragma omp parallel for
for ( int vxIdx = 0; vxIdx < numVertices; vxIdx++ )
for ( int vxIdx = 0; vxIdx < static_cast<int>( numVertices ); vxIdx++ )
{
double cellScalarValue = resultAccessor->cellScalarGlobIdx( vertexToCellIdxMap[vxIdx] );
cvf::Vec2f texCoord = mapper->mapToTextureCoord( cellScalarValue );

View File

@@ -43,7 +43,7 @@ CAF_PDM_XML_ABSTRACT_SOURCE_INIT( RimCase, "Case", "RimCase" );
RimCase::RimCase()
: m_isInActiveDestruction( false )
{
RICF_InitObjectWithScriptNameAndComment( "Case", ":/Case48x48.png", "", "", "Case", "The ResInsight base class for Cases" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Case", ":/Case48x48.png", "", "", "Case", "The ResInsight base class for Cases" );
RICF_InitField( &caseUserDescription, "Name", QString(), "Case Name", "", "", "" );
caseUserDescription.registerKeywordAlias( "CaseUserDescription" );

View File

@@ -78,14 +78,20 @@ CAF_PDM_XML_ABSTRACT_SOURCE_INIT( RimEclipseCase, "RimReservoir" );
//--------------------------------------------------------------------------------------------------
RimEclipseCase::RimEclipseCase()
{
RICF_InitObjectWithScriptNameAndComment( "EclipseCase",
CAF_PDM_InitScriptableObjectWithNameAndComment( "EclipseCase",
":/Case48x48.png",
"",
"",
"Reservoir",
"Abtract base class for Eclipse Cases" );
CAF_PDM_InitFieldNoDefault( &reservoirViews, "ReservoirViews", "", "", "", "" );
CAF_PDM_InitScriptableFieldWithKeywordNoDefault( &reservoirViews,
"ReservoirViews",
"Views",
"",
"",
"",
"All Eclipse Views in the case" );
reservoirViews.uiCapability()->setUiHidden( true );
CAF_PDM_InitFieldNoDefault( &m_matrixModelResults, "MatrixModelResults", "", "", "", "" );

View File

@@ -21,6 +21,7 @@
#include "RimEclipseCellColors.h"
#include "RiaColorTables.h"
#include "RicfCommandObject.h"
#include "RigCaseCellResultsData.h"
#include "RigEclipseCaseData.h"
#include "RigFlowDiagResults.h"
@@ -50,7 +51,12 @@ CAF_PDM_SOURCE_INIT( RimEclipseCellColors, "ResultSlot" );
//--------------------------------------------------------------------------------------------------
RimEclipseCellColors::RimEclipseCellColors()
{
CAF_PDM_InitObject( "Cell Result", ":/CellResult.png", "", "" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Cell Result",
":/CellResult.png",
"",
"",
"CellColors",
"Eclipse Cell Colors class" );
CAF_PDM_InitFieldNoDefault( &obsoleteField_legendConfig, "LegendDefinition", "Color Legend", "", "", "" );
this->obsoleteField_legendConfig.xmlCapability()->setIOWritable( false );

View File

@@ -53,7 +53,7 @@ const cvf::Mat4d RimEclipseContourMapView::sm_defaultViewMatrix =
RimEclipseContourMapView::RimEclipseContourMapView()
: m_cameraPositionLastUpdate( cvf::Vec3d::UNDEFINED )
{
RICF_InitObjectWithScriptNameAndComment( "Contour Map View",
CAF_PDM_InitScriptableObjectWithNameAndComment( "Contour Map View",
":/2DMap16x16.png",
"",
"",

View File

@@ -70,7 +70,7 @@ CAF_PDM_SOURCE_INIT( RimEclipseResultCase, "EclipseCase" );
RimEclipseResultCase::RimEclipseResultCase()
: RimEclipseCase()
{
RICF_InitObject( "Eclipse Case", ":/Case48x48.png", "", "The Regular Eclipse Results Case" );
CAF_PDM_InitScriptableObject( "Eclipse Case", ":/Case48x48.png", "", "The Regular Eclipse Results Case" );
CAF_PDM_InitFieldNoDefault( &m_unitSystem, "UnitSystem", "Unit System", "", "", "" );
m_unitSystem.registerGetMethod( RiaApplication::instance()->project(), &RimProject::commonUnitSystemForAllCases );

View File

@@ -95,7 +95,7 @@ RimEclipseResultDefinition::RimEclipseResultDefinition( caf::PdmUiItemInfo::Labe
, m_labelPosition( labelPosition )
, m_ternaryEnabled( true )
{
CAF_PDM_InitObject( "Result Definition", "", "", "" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Result Definition", "", "", "", "EclipseResult", "An eclipse result definition" );
RICF_InitFieldNoDefault( &m_resultType, "ResultType", "Type", "", "", "" );
m_resultType.uiCapability()->setUiHidden( true );

View File

@@ -121,14 +121,20 @@ RimEclipseView::RimEclipseView()
RiaPreferences* preferences = app->preferences();
CVF_ASSERT( preferences );
RICF_InitObjectWithScriptNameAndComment( "Reservoir View",
CAF_PDM_InitScriptableObjectWithNameAndComment( "Reservoir View",
":/3DView16x16.png",
"",
"The Eclipse 3d Reservoir View",
"EclipseView",
"The Eclipse 3d Reservoir View" );
CAF_PDM_InitFieldNoDefault( &m_cellResult, "GridCellResult", "Cell Result", ":/CellResult.png", "", "" );
CAF_PDM_InitScriptableFieldWithKeywordNoDefault( &m_cellResult,
"GridCellResult",
"CellResult",
"Cell Result",
":/CellResult.png",
"",
"" );
m_cellResult = new RimEclipseCellColors();
m_cellResult.uiCapability()->setUiHidden( true );
m_cellResult->setDiffResultOptionsEnabled( true );
@@ -172,8 +178,12 @@ RimEclipseView::RimEclipseView()
CAF_PDM_InitField( &m_showInactiveCells, "ShowInactiveCells", false, "Show Inactive Cells", "", "", "" );
CAF_PDM_InitField( &m_showInvalidCells, "ShowInvalidCells", false, "Show Invalid Cells", "", "", "" );
this->cellResult()->setReservoirView( this );
CAF_PDM_InitScriptableFieldNoDefault( &m_cellResultData, "CellResultData", "", "", "", "Current Eclipse Cell Result" );
m_cellResultData.xmlCapability()->disableIO();
m_cellResultData.registerGetMethod( this, &RimEclipseView::currentCellResultData );
m_cellResultData.registerSetMethod( this, &RimEclipseView::setCurrentCellResultData );
this->cellResult()->setReservoirView( this );
this->cellEdgeResult()->setReservoirView( this );
this->cellEdgeResult()->legendConfig()->setColorRange( RimRegularLegendConfig::PINK_WHITE );
@@ -351,6 +361,12 @@ void RimEclipseView::fieldChangedByUi( const caf::PdmFieldHandle* changedField,
scheduleCreateDisplayModelAndRedraw();
}
else if ( changedField == &m_cellResultData )
{
currentGridCellResults()->recalculateStatistics( m_cellResult->eclipseResultAddress() );
setCurrentTimeStepAndUpdate( currentTimeStep() );
createDisplayModelAndRedraw();
}
}
//--------------------------------------------------------------------------------------------------
@@ -1120,7 +1136,7 @@ void RimEclipseView::onUpdateDisplayModelVisibility()
//--------------------------------------------------------------------------------------------------
/// Convenience for quick access to results
//--------------------------------------------------------------------------------------------------
RigCaseCellResultsData* RimEclipseView::currentGridCellResults()
RigCaseCellResultsData* RimEclipseView::currentGridCellResults() const
{
if ( m_eclipseCase )
{
@@ -1894,6 +1910,45 @@ RimEclipseCellColors* RimEclipseView::currentFaultResultColors()
return faultResultColors;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<double> RimEclipseView::currentCellResultData() const
{
std::vector<double> resultData;
if ( currentGridCellResults() && cellResult() )
{
int timeStep = 0;
if ( cellResult()->hasDynamicResult() )
{
timeStep = this->currentTimeStep();
}
resultData = currentGridCellResults()->cellScalarResults( cellResult()->eclipseResultAddress() )[timeStep];
}
return resultData;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimEclipseView::setCurrentCellResultData( const std::vector<double>& values )
{
if ( currentGridCellResults() && cellResult() )
{
int timeStep = 0;
if ( cellResult()->hasDynamicResult() )
{
timeStep = this->currentTimeStep();
}
std::vector<double>* modResult =
currentGridCellResults()->modifiableCellScalarResult( cellResult()->eclipseResultAddress(), timeStep );
if ( modResult->size() == values.size() )
{
*modResult = values;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------

View File

@@ -24,6 +24,7 @@
#include "cafPdmChildField.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
#include "cafPdmProxyValueField.h"
#include "cvfArray.h"
@@ -101,10 +102,13 @@ public:
const RimEclipsePropertyFilterCollection* eclipsePropertyFilterCollection() const;
void setOverridePropertyFilterCollection( RimEclipsePropertyFilterCollection* pfc );
RigCaseCellResultsData* currentGridCellResults();
RigCaseCellResultsData* currentGridCellResults() const;
const RigActiveCellInfo* currentActiveCellInfo() const;
RimEclipseCellColors* currentFaultResultColors();
std::vector<double> currentCellResultData() const;
void setCurrentCellResultData( const std::vector<double>& values );
void setEclipseCase( RimEclipseCase* reservoir );
RimEclipseCase* eclipseCase() const;
RimCase* ownerCase() const override;
@@ -206,6 +210,8 @@ private:
caf::PdmChildField<RimStimPlanColors*> m_fractureColors;
caf::PdmChildField<RimVirtualPerforationResults*> m_virtualPerforationResult;
caf::PdmProxyValueField<std::vector<double>> m_cellResultData;
caf::PdmChildField<RimSimWellInViewCollection*> m_wellCollection;
caf::PdmChildField<RimFaultInViewCollection*> m_faultCollection;

View File

@@ -15,7 +15,12 @@ CAF_PDM_SOURCE_INIT( RimFileWellPath, "WellPath" );
//--------------------------------------------------------------------------------------------------
RimFileWellPath::RimFileWellPath()
{
RICF_InitObjectWithScriptNameAndComment( "File Well Path", ":/Well.png", "", "", "FileWellPath", "Well Paths Loaded From File" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "File Well Path",
":/Well.png",
"",
"",
"FileWellPath",
"Well Paths Loaded From File" );
CAF_PDM_InitFieldNoDefault( &id, "WellPathId", "Id", "", "", "" );
id.uiCapability()->setUiReadOnly( true );

View File

@@ -69,14 +69,20 @@ CAF_PDM_SOURCE_INIT( RimGeoMechCase, "ResInsightGeoMechCase" );
RimGeoMechCase::RimGeoMechCase( void )
: m_applyTimeFilter( false )
{
RICF_InitObjectWithScriptNameAndComment( "GeoMechanical Case",
CAF_PDM_InitScriptableObjectWithNameAndComment( "GeoMechanical Case",
":/GeoMechCase48x48.png",
"",
"The GeoMechanical Results Case",
"GeoMechCase",
"The Abaqus Based GeoMech Case" );
CAF_PDM_InitFieldNoDefault( &geoMechViews, "GeoMechViews", "", "", "", "" );
CAF_PDM_InitScriptableFieldWithKeywordNoDefault( &geoMechViews,
"GeoMechViews",
"Views",
"",
"",
"",
"All GeoMech Views in the Case" );
geoMechViews.uiCapability()->setUiHidden( true );
CAF_PDM_InitField( &m_cohesion, "CaseCohesion", 10.0, "Cohesion", "", "Used to calculate the SE:SFI result", "" );

View File

@@ -51,7 +51,7 @@ const cvf::Mat4d RimGeoMechContourMapView::sm_defaultViewMatrix =
RimGeoMechContourMapView::RimGeoMechContourMapView()
: m_cameraPositionLastUpdate( cvf::Vec3d::UNDEFINED )
{
RICF_InitObjectWithScriptNameAndComment( "GeoMech Contour Map View",
CAF_PDM_InitScriptableObjectWithNameAndComment( "GeoMech Contour Map View",
":/2DMap16x16.png",
"",
"",

View File

@@ -85,7 +85,7 @@ CAF_PDM_SOURCE_INIT( RimGeoMechView, "GeoMechView" );
//--------------------------------------------------------------------------------------------------
RimGeoMechView::RimGeoMechView( void )
{
RICF_InitObject( "Geomechanical View", ":/3DViewGeoMech16x16.png", "", "The Geomechanical 3d View" );
CAF_PDM_InitScriptableObject( "Geomechanical View", ":/3DViewGeoMech16x16.png", "", "The Geomechanical 3d View" );
CAF_PDM_InitFieldNoDefault( &cellResult, "GridCellResult", "Color Result", ":/CellResult.png", "", "" );
cellResult = new RimGeoMechCellColors();

View File

@@ -55,7 +55,7 @@ CAF_PDM_SOURCE_INIT( RimIdenticalGridCaseGroup, "RimIdenticalGridCaseGroup" );
//--------------------------------------------------------------------------------------------------
RimIdenticalGridCaseGroup::RimIdenticalGridCaseGroup()
{
RICF_InitObjectWithScriptNameAndComment( "Grid Case Group",
CAF_PDM_InitScriptableObjectWithNameAndComment( "Grid Case Group",
":/GridCaseGroup16x16.png",
"",
"",

View File

@@ -40,7 +40,10 @@ CAF_PDM_SOURCE_INIT( RimModeledWellPath, "ModeledWellPath" );
//--------------------------------------------------------------------------------------------------
RimModeledWellPath::RimModeledWellPath()
{
RICF_InitObject( "Modeled WellPath", ":/EditableWell.png", "", "A Well Path created interactively in ResInsight" );
CAF_PDM_InitScriptableObject( "Modeled WellPath",
":/EditableWell.png",
"",
"A Well Path created interactively in ResInsight" );
CAF_PDM_InitFieldNoDefault( &m_geometryDefinition, "WellPathGeometryDef", "Trajectory", "", "", "" );
m_geometryDefinition = new RimWellPathGeometryDef;

View File

@@ -33,7 +33,7 @@ CAF_PDM_XML_ABSTRACT_SOURCE_INIT( RimPlot, "RimPlot" ); // Do not use. Abstract
//--------------------------------------------------------------------------------------------------
RimPlot::RimPlot()
{
RICF_InitObjectWithScriptNameAndComment( "Plot", "", "", "", "Plot", "The Abstract Base Class for all Plot Objects" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Plot", "", "", "", "Plot", "The Abstract Base Class for all Plot Objects" );
CAF_PDM_InitFieldNoDefault( &m_rowSpan, "RowSpan", "Row Span", "", "", "" );
CAF_PDM_InitFieldNoDefault( &m_colSpan, "ColSpan", "Col Span", "", "", "" );

View File

@@ -37,7 +37,7 @@ CAF_PDM_XML_ABSTRACT_SOURCE_INIT( RimPlotWindow, "RimPlotWindow" ); // Do not us
//--------------------------------------------------------------------------------------------------
RimPlotWindow::RimPlotWindow()
{
RICF_InitObjectWithScriptNameAndComment( "PlotWindow",
CAF_PDM_InitScriptableObjectWithNameAndComment( "PlotWindow",
"",
"",
"",

View File

@@ -114,7 +114,7 @@ RimProject::RimProject( void )
, m_nextValidPlotId( 1 )
, m_nextValidCalculationId( 1 )
{
RICF_InitObjectWithScriptNameAndComment( "Project", "", "", "", "Project", "The ResInsight Project" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Project", "", "", "", "Project", "The ResInsight Project" );
CAF_PDM_InitField( &m_projectFileVersionString, "ProjectFileVersionString", QString( STRPRODUCTVER ), "", "", "", "" );
m_projectFileVersionString.uiCapability()->setUiHidden( true );

View File

@@ -62,7 +62,12 @@ CAF_PDM_SOURCE_INIT( RimSimWellInView, "Well" );
//--------------------------------------------------------------------------------------------------
RimSimWellInView::RimSimWellInView()
{
RICF_InitObjectWithScriptNameAndComment( "Simulation Well", ":/Well.png", "", "", "SimulationWell", "An Eclipse Simulation Well" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "Simulation Well",
":/Well.png",
"",
"",
"SimulationWell",
"An Eclipse Simulation Well" );
RICF_InitFieldNoDefault( &name, "Name", "Name", "", "", "" );
name.registerKeywordAlias( "WellName" );

View File

@@ -43,7 +43,7 @@ CAF_PDM_XML_ABSTRACT_SOURCE_INIT( RimViewWindow, "ViewWindow" ); // Do not use.
//--------------------------------------------------------------------------------------------------
RimViewWindow::RimViewWindow( void )
{
RICF_InitObjectWithScriptNameAndComment( "View window",
CAF_PDM_InitScriptableObjectWithNameAndComment( "View window",
"",
"",
"",

View File

@@ -33,7 +33,7 @@ CAF_PDM_SOURCE_INIT( RimWbsParameters, "WbsParameters" );
//--------------------------------------------------------------------------------------------------
RimWbsParameters::RimWbsParameters()
{
RICF_InitObject( "Well Bore Stability Parameters", ":/WellLogPlot16x16.png", "", "" );
CAF_PDM_InitScriptableObject( "Well Bore Stability Parameters", ":/WellLogPlot16x16.png", "", "" );
RICF_InitFieldNoDefault( &m_porePressureSource,
"PorePressureReservoirSource",
@@ -427,13 +427,18 @@ std::vector<RimWbsParameters::ParameterSource> RimWbsParameters::supportedSource
{
std::vector<RigGeoMechWellLogExtractor::WbsParameterSource> sources;
std::set<RimWbsParameters::ParameterSource> sourcesAlreadyAdded;
for ( auto source : parameter.sources() )
{
if ( sourcesAlreadyAdded.count( source ) ) continue;
if ( source == RigWbsParameter::LAS_FILE )
{
if ( hasLasFileWithChannel( parameter.addressString( RigWbsParameter::LAS_FILE ) ) )
{
sources.push_back( source );
sourcesAlreadyAdded.insert( source );
}
}
else if ( source == RigWbsParameter::ELEMENT_PROPERTY_TABLE )
@@ -442,11 +447,13 @@ std::vector<RimWbsParameters::ParameterSource> RimWbsParameters::supportedSource
if ( hasElementPropertyEntry( resAddr ) )
{
sources.push_back( source );
sourcesAlreadyAdded.insert( source );
}
}
else
{
sources.push_back( source );
sourcesAlreadyAdded.insert( source );
}
}
return sources;

View File

@@ -42,9 +42,18 @@ CAF_PDM_SOURCE_INIT( RimWellBoreStabilityPlot, "WellBoreStabilityPlot" );
//--------------------------------------------------------------------------------------------------
RimWellBoreStabilityPlot::RimWellBoreStabilityPlot()
{
RICF_InitObject( "Well Bore Stability Plot", ":/WellBoreStability16x16.png", "", "A GeoMechanical Well Bore Stabilit Plot" );
CAF_PDM_InitScriptableObject( "Well Bore Stability Plot",
":/WellBoreStability16x16.png",
"",
"A GeoMechanical Well Bore Stabilit Plot" );
CAF_PDM_InitFieldNoDefault( &m_wbsParameters, "WbsParameters", "Well Bore Stability Parameters", "", "", "" );
CAF_PDM_InitScriptableFieldWithKeywordNoDefault( &m_wbsParameters,
"WbsParameters",
"Parameters",
"Well Bore Stability Parameters",
"",
"",
"" );
m_wbsParameters = new RimWbsParameters;
m_wbsParameters.uiCapability()->setUiTreeHidden( true );
m_wbsParameters.uiCapability()->setUiTreeChildrenHidden( true );
@@ -82,6 +91,16 @@ void RimWellBoreStabilityPlot::copyWbsParameters( const RimWbsParameters* wbsPar
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellBoreStabilityPlot::setCaseWellPathAndTimeStep( RimGeoMechCase* geoMechCase, RimWellPath* wellPath, int timeStep )
{
m_wbsParameters->setGeoMechCase( geoMechCase );
m_wbsParameters->setWellPath( wellPath );
m_wbsParameters->setTimeStep( timeStep );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------

View File

@@ -39,6 +39,7 @@ public:
void applyWbsParametersToExtractor( RigGeoMechWellLogExtractor* extractor );
double userDefinedValue( const RigWbsParameter& parameter ) const;
void copyWbsParameters( const RimWbsParameters* wbsParameters );
void setCaseWellPathAndTimeStep( RimGeoMechCase* geoMechCase, RimWellPath* wellPath, int timeStep );
protected:
void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override;

View File

@@ -108,6 +108,19 @@ void RimWellLogFileCurve::onLoadDataAndUpdate( bool updateParentPlot )
}
}
}
if ( tvdRkbValues.size() != values.size() )
{
RigWellPath* rigWellPath = m_wellPath->wellPathGeometry();
if ( rigWellPath )
{
tvdRkbValues.clear();
for ( double measuredDepthValue : measuredDepthValues )
{
tvdRkbValues.push_back( -rigWellPath->interpolatedPointAlongWellPath( measuredDepthValue ).z() +
m_wellPath->wellPathGeometry()->rkbDiff() );
}
}
}
std::map<RiaDefines::DepthTypeEnum, std::vector<double>> validDepths;
if ( values.size() == measuredDepthValues.size() )

View File

@@ -71,7 +71,7 @@ CAF_PDM_SOURCE_INIT( RimWellLogPlot, "WellLogPlot" );
//--------------------------------------------------------------------------------------------------
RimWellLogPlot::RimWellLogPlot()
{
RICF_InitObject( "Well Log Plot",
CAF_PDM_InitScriptableObject( "Well Log Plot",
":/WellLogPlot16x16.png",
"",
"A Well Log Plot With a shared Depth Axis and Multiple Tracks" );

View File

@@ -73,7 +73,7 @@ const char RimWellPath::SIM_WELL_NONE_UI_TEXT[] = "None";
//--------------------------------------------------------------------------------------------------
RimWellPath::RimWellPath()
{
RICF_InitObject( "WellPath", ":/Well.png", "", "The Base class for Well Paths" );
CAF_PDM_InitScriptableObjectWithNameAndComment( "WellPath", ":/Well.png", "", "", "WellPath", "The Base class for Well Paths" );
RICF_InitFieldNoDefault( &m_name, "Name", "Name", "", "", "" );
m_name.registerKeywordAlias( "WellPathName" );

View File

@@ -42,7 +42,7 @@ CAF_PDM_SOURCE_INIT( RimFileSummaryCase, "FileSummaryCase" );
//--------------------------------------------------------------------------------------------------
RimFileSummaryCase::RimFileSummaryCase()
{
RICF_InitObject( "File Summary Case ", "", "", "A Summary Case based on SMSPEC files" );
CAF_PDM_InitScriptableObject( "File Summary Case ", "", "", "A Summary Case based on SMSPEC files" );
CAF_PDM_InitField( &m_includeRestartFiles, "IncludeRestartFiles", false, "Include Restart Files", "", "", "" );
m_includeRestartFiles.uiCapability()->setUiHidden( true );

View File

@@ -40,7 +40,7 @@ CAF_PDM_SOURCE_INIT( RimGridSummaryCase, "GridSummaryCase" );
//--------------------------------------------------------------------------------------------------
RimGridSummaryCase::RimGridSummaryCase()
{
RICF_InitObject( "Grid Summary Case ", "", "", "A Summary Case based on extracting grid data." );
CAF_PDM_InitScriptableObject( "Grid Summary Case ", "", "", "A Summary Case based on extracting grid data." );
CAF_PDM_InitFieldNoDefault( &m_eclipseCase, "Associated3DCase", "Eclipse Case", "", "", "" );
m_eclipseCase.uiCapability()->setUiHidden( true );

View File

@@ -44,7 +44,7 @@ const QString RimSummaryCase::DEFAULT_DISPLAY_NAME = "Display Name";
//--------------------------------------------------------------------------------------------------
RimSummaryCase::RimSummaryCase()
{
RICF_InitObject( "Summary Case", ":/SummaryCase16x16.png", "", "The Base Class for all Summary Cases" );
CAF_PDM_InitScriptableObject( "Summary Case", ":/SummaryCase16x16.png", "", "The Base Class for all Summary Cases" );
RICF_InitField( &m_shortName, "ShortName", QString( "Display Name" ), DEFAULT_DISPLAY_NAME, "", "", "" );
RICF_InitField( &m_useAutoShortName, "AutoShortyName", false, "Use Auto Display Name", "", "", "" );

View File

@@ -143,7 +143,7 @@ CurvesData concatCurvesData( const std::vector<CurvesData>& curvesData );
RimSummaryPlot::RimSummaryPlot()
: RimPlot()
{
RICF_InitObject( "Summary Plot", ":/SummaryPlotLight16x16.png", "", "A Summary Plot" );
CAF_PDM_InitScriptableObject( "Summary Plot", ":/SummaryPlotLight16x16.png", "", "A Summary Plot" );
RICF_InitField( &m_showPlotTitle, "ShowPlotTitle", true, "Plot Title", "", "", "" );
m_showPlotTitle.xmlCapability()->setIOWritable( false );

View File

@@ -183,6 +183,7 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd
}
}
}
return RiaWellLogUnitTools::sg_emwUnitString();
}
else if ( resAddr.isValid() )
{
@@ -210,7 +211,7 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd
}
}
}
return RiaWellLogUnitTools::sg_emwUnitString();
return RiaWellLogUnitTools::barUnitString();
}
//--------------------------------------------------------------------------------------------------

View File

@@ -255,8 +255,8 @@ RigWbsParameter RigWbsParameter::PP_NonReservoir()
true,
{{LAS_FILE, SourceAddress( "PP_NONRES_INP", "", RiaWellLogUnitTools::sg_emwUnitString() )},
{LAS_FILE, SourceAddress( "POR_NONRES_INP", "", RiaWellLogUnitTools::gPerCm3UnitString() )},
{HYDROSTATIC, SourceAddress( "Hydrostatic", "", RiaWellLogUnitTools::barUnitString() )},
{USER_DEFINED, SourceAddress( "", "", RiaWellLogUnitTools::barUnitString() )}} );
{USER_DEFINED, SourceAddress( "", "", RiaWellLogUnitTools::barUnitString() )},
{HYDROSTATIC, SourceAddress( "Hydrostatic", "", RiaWellLogUnitTools::barUnitString() )}} );
}
//--------------------------------------------------------------------------------------------------

View File

@@ -2,10 +2,10 @@
#include "RicfCommandFileExecutor.h"
#include "RicfCommandObject.h"
#include "RicfMessages.h"
#include "RifcCommandFileReader.h"
#include "cafPdmField.h"
#include "cafPdmScriptIOMessages.h"
class TestCommand1 : public RicfCommandObject
{
@@ -81,7 +81,7 @@ TEST( RicfCommands, Test1 )
// std::cout << commandString.toStdString() << std::endl;
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
EXPECT_EQ( (size_t)5, objects.size() );
@@ -139,7 +139,7 @@ TEST( RicfCommands, ErrorMessages )
std::cout << commandString.toStdString() << std::endl;
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
@@ -155,7 +155,7 @@ TEST( RicfCommands, ErrorMessages )
for ( const auto& msg : errors.m_messages )
{
QString label;
if ( msg.first == RicfMessages::MESSAGE_ERROR )
if ( msg.first == caf::PdmScriptIOMessages::MESSAGE_ERROR )
{
label = "Error : ";
}
@@ -181,7 +181,7 @@ TEST( RicfCommands, EmptyArgumentList )
QString commandString( "TestCommand1()" );
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
@@ -216,7 +216,7 @@ TEST( RicfCommands, TransformFileCommandObjectsToExecutableCommandObjects )
)";
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
EXPECT_TRUE( errors.m_messages.empty() );
@@ -253,7 +253,7 @@ TEST( RicfCommands, IgnoreCommentLines )
)";
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
EXPECT_TRUE( errors.m_messages.empty() );
@@ -284,7 +284,7 @@ TEST( RicfCommands, IgnoreCommentLinesShowErrorLine )
)";
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects = RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );
EXPECT_EQ( (size_t)1, errors.m_messages.size() );
@@ -316,7 +316,7 @@ TEST( RicfCommands, WriteCommand )
{
QTextStream inputStream( &commandString );
RicfMessages errors;
caf::PdmScriptIOMessages errors;
auto objects =
RicfCommandFileReader::readCommands( inputStream, caf::PdmDefaultObjectFactory::instance(), &errors );

View File

@@ -483,9 +483,18 @@ void RiuMultiPlotBook::createPages()
page->addPlot( plotWidgets[visibleIndex] );
page->performUpdate();
}
// Set page numbers in title when there's more than one page
if ( m_pages.size() > 1 )
{
for ( int i = 0; i < m_pages.size(); ++i )
{
int pageNumber = i + 1;
m_pages[i]->setPlotTitle( QString( "%1 %2/%3" ).arg( m_plotTitle ).arg( pageNumber ).arg( m_pages.size() ) );
}
}
m_book->adjustSize();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -502,8 +511,7 @@ RiuMultiPlotPage* RiuMultiPlotBook::createPage()
RiuMultiPlotPage* page = new RiuMultiPlotPage( m_plotDefinition, this );
// Reapply plot settings
size_t pageNumber = m_pages.size() + 1;
page->setPlotTitle( QString( "%1 %2/%3" ).arg( m_plotTitle ).arg( pageNumber ).arg( pageNumber ) );
page->setPlotTitle( m_plotTitle );
page->setFontSize( RiaApplication::instance()->preferences()->defaultPlotFontSize() );
page->setTitleVisible( m_titleVisible );
page->setSubTitlesVisible( m_subTitlesVisible );

View File

@@ -382,10 +382,13 @@ add_subdirectory(Fwk/AppFwk/cafUserInterface)
add_subdirectory(Fwk/AppFwk/cafPdmCvf)
add_subdirectory(Fwk/AppFwk/CommonCode)
add_subdirectory(Fwk/AppFwk/cafVizExtensions)
add_subdirectory(Fwk/AppFwk/cafPdmScripting)
set_property(TARGET cafPdmScripting PROPERTY FOLDER "AppFwk")
add_subdirectory(Fwk/AppFwk/cafCommandFeatures)
set_property(TARGET cafCommandFeatures PROPERTY FOLDER "AppFwk")
#add_subdirectory(Fwk/AppFwk/cafTests/cafTestCvfApplication)
add_subdirectory(Fwk/AppFwk/cafTensor)
@@ -406,6 +409,7 @@ list(APPEND APP_FWK_LIBRARIES
cafTensor
CommonCode
cafVizExtensions
cafPdmScripting
)
set_property(TARGET

View File

@@ -47,6 +47,7 @@ add_subdirectory(cafProjectDataModel)
add_subdirectory(cafCommand)
add_subdirectory(cafCommandFeatures)
add_subdirectory(cafUserInterface)
add_subdirectory(cafPdmScripting)
#executables
add_subdirectory(cafTests/cafTestApplication)
@@ -59,6 +60,7 @@ add_subdirectory (cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests)
add_subdirectory (cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests)
add_subdirectory (cafProjectDataModel/cafProjectDataModel_UnitTests)
add_subdirectory (cafUserInterface/cafUserInterface_UnitTests)
#add_subdirectory(cafPdmScripting/cafPdmScripting_UnitTests)
# Organize sub-projects into folders on Visual Studio
# Turn on using solution folders

View File

@@ -63,7 +63,7 @@ QString CmdAddItemExec::name()
if (listField)
{
PdmXmlFieldHandle* xfh = listField->xmlCapability();
containedObjectType = xfh->childClassKeyword();
containedObjectType = xfh->dataTypeName();
}
return QString("Create new '%1'").arg(containedObjectType);
@@ -79,7 +79,7 @@ void CmdAddItemExec::redo()
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField && field->xmlCapability())
{
QString classKeyword = field->xmlCapability()->childClassKeyword();
QString classKeyword = field->xmlCapability()->dataTypeName();
if (classKeyword.isEmpty()) return;

View File

@@ -0,0 +1,34 @@
cmake_minimum_required (VERSION 2.8.12)
project (cafPdmScripting)
set( PROJECT_FILES
cafPdmCodeGenerator.h
cafPdmFieldScriptability.h
cafPdmFieldScriptability.cpp
cafPdmObjectScriptabilityRegister.h
cafPdmObjectScriptabilityRegister.cpp
cafPdmPythonGenerator.h
cafPdmPythonGenerator.cpp
cafPdmScriptIOMessages.h
cafPdmScriptIOMessages.cpp
)
add_library( ${PROJECT_NAME}
${PROJECT_FILES}
)
target_include_directories(${PROJECT_NAME}
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries( ${PROJECT_NAME} cafProjectDataModel ${QT_LIBRARIES} )
source_group("" FILES ${PROJECT_FILES})
# cotire
if (COMMAND caf_apply_cotire)
caf_apply_cotire("${PROJECT_NAME}")
endif()

View File

@@ -0,0 +1,67 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cafFactory.h"
#include <QString>
#define CAF_PDM_CODE_GENERATOR_HEADER_INIT \
public: \
static const std::string& fileExtension();
#define CAF_PDM_CODE_GENERATOR_SOURCE_INIT(ClassName, FileExtension)\
const std::string& ClassName::fileExtension() { static std::string ext = FileExtension; return ext;} \
CAF_FACTORY_REGISTER(caf::PdmCodeGenerator, ClassName, std::string, ClassName::fileExtension())
namespace caf {
class PdmObjectFactory;
//==================================================================================================
/// Abstract skeleton code generator for the Project Data Model
//==================================================================================================
class PdmCodeGenerator
{
public:
virtual QString generate(PdmObjectFactory* factory) const = 0;
};
typedef Factory<PdmCodeGenerator, std::string> PdmCodeGeneratorFactory;
}

View File

@@ -0,0 +1,111 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#include "cafPdmFieldScriptability.h"
#include "cafPdmFieldHandle.h"
using namespace caf;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
PdmFieldScriptability::PdmFieldScriptability(caf::PdmFieldHandle* owner, const QString& scriptFieldName, bool giveOwnership)
{
m_IOWriteable = true;
m_owner = owner;
m_scriptFieldName = scriptFieldName;
owner->addCapability(this, giveOwnership);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
PdmFieldScriptability::~PdmFieldScriptability()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
const QString PdmFieldScriptability::scriptFieldName() const
{
return m_scriptFieldName;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool PdmFieldScriptability::isIOWriteable() const
{
return m_IOWriteable;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptability::setIOWriteable(bool writeable)
{
m_IOWriteable = writeable;
}
//--------------------------------------------------------------------------------------------------
/// Empty default implementation that doesn't offer any script IO for the field
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptability::readFromField(QTextStream& outputStream, bool quoteStrings /*= true*/, bool quoteNonBuiltins /*= false*/) const
{
}
//--------------------------------------------------------------------------------------------------
/// Empty default implementation that doesn't offer any script IO for the field
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptability::writeToField(QTextStream& inputStream, caf::PdmObjectFactory* objectFactory, caf::PdmScriptIOMessages* errorMessageContainer, bool stringsAreQuoted /*= true*/)
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptability::addToField(caf::PdmFieldHandle* field, const QString& fieldName)
{
if (field->template capability<PdmFieldScriptability>() == nullptr)
{
new PdmFieldScriptability(field, fieldName, true);
}
}

View File

@@ -0,0 +1,113 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include <QString>
#include "cafPdmFieldCapability.h"
class QTextStream;
namespace caf {
class PdmFieldHandle;
class PdmObjectFactory;
class PdmScriptIOMessages;
#define CAF_PDM_InitScriptableField( field, keyword, default, uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitField( field, \
keyword, \
default, \
uiName, \
iconResourceName, \
caf::PdmPythonGenerator::pythonHelpString( toolTip, keyword ), \
whatsThis ); \
caf::PdmFieldScriptability::addToField( field, keyword )
#define CAF_PDM_InitScriptableFieldNoDefault( field, keyword, uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitFieldNoDefault( field, \
keyword, \
uiName, \
iconResourceName, \
caf::PdmPythonGenerator::pythonHelpString( toolTip, keyword ), \
whatsThis ); \
caf::PdmFieldScriptability::addToField( field, keyword )
#define CAF_PDM_InitScriptableFieldWithKeyword( field, keyword, scriptKeyword, default, uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitField( field, \
keyword, \
default, \
uiName, \
iconResourceName, \
caf::PdmPythonGenerator::pythonHelpString( toolTip, scriptKeyword ), \
whatsThis ); \
caf::PdmFieldScriptability::addToField( field, scriptKeyword )
#define CAF_PDM_InitScriptableFieldWithKeywordNoDefault( field, keyword, scriptKeyword, uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitFieldNoDefault( field, \
keyword, \
uiName, \
iconResourceName, \
caf::PdmPythonGenerator::pythonHelpString( toolTip, scriptKeyword ), \
whatsThis ); \
caf::PdmFieldScriptability::addToField( field, scriptKeyword )
class PdmFieldScriptability : public PdmFieldCapability
{
public:
PdmFieldScriptability(caf::PdmFieldHandle* owner, const QString& scriptFieldName, bool giveOwnership);
virtual ~PdmFieldScriptability();
const QString scriptFieldName() const;
bool isIOWriteable() const;
void setIOWriteable(bool writeable);
virtual void readFromField(QTextStream& outputStream, bool quoteStrings = true, bool quoteNonBuiltins = false) const;
virtual void writeToField(QTextStream& inputStream,
caf::PdmObjectFactory* objectFactory,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true);
static void addToField(caf::PdmFieldHandle* field, const QString& fieldName);
private:
caf::PdmFieldHandle* m_owner;
QString m_scriptFieldName;
bool m_IOWriteable;
};
}

View File

@@ -0,0 +1,103 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#include "cafPdmObjectScriptabilityRegister.h"
#include "cafPdmObject.h"
using namespace caf;
std::map<QString, QString> PdmObjectScriptabilityRegister::s_classKeywordToScriptClassName;
std::map<QString, QString> PdmObjectScriptabilityRegister::s_scriptClassNameToClassKeyword;
std::map<QString, QString> PdmObjectScriptabilityRegister::s_scriptClassComments;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmObjectScriptabilityRegister::registerScriptClassNameAndComment(const QString& classKeyword,
const QString& scriptClassName,
const QString& scriptClassComment)
{
s_classKeywordToScriptClassName[classKeyword] = scriptClassName;
s_scriptClassNameToClassKeyword[scriptClassName] = classKeyword;
s_scriptClassComments[classKeyword] = scriptClassComment;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmObjectScriptabilityRegister::scriptClassNameFromClassKeyword(const QString& classKeyword)
{
auto it = s_classKeywordToScriptClassName.find(classKeyword);
if (it != s_classKeywordToScriptClassName.end())
{
return it->second;
}
return classKeyword;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmObjectScriptabilityRegister::classKeywordFromScriptClassName(const QString& scriptClassName)
{
auto it = s_scriptClassNameToClassKeyword.find(scriptClassName);
if (it != s_scriptClassNameToClassKeyword.end())
{
return it->second;
}
return scriptClassName;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmObjectScriptabilityRegister::scriptClassComment(const QString& classKeyword)
{
auto it = s_scriptClassComments.find(classKeyword);
if (it != s_scriptClassComments.end())
{
return it->second;
}
return "";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool PdmObjectScriptabilityRegister::isScriptable(const caf::PdmObject* object)
{
return s_classKeywordToScriptClassName.find(object->classKeyword()) != s_classKeywordToScriptClassName.end();
}

View File

@@ -0,0 +1,75 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include <QString>
#include <map>
#define CAF_PDM_InitScriptableObject( uiName, iconResourceName, toolTip, whatsThis ) \
CAF_PDM_InitObject( uiName, iconResourceName, toolTip, whatsThis ); \
caf::PdmObjectScriptabilityRegister::registerScriptClassNameAndComment( classKeyword(), classKeyword(), whatsThis );
#define CAF_PDM_InitScriptableObjectWithNameAndComment( uiName, iconResourceName, toolTip, whatsThis, scriptClassName, scriptComment ) \
CAF_PDM_InitObject( uiName, iconResourceName, toolTip, whatsThis ); \
caf::PdmObjectScriptabilityRegister::registerScriptClassNameAndComment( classKeyword(), scriptClassName, scriptComment );
namespace caf {
class PdmObject;
//==================================================================================================
/// Static register for object scriptability.
//==================================================================================================
class PdmObjectScriptabilityRegister
{
public:
static void registerScriptClassNameAndComment(const QString& classKeyword,
const QString& scriptClassName,
const QString& scriptClassComment);
static QString scriptClassNameFromClassKeyword(const QString& classKeyword);
static QString classKeywordFromScriptClassName(const QString& scriptClassName);
static QString scriptClassComment(const QString& classKeyword);
static bool isScriptable(const caf::PdmObject* object);
private:
static std::map<QString, QString> s_classKeywordToScriptClassName;
static std::map<QString, QString> s_scriptClassNameToClassKeyword;
static std::map<QString, QString> s_scriptClassComments;
};
}

View File

@@ -0,0 +1,406 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#include "cafPdmPythonGenerator.h"
#include "cafPdmChildArrayField.h"
#include "cafPdmChildField.h"
#include "cafPdmFieldScriptability.h"
#include "cafPdmObject.h"
#include "cafPdmObjectFactory.h"
#include "cafPdmObjectScriptabilityRegister.h"
#include "cafPdmProxyValueField.h"
#include "cafPdmXmlFieldHandle.h"
#include <QRegularExpression>
#include <QTextStream>
#include <list>
#include <memory>
#include <set>
using namespace caf;
CAF_PDM_CODE_GENERATOR_SOURCE_INIT(PdmPythonGenerator, "py");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmPythonGenerator::generate(PdmObjectFactory* factory) const
{
QString generatedCode;
QTextStream out(&generatedCode);
std::vector<QString> classKeywords = factory->classKeywords();
std::vector<std::shared_ptr<const PdmObject>> dummyObjects;
for (QString classKeyword : classKeywords)
{
auto objectHandle = factory->create(classKeyword);
const PdmObject* object = dynamic_cast<const PdmObject*>(objectHandle);
CAF_ASSERT(object);
std::shared_ptr<const PdmObject> sharedObject(object);
if (PdmObjectScriptabilityRegister::isScriptable(sharedObject.get()))
{
dummyObjects.push_back(sharedObject);
}
}
// Sort to make sure super classes get created before sub classes
std::sort(dummyObjects.begin(),
dummyObjects.end(),
[](std::shared_ptr<const PdmObject> lhs, std::shared_ptr<const PdmObject> rhs) {
if (lhs->inheritsClassWithKeyword(rhs->classKeyword()))
{
return false;
}
return lhs->classKeyword() < rhs->classKeyword();
});
std::map<QString, std::map<QString, std::pair<QString, QString>>> classAttributesGenerated;
std::map<QString, std::map<QString, QString>> classMethodsGenerated;
std::map<QString, QString> classCommentsGenerated;
// First generate all attributes and comments to go into each object
for (std::shared_ptr<const PdmObject> object : dummyObjects)
{
const std::list<QString>& classInheritanceStack = object->classInheritanceStack();
for (auto it = classInheritanceStack.begin(); it != classInheritanceStack.end(); ++it)
{
const QString& classKeyword = *it;
QString scriptClassComment = PdmObjectScriptabilityRegister::scriptClassComment(classKeyword);
std::map<QString, QString> attributesGenerated;
if (!scriptClassComment.isEmpty()) classCommentsGenerated[classKeyword] = scriptClassComment;
if (classKeyword == object->classKeyword())
{
std::vector<PdmFieldHandle*> fields;
object->fields(fields);
for (auto field : fields)
{
auto scriptability = field->template capability<PdmFieldScriptability>();
if (scriptability != nullptr)
{
QString snake_field_name = camelToSnakeCase(scriptability->scriptFieldName());
QString comment;
{
QStringList commentComponents;
commentComponents << field->capability<PdmUiFieldHandle>()->uiName();
commentComponents << field->capability<PdmUiFieldHandle>()->uiWhatsThis();
commentComponents.removeAll(QString(""));
comment = commentComponents.join(". ");
}
auto pdmValueField = dynamic_cast<const PdmValueField*>(field);
auto pdmChildField = dynamic_cast<const PdmChildFieldHandle*>(field);
auto pdmChildArrayField = dynamic_cast<const PdmChildArrayFieldHandle*>(field);
if (pdmValueField)
{
QString dataType = PdmPythonGenerator::dataTypeString(field, true);
if (field->xmlCapability()->isVectorField())
{
dataType = QString("List of %1").arg(dataType);
}
bool shouldBeMethod = false;
auto proxyField = dynamic_cast<const PdmProxyFieldHandle*>(field);
if (proxyField && proxyField->isStreamingField()) shouldBeMethod = true;
if (classAttributesGenerated[field->ownerClass()].count(snake_field_name)) continue;
if (classMethodsGenerated[field->ownerClass()].count(snake_field_name)) continue;
QVariant valueVariant = pdmValueField->toQVariant();
if (shouldBeMethod)
{
if (proxyField->hasGetter())
{
QString fullComment =
QString(" \"\"\"%1\n Returns:\n %2\n \"\"\"")
.arg(comment)
.arg(dataType);
QString fieldCode = QString(" def %1(self):\n%2\n return "
"self._call_get_method(\"%3\")\n")
.arg(snake_field_name)
.arg(fullComment)
.arg(scriptability->scriptFieldName());
classMethodsGenerated[field->ownerClass()][snake_field_name] = fieldCode;
}
if (proxyField->hasSetter())
{
QString fullComment = QString(" \"\"\"Set %1\n Arguments:\n"
" values (%2): data\n \"\"\"")
.arg(comment)
.arg(dataType);
QString fieldCode = QString(" def set_%1(self, values):\n%2\n "
"self._call_set_method(\"%3\", values)\n")
.arg(snake_field_name)
.arg(fullComment)
.arg(scriptability->scriptFieldName());
classMethodsGenerated[field->ownerClass()][QString("set_%1").arg(snake_field_name)] =
fieldCode;
}
}
else
{
QString valueString;
QTextStream valueStream(&valueString);
scriptability->readFromField(valueStream, true, true);
if (valueString.isEmpty())
valueString = QString("\"\"");
valueString = pythonifyDataValue(valueString);
QString fieldCode = QString(" self.%1 = %2\n").arg(snake_field_name).arg(valueString);
QString fullComment =
QString("%1 (%2): %3\n").arg(snake_field_name).arg(dataType).arg(comment);
classAttributesGenerated[field->ownerClass()][snake_field_name].first = fieldCode;
classAttributesGenerated[field->ownerClass()][snake_field_name].second = fullComment;
}
}
else if (pdmChildField || pdmChildArrayField)
{
QString dataType = PdmPythonGenerator::dataTypeString(field, false);
QString scriptDataType = PdmObjectScriptabilityRegister::scriptClassNameFromClassKeyword(dataType);
QString commentDataType = field->xmlCapability()->isVectorField() ?
QString("List of %1").arg(scriptDataType) : scriptDataType;
QString fullComment =
QString(" \"\"\"%1\n Returns:\n %2\n \"\"\"")
.arg(comment)
.arg(commentDataType);
if (pdmChildField)
{
QString fieldCode = QString(" def %1(self):\n%2\n children = "
"self.children(\"%3\", %4)\n return children[0] if len(children) > 0 else None\n")
.arg(snake_field_name)
.arg(fullComment)
.arg(scriptability->scriptFieldName())
.arg(scriptDataType);
classMethodsGenerated[field->ownerClass()][snake_field_name] = fieldCode;
}
else
{
QString fieldCode = QString(" def %1(self):\n%2\n return "
"self.children(\"%3\", %4)\n")
.arg(snake_field_name)
.arg(fullComment)
.arg(scriptability->scriptFieldName())
.arg(scriptDataType);
classMethodsGenerated[field->ownerClass()][snake_field_name] = fieldCode;
}
}
}
}
}
}
}
// Write out classes
std::set<QString> classesWritten;
for (std::shared_ptr<const PdmObject> object : dummyObjects)
{
const std::list<QString>& classInheritanceStack = object->classInheritanceStack();
std::list<QString> scriptSuperClassNames;
for (auto it = classInheritanceStack.begin(); it != classInheritanceStack.end(); ++it)
{
const QString& classKeyword = *it;
QString scriptClassName = PdmObjectScriptabilityRegister::scriptClassNameFromClassKeyword(classKeyword);
if (scriptClassName.isEmpty()) scriptClassName = classKeyword;
if (!classesWritten.count(scriptClassName))
{
QString classCode;
if (scriptSuperClassNames.empty())
{
classCode = QString("class %1:\n").arg(scriptClassName);
}
else
{
classCode = QString("class %1(%2):\n").arg(scriptClassName).arg(scriptSuperClassNames.back());
}
if (!classCommentsGenerated[classKeyword].isEmpty() || !classAttributesGenerated[classKeyword].empty())
{
classCode += " \"\"\"\n";
if (!classCommentsGenerated[classKeyword].isEmpty())
{
if (!classCommentsGenerated[classKeyword].isEmpty())
{
classCode += QString(" %1\n\n").arg(classCommentsGenerated[classKeyword]);
}
}
if (!classAttributesGenerated[classKeyword].empty())
{
classCode += " Attributes\n";
for (auto keyWordValuePair : classAttributesGenerated[classKeyword])
{
classCode += " " + keyWordValuePair.second.second;
}
}
classCode += " \"\"\"\n";
}
classCode +=
QString(" __custom_init__ = None #: Assign a custom init routine to be run at __init__\n\n");
classCode += QString(" def __init__(self, pb2_object=None, channel=None):\n");
if (!scriptSuperClassNames.empty())
{
// Own attributes. This initializes a lot of attributes to None.
// This means it has to be done before we set any values.
for (auto keyWordValuePair : classAttributesGenerated[classKeyword])
{
classCode += keyWordValuePair.second.first;
}
// Parent constructor
classCode +=
QString(" %1.__init__(self, pb2_object, channel)\n").arg(scriptSuperClassNames.back());
}
classCode += QString(" if %1.__custom_init__ is not None:\n").arg(scriptClassName);
classCode += QString(" %1.__custom_init__(self, pb2_object=pb2_object, channel=channel)\n")
.arg(scriptClassName);
for (auto keyWordValuePair : classMethodsGenerated[classKeyword])
{
classCode += "\n";
classCode += keyWordValuePair.second;
classCode += "\n";
}
out << classCode << "\n";
classesWritten.insert(scriptClassName);
}
scriptSuperClassNames.push_back(scriptClassName);
}
}
out << "def class_dict():\n";
out << " classes = {}\n";
for (QString classKeyword : classesWritten)
{
out << QString(" classes['%1'] = %1\n").arg(classKeyword);
}
out << " return classes\n\n";
out << "def class_from_keyword(class_keyword):\n";
out << " all_classes = class_dict()\n";
out << " if class_keyword in all_classes.keys():\n";
out << " return all_classes[class_keyword]\n";
out << " return None\n";
return generatedCode;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmPythonGenerator::camelToSnakeCase(const QString& camelString)
{
static QRegularExpression re1("(.)([A-Z][a-z]+)");
static QRegularExpression re2("([a-z0-9])([A-Z])");
QString snake_case = camelString;
snake_case.replace(re1, "\\1_\\2");
snake_case.replace(re2, "\\1_\\2");
return snake_case.toLower();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmPythonGenerator::dataTypeString(const PdmFieldHandle* field, bool useStrForUnknownDataTypes)
{
auto xmlObj = field->capability<PdmXmlFieldHandle>();
QString dataType = xmlObj->dataTypeName();
std::map<QString, QString> builtins =
{ {QString::fromStdString(typeid(double).name()), "float"},
{QString::fromStdString(typeid(float).name()), "float"},
{QString::fromStdString(typeid(int).name()), "int"},
{QString::fromStdString(typeid(QString).name()), "str"}
};
bool foundBuiltin = false;
for (auto builtin : builtins)
{
if (dataType == builtin.first)
{
dataType.replace(builtin.first, builtin.second);
foundBuiltin = true;
}
}
if (!foundBuiltin && useStrForUnknownDataTypes)
{
dataType = "str";
}
return dataType;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmPythonGenerator::pythonifyDataValue(const QString& dataValue)
{
QString outValue = dataValue;
outValue.replace("false", "False");
outValue.replace("true", "True");
return outValue;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString PdmPythonGenerator::pythonHelpString(const QString& existingTooltip, const QString& keyword)
{
QString snake_case = caf::PdmPythonGenerator::camelToSnakeCase(keyword);
QString helpString = QString("Available through python/rips as the attribute '%1'").arg(snake_case);
if (!existingTooltip.isEmpty()) return existingTooltip + "\n\n" + helpString;
return helpString;
}

View File

@@ -0,0 +1,60 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cafPdmCodeGenerator.h"
namespace caf {
class PdmFieldHandle;
//==================================================================================================
/// Python skeleton generator from Project Data Model
//==================================================================================================
class PdmPythonGenerator : public PdmCodeGenerator
{
CAF_PDM_CODE_GENERATOR_HEADER_INIT;
public:
QString generate(PdmObjectFactory* factory) const override;
static QString camelToSnakeCase(const QString& camelString);
static QString dataTypeString(const PdmFieldHandle* field, bool useStrForUnknownDataTypes);
static QString pythonifyDataValue(const QString& dataValue);
static QString pythonHelpString(const QString& existingTooltip, const QString& keyword);
};
}

View File

@@ -0,0 +1,110 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#include "cafPdmScriptIOMessages.h"
#include <QTextStream>
using namespace caf;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmScriptIOMessages::addWarning( const QString& message )
{
m_messages.push_back(
std::make_pair( MESSAGE_WARNING, "Line " + QString::number( m_currentLineNumber ) + ": " + message ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmScriptIOMessages::addError( const QString& message )
{
m_messages.push_back(
std::make_pair( MESSAGE_ERROR, "Line " + QString::number( m_currentLineNumber ) + ": " + message ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmScriptIOMessages::skipWhiteSpaceWithLineNumberCount( QTextStream& inputStream )
{
while ( !inputStream.atEnd() )
{
QChar ch = readCharWithLineNumberCount( inputStream );
if ( !ch.isSpace() )
{
inputStream.seek( inputStream.pos() - 1 );
break;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QChar PdmScriptIOMessages::readCharWithLineNumberCount( QTextStream& inputStream )
{
QChar ch;
inputStream >> ch;
if ( ch == QChar( '\n' ) )
{
m_currentLineNumber++;
}
return ch;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QChar PdmScriptIOMessages::peekNextChar( QTextStream& inputStream )
{
QChar ch;
if ( !inputStream.atEnd() )
{
inputStream >> ch;
inputStream.seek( inputStream.pos() - 1 );
}
return ch;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmScriptIOMessages::skipLineWithLineNumberCount( QTextStream& inputStream )
{
inputStream.readLine();
m_currentLineNumber++;
}

View File

@@ -0,0 +1,76 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library 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>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include <QString>
#include <vector>
class QTextStream;
namespace caf {
class PdmScriptIOMessages
{
public:
PdmScriptIOMessages()
: m_currentLineNumber( 1 )
{
}
enum MessageType
{
MESSAGE_WARNING,
MESSAGE_ERROR
};
void addWarning( const QString& message );
void addError( const QString& message );
void skipWhiteSpaceWithLineNumberCount( QTextStream& inputStream );
void skipLineWithLineNumberCount( QTextStream& inputStream );
QChar readCharWithLineNumberCount( QTextStream& inputStream );
QChar peekNextChar( QTextStream& inputStream );
QString currentCommand;
QString currentArgument;
std::vector<std::pair<MessageType, QString>> m_messages;
private:
int m_currentLineNumber;
};
}

View File

@@ -19,6 +19,7 @@ template< typename T> class PdmFieldXmlCap;
class PdmChildFieldHandle : public PdmFieldHandle
{
public:
virtual void childObjects(std::vector<PdmObjectHandle*>* objects) = 0;
virtual void setChildObject(PdmObjectHandle* object) = 0;
};

View File

@@ -45,6 +45,7 @@
#include <QVariant>
#include <typeinfo>
#include <vector>
@@ -62,6 +63,10 @@ template<typename DataType >
class PdmDataValueField : public PdmValueField
{
public:
// Type traits magic to check if a template argument is a vector
template<typename T> struct is_vector : public std::false_type {};
template<typename T, typename A> struct is_vector<std::vector<T, A>> : public std::true_type {};
typedef DataType FieldDataType;
PdmDataValueField() {}
PdmDataValueField(const PdmDataValueField& other) { m_fieldValue = other.m_fieldValue; }
@@ -95,6 +100,7 @@ public:
bool operator== (const DataType& fieldValue) const { return m_fieldValue == fieldValue; }
bool operator!= (const DataType& fieldValue) const { return m_fieldValue != fieldValue; }
protected:
DataType m_fieldValue;

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