diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.cpp index e01cb709b2..d0d72fee6e 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.cpp +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.cpp @@ -281,14 +281,6 @@ bool RimPolygonCloudAddress::canAddSubCollection() const return false; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimPolygonContainer* RimPolygonCloudAddress::addNewSubCollection() -{ - return nullptr; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.h b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.h index 23188db1f0..86763b3e8d 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.h +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudAddress.h @@ -83,8 +83,7 @@ public: QString name() const; - bool canAddSubCollection() const override; - RimPolygonContainer* addNewSubCollection() override; + bool canAddSubCollection() const override; protected: void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.cpp index 5c55e8c770..126b73db85 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.cpp +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.cpp @@ -54,11 +54,3 @@ bool RimPolygonCloudFolder::canAddSubCollection() const { return false; } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimPolygonContainer* RimPolygonCloudFolder::addNewSubCollection() -{ - return nullptr; -} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.h b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.h index c05c71d409..1f9bebdacb 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.h +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudFolder.h @@ -35,6 +35,5 @@ public: RimPolygonCloudFolder(); explicit RimPolygonCloudFolder( const QString& folderName ); - bool canAddSubCollection() const override; - RimPolygonContainer* addNewSubCollection() override; + bool canAddSubCollection() const override; }; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.cpp index 7129b47ac6..f8cf4296ea 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.cpp +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.cpp @@ -201,14 +201,6 @@ bool RimPolygonCloudSource::canAddSubCollection() const return false; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimPolygonContainer* RimPolygonCloudSource::addNewSubCollection() -{ - return nullptr; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.h b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.h index 4e1223ecc8..8cffc55bda 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.h +++ b/ApplicationLibCode/ProjectDataModel/Polygons/Cloud/RimPolygonCloudSource.h @@ -78,8 +78,7 @@ public: // other than this source's own applied base one. QString nameForRealization( int realization ) const; - bool canAddSubCollection() const override; - RimPolygonContainer* addNewSubCollection() override; + bool canAddSubCollection() const override; bool supportsRealizationOverride() const override; std::vector availableRealizationIdsForOverride() const override; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.cpp index c8e8f0c332..d1dfc5ea6f 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.cpp +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.cpp @@ -40,7 +40,16 @@ RimPolygonContainer::RimPolygonContainer() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimPolygonContainer* RimPolygonContainer::addNewSubCollection() +QString RimPolygonContainer::subCollectionClassKeyword() const +{ + if ( !canAddSubCollection() ) return {}; + return RimPolygonCollection::classKeywordStatic(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonContainer* RimPolygonContainer::createSubCollection() { auto* sub = new RimPolygonCollection(); addSubCollection( sub ); diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.h index e7ccec9720..9b46a30d19 100644 --- a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.h +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonContainer.h @@ -39,9 +39,8 @@ class RimPolygonContainer : public caf::PdmNestedCollection RimcNestedCollectionBase::execute() { auto* coll = self(); + // Checked before the name conflict policy runs, since OVERWRITE deletes an existing folder. if ( !coll || !coll->canAddSubCollection() ) { return std::unexpected( "Cannot add subfolder" ); @@ -69,16 +72,13 @@ std::expected RimcNestedCollectionBase::execute( } } - caf::PdmObject* added = coll->addNewSubCollection(); + caf::PdmNestedCollectionBase* added = coll->addNewSubCollection(); if ( !added ) { return std::unexpected( "Failed to add subfolder" ); } - if ( auto* asNested = dynamic_cast( added ) ) - { - asNested->setCollectionName( resolution.nameToUse ); - } + added->setCollectionName( resolution.nameToUse ); coll->uiCapability()->updateConnectedEditors(); return added; } @@ -88,10 +88,54 @@ std::expected RimcNestedCollectionBase::execute( //-------------------------------------------------------------------------------------------------- QString RimcNestedCollectionBase::classKeywordReturnedType() const { - // Returned at codegen time. The Python generator emits AddFolder on the - // PdmNestedCollectionBase Python class (since that is where the method is registered), - // so the declared return type must be stable across all concrete nested collections. - // The actual runtime instance is whatever the concrete addNewSubCollection() returns; - // callers can use descendants() / class_from_keyword to recover the precise type. + // The method is registered on PdmNestedCollectionBase, so this is the type the Python generator + // declares for PdmNestedCollectionBase.add_folder(). It must not depend on self(): the generator + // creates the method once per concrete collection and would otherwise keep the type of whichever + // collection it visited last. The concrete type is reported by classKeywordReturnedTypeForSelf() + // and emitted as a typed override on the concrete class. return caf::PdmNestedCollectionBase::classKeywordStatic(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimcNestedCollectionBase::classKeywordReturnedTypeForSelf() const +{ + auto* coll = self(); + if ( !coll ) return classKeywordReturnedType(); + + QString keyword = coll->subCollectionClassKeyword(); + return keyword.isEmpty() ? classKeywordReturnedType() : keyword; +} + +CAF_PDM_OBJECT_METHOD_SOURCE_INIT( caf::PdmNestedCollectionBase, RimcNestedCollectionBase_collectionName, "CollectionNameInternal" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimcNestedCollectionBase_collectionName::RimcNestedCollectionBase_collectionName( caf::PdmObjectHandle* self ) + : caf::PdmObjectMethod( self, PdmObjectMethod::NullPointerType::NULL_IS_INVALID, PdmObjectMethod::ResultType::PERSISTENT_FALSE ) +{ + CAF_PDM_InitObject( "Collection Name", "", "", "Name of the folder" ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::expected RimcNestedCollectionBase_collectionName::execute() +{ + auto* coll = self(); + if ( !coll ) return std::unexpected( "Not a folder" ); + + auto* result = new RimcDataContainerString(); + result->m_stringValues = { coll->collectionName() }; + return result; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimcNestedCollectionBase_collectionName::classKeywordReturnedType() const +{ + return RimcDataContainerString::classKeywordStatic(); +} diff --git a/ApplicationLibCode/ProjectDataModelCommands/RimcNestedCollectionBase.h b/ApplicationLibCode/ProjectDataModelCommands/RimcNestedCollectionBase.h index b8ab6e992c..046a4654a8 100644 --- a/ApplicationLibCode/ProjectDataModelCommands/RimcNestedCollectionBase.h +++ b/ApplicationLibCode/ProjectDataModelCommands/RimcNestedCollectionBase.h @@ -43,8 +43,26 @@ public: std::expected execute() override; QString classKeywordReturnedType() const override; + QString classKeywordReturnedTypeForSelf() const override; private: caf::PdmField m_folderName; caf::PdmField> m_onNameConflict; }; + +//================================================================================================== +/// +/// Name of the folder, the same for every nested collection whichever class owns the name field. +/// Exposed in Python as PdmNestedCollectionBase.collection_name() (rips/nested_collection.py). +/// +//================================================================================================== +class RimcNestedCollectionBase_collectionName : public caf::PdmObjectMethod +{ + CAF_PDM_HEADER_INIT; + +public: + RimcNestedCollectionBase_collectionName( caf::PdmObjectHandle* self ); + + std::expected execute() override; + QString classKeywordReturnedType() const override; +}; diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.cpp b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.cpp index 18cddefa4c..7776195cba 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.cpp +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.cpp @@ -74,6 +74,14 @@ QString PdmObjectMethod::classKeywordReturnedType() const return {}; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString PdmObjectMethod::classKeywordReturnedTypeForSelf() const +{ + return classKeywordReturnedType(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h index adcaa7fd77..d7e03fdbdd 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h @@ -88,6 +88,12 @@ public: virtual QString selfClassKeyword() const; virtual QString classKeywordReturnedType() const = 0; + /// Return type when the method is called on the concrete class of self(). Defaults to + /// classKeywordReturnedType(). A method registered on a base class overrides this when its + /// result type narrows per subclass; the Python generator then emits a typed override of the + /// method on that subclass, while the base class keeps classKeywordReturnedType(). + virtual QString classKeywordReturnedTypeForSelf() const; + /// Optional metadata describing an enum return value. When returnEnumScriptName() is non-empty /// the Python code generator emits a StrEnum class with the listed texts and wraps the call /// site so the caller receives a typed enum value rather than the raw container. execute() @@ -109,6 +115,14 @@ protected: return object; } + template + const PdmObjectType* self() const + { + const PdmObjectType* object = dynamic_cast( m_self.p() ); + CAF_ASSERT( object ); + return object; + } + private: friend class PdmObjectScriptingCapability; PdmPointer m_self; diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmPythonGenerator.cpp b/Fwk/AppFwk/cafPdmScripting/cafPdmPythonGenerator.cpp index 773eb99dd4..949d45874c 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmPythonGenerator.cpp +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmPythonGenerator.cpp @@ -57,6 +57,7 @@ #include #include +#include #include #include #include @@ -72,19 +73,33 @@ void appendCodeForMethod( std::map>& classMe const std::list& classInheritanceStack, const QString& classKeyword, const QString& methodName, - const QString& sourceCode ) + const QString& sourceCode, + bool isReturnTypeOverride ) { + // A return type override is the super class method emitted again on a subclass, with the same arguments and a + // return type that is a subclass of the declared one. The caller builds it from the same PdmObjectMethod as the + // super class method and has checked the return types, so it is accepted whether or not the super class method + // has been generated yet (see PdmObjectMethod::classKeywordReturnedTypeForSelf). + if ( isReturnTypeOverride ) + { + classMethods[classKeyword][methodName] = sourceCode; + return; + } + // Check if method already exists in any super class. This is not supported, and causes the generated // Python code to silently ignore the second version of the source code. Show an error message and assert will be // issued. It is difficult to trap this error earlier. The method names are registered with the macro // CAF_PDM_OBJECT_METHOD_SOURCE_INIT, and this macro does not have access to the class inheritance structure. // See "cafPdmObjectMethod.h" // https://github.com/OPM/ResInsight/issues/12972 + // + // The stack runs from the root class to the concrete class, so only the entries before classKeyword are super + // classes. The entries after it are subclasses, which may already carry a return type override of this method. for ( auto it = classInheritanceStack.begin(); it != classInheritanceStack.end(); ++it ) { const auto& superClassKeyword = *it; - if ( superClassKeyword == classKeyword ) continue; + if ( superClassKeyword == classKeyword ) break; if ( classMethods[superClassKeyword].contains( methodName ) ) { @@ -145,6 +160,12 @@ QString caf::PdmPythonGenerator::generate( PdmObjectFactory* factory, std::vecto return lhs->classKeyword() < rhs->classKeyword(); } ); + std::map dummyObjectByKeyword; + for ( const auto& object : dummyObjects ) + { + dummyObjectByKeyword[object->classKeyword()] = object.get(); + } + std::map>> classAttributesGenerated; std::map> classMethodsGenerated; std::map classCommentsGenerated; @@ -639,8 +660,11 @@ QString caf::PdmPythonGenerator::generate( PdmObjectFactory* factory, std::vecto argumentComments.push_back( QString( "%1 (%2): %3" ).arg( argumentName ).arg( dataType ).arg( commentOrEnumDescription ) ); } - QString fullComment = QString( " \"\"\"\n %1\n\n Arguments:\n " - "%2\n Returns:\n %3\n \"\"\"" ) + const QString commentTemplate = " \"\"\"\n %1\n\n Arguments:\n " + "%2\n Returns:\n %3\n \"\"\""; + const QString methodTemplate = " def %1(self, %2) -> %3:\n%4\n %5\n"; + + QString fullComment = QString( commentTemplate ) .arg( methodComment ) .arg( argumentComments.join( "\n " ) ) .arg( returnComment ); @@ -668,7 +692,7 @@ QString caf::PdmPythonGenerator::generate( PdmObjectFactory* factory, std::vecto } } - QString methodCode = QString( " def %1(self, %2) -> %3:\n%4\n %5\n" ) + QString methodCode = QString( methodTemplate ) .arg( snake_method_name ) .arg( inputArgumentStrings.join( ", " ) ) .arg( returnDataType ) @@ -679,7 +703,80 @@ QString caf::PdmPythonGenerator::generate( PdmObjectFactory* factory, std::vecto classInheritanceStack, classKeyword, snake_method_name, - methodCode ); + methodCode, + false ); + + // A method registered on a base class may narrow its return type on a concrete class (AddFolder on + // PdmNestedCollectionBase returns a SurfaceCollection when called on one). The base class keeps the + // declared type; the concrete class gets a typed override, emitted once in the hierarchy: not when + // the direct super class already reports the same type. Enum returns are unwrapped above and do not + // narrow. + QString selfReturnKeyword = method->classKeywordReturnedTypeForSelf(); + if ( classKeyword != object->classKeyword() && returnEnumClassName.isEmpty() && + !method->classKeywordReturnedType().isEmpty() && !selfReturnKeyword.isEmpty() && + selfReturnKeyword != method->classKeywordReturnedType() ) + { + auto narrowedIt = dummyObjectByKeyword.find( selfReturnKeyword ); + if ( narrowedIt == dummyObjectByKeyword.end() || + !narrowedIt->second->inheritsClassWithKeyword( method->classKeywordReturnedType() ) ) + { + errorMessages.push_back( QString( "Method '%1' on '%2' returns '%3', which is not a scriptable " + "subclass of the declared return type '%4'." ) + .arg( methodName ) + .arg( object->classKeyword() ) + .arg( selfReturnKeyword ) + .arg( method->classKeywordReturnedType() ) ); + continue; + } + + if ( classInheritanceStack.size() > 1 ) + { + auto superIt = dummyObjectByKeyword.find( *std::next( classInheritanceStack.rbegin() ) ); + if ( superIt != dummyObjectByKeyword.end() ) + { + auto superMethod = + PdmObjectMethodFactory::instance()->createMethod( superIt->second, methodName ); + if ( superMethod && superMethod->classKeywordReturnedTypeForSelf() == selfReturnKeyword ) + continue; + } + } + + QString overrideClassName = + PdmObjectScriptingCapabilityRegister::scriptClassNameFromClassKeyword( selfReturnKeyword ); + if ( overrideClassName.isEmpty() ) overrideClassName = selfReturnKeyword; + + QStringList overrideArguments = outputArgumentStrings; + overrideArguments[1] = overrideClassName; + + QString overrideReturnType = overrideClassName; + QString overrideBody = + QString( "return self._call_pdm_method_return_value(%1)" ).arg( overrideArguments.join( ", " ) ); + if ( method->isNullptrValidResult() ) + { + overrideReturnType = QString( "Optional[%1]" ).arg( overrideClassName ); + overrideBody = QString( "return self._call_pdm_method_return_optional_value(%1)" ) + .arg( overrideArguments.join( ", " ) ); + } + + QString overrideComment = QString( commentTemplate ) + .arg( methodComment ) + .arg( argumentComments.join( "\n " ) ) + .arg( overrideClassName ); + + QString overrideCode = QString( methodTemplate ) + .arg( snake_method_name ) + .arg( inputArgumentStrings.join( ", " ) ) + .arg( overrideReturnType ) + .arg( overrideComment ) + .arg( overrideBody ); + + internal::appendCodeForMethod( classMethodsGenerated, + classInheritanceStack, + object->classKeyword(), + snake_method_name, + overrideCode, + true ); + } } } } diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmPythonGeneratorTest.cpp b/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmPythonGeneratorTest.cpp index c6d85de548..c7c4b129be 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmPythonGeneratorTest.cpp +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmPythonGeneratorTest.cpp @@ -38,8 +38,62 @@ #include "cafMockObjects.h" #include "cafPdmDefaultObjectFactory.h" +#include "cafPdmObjectMethod.h" +#include "cafPdmObjectScriptingCapability.h" #include "cafPdmPythonGenerator.h" +namespace caf +{ +//================================================================================================== +/// A method registered on a base class whose return type narrows to the concrete class of self. +//================================================================================================== +class NarrowingReturnBaseObj : public caf::PdmObject +{ + CAF_PDM_HEADER_INIT; + +public: + NarrowingReturnBaseObj() { CAF_PDM_InitScriptableObject( "Narrowing Return Base" ); } +}; +CAF_PDM_SOURCE_INIT( NarrowingReturnBaseObj, "NarrowingReturnBaseObj" ); + +class NarrowingReturnDerivedObj : public NarrowingReturnBaseObj +{ + CAF_PDM_HEADER_INIT; + +public: + NarrowingReturnDerivedObj() { CAF_PDM_InitScriptableObject( "Narrowing Return Derived" ); } +}; +CAF_PDM_SOURCE_INIT( NarrowingReturnDerivedObj, "NarrowingReturnDerivedObj" ); + +// Third level: the base method is generated again through this class's inheritance stack after the +// derived class already carries its override. +class NarrowingReturnGrandchildObj : public NarrowingReturnDerivedObj +{ + CAF_PDM_HEADER_INIT; + +public: + NarrowingReturnGrandchildObj() { CAF_PDM_InitScriptableObject( "Narrowing Return Grandchild" ); } +}; +CAF_PDM_SOURCE_INIT( NarrowingReturnGrandchildObj, "NarrowingReturnGrandchildObj" ); + +class NarrowingReturnBaseObj_clone : public caf::PdmObjectCreationMethod +{ + CAF_PDM_HEADER_INIT; + +public: + NarrowingReturnBaseObj_clone( caf::PdmObjectHandle* self ) + : caf::PdmObjectCreationMethod( self ) + { + CAF_PDM_InitObject( "Clone", "", "", "Clone" ); + } + + std::expected execute() override { return std::unexpected( "Not used" ); } + QString classKeywordReturnedType() const override { return NarrowingReturnBaseObj::classKeywordStatic(); } + QString classKeywordReturnedTypeForSelf() const override { return selfClassKeyword(); } +}; +CAF_PDM_OBJECT_METHOD_SOURCE_INIT( NarrowingReturnBaseObj, NarrowingReturnBaseObj_clone, "Clone" ); +} // namespace caf + //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- TEST( PdmPythonGenerator, CamelToSnakeCase_SimpleCamel ) @@ -252,3 +306,37 @@ TEST( PdmPythonGenerator, RejectsEnumClassNamesThatConflictWithModuleNames ) EXPECT_TRUE( errorMessages.front().contains( "CollisionTestPdmObject.Type" ) ); EXPECT_TRUE( errorMessages.front().contains( "PdmScriptEnumNameRegistry" ) ); } + +//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------------------------- +TEST( PdmPythonGenerator, EmitsTypedOverrideWhenReturnTypeNarrowsOnSubclass ) +{ + caf::PdmPythonGenerator generator; + std::vector errorMessages; + QString generatedCode = generator.generate( caf::PdmDefaultObjectFactory::instance(), errorMessages ); + + EXPECT_TRUE( errorMessages.empty() ); + + int baseClassStart = generatedCode.indexOf( "class NarrowingReturnBaseObj(" ); + int derivedClassStart = generatedCode.indexOf( "class NarrowingReturnDerivedObj(" ); + ASSERT_NE( -1, baseClassStart ); + ASSERT_NE( -1, derivedClassStart ); + ASSERT_LT( baseClassStart, derivedClassStart ); + + int grandchildClassStart = generatedCode.indexOf( "class NarrowingReturnGrandchildObj(" ); + ASSERT_LT( derivedClassStart, grandchildClassStart ); + + int grandchildClassEnd = generatedCode.indexOf( "\nclass ", grandchildClassStart ); + if ( grandchildClassEnd == -1 ) grandchildClassEnd = generatedCode.size(); + + QString baseClassCode = generatedCode.mid( baseClassStart, derivedClassStart - baseClassStart ); + QString derivedClassCode = generatedCode.mid( derivedClassStart, grandchildClassStart - derivedClassStart ); + QString grandchildClassCode = generatedCode.mid( grandchildClassStart, grandchildClassEnd - grandchildClassStart ); + + // The base class keeps the declared type, each subclass gets a typed override of the same method + EXPECT_TRUE( baseClassCode.contains( "def clone(self, ) -> NarrowingReturnBaseObj:" ) ); + EXPECT_TRUE( baseClassCode.contains( "_call_pdm_method_return_value(\"Clone\", NarrowingReturnBaseObj)" ) ); + EXPECT_TRUE( derivedClassCode.contains( "def clone(self, ) -> NarrowingReturnDerivedObj:" ) ); + EXPECT_TRUE( derivedClassCode.contains( "_call_pdm_method_return_value(\"Clone\", NarrowingReturnDerivedObj)" ) ); + EXPECT_TRUE( grandchildClassCode.contains( "def clone(self, ) -> NarrowingReturnGrandchildObj:" ) ); +} diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.h index 2b5599352f..966e5c0108 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.h @@ -73,7 +73,7 @@ public: // Subcollection CRUD void addSubCollection( SelfT* sub ); - PdmObject* addNewSubCollection() override; + QString subCollectionClassKeyword() const override; PdmChildArrayFieldHandle* subCollectionsField() override; SelfT* findSubCollectionByName( const QString& name ) const; @@ -88,6 +88,11 @@ protected: // Hook for derived classes; called when m_items changes. virtual void onItemsChanged(); + // Creates a SelfT. A collection whose folders are a different class overrides this together + // with subCollectionClassKeyword(). Not covariant: SelfT is incomplete where the CRTP base is + // instantiated. + PdmNestedCollectionBase* createSubCollection() override; + void fieldChangedByUi( const PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void defineUiOrdering( QString uiConfigName, PdmUiOrdering& uiOrdering ) override; void onChildDeleted( PdmChildArrayFieldHandle* childArray, std::vector& referringObjects ) override; diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.inl b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.inl index 3b67108619..a1c1da46a7 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.inl +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollection.inl @@ -190,7 +190,17 @@ void PdmNestedCollection::addSubCollection( SelfT* sub ) /// //-------------------------------------------------------------------------------------------------- template -PdmObject* PdmNestedCollection::addNewSubCollection() +QString PdmNestedCollection::subCollectionClassKeyword() const +{ + if ( !this->canAddSubCollection() ) return {}; + return SelfT::classKeywordStatic(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +template +PdmNestedCollectionBase* PdmNestedCollection::createSubCollection() { auto* sub = new SelfT(); addSubCollection( sub ); diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.cpp index ae55126e2f..9198c26a1a 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.cpp @@ -77,6 +77,15 @@ void PdmNestedCollectionBase::setCollectionName( const QString& name ) m_collectionName.setValue( name ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +PdmNestedCollectionBase* PdmNestedCollectionBase::addNewSubCollection() +{ + if ( !canAddSubCollection() ) return nullptr; + return createSubCollection(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.h index 26ef90e5eb..ac3088285e 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmNestedCollectionBase.h @@ -35,9 +35,9 @@ class PdmChildArrayFieldHandle; /// generic command features and script methods need. The templated caf::PdmNestedCollection<> /// derives from this and supplies typed storage and accessors. /// -/// Concrete (instantiable) so the CAF factory can create a dummy instance for the Python -/// generator. The base's addNewSubCollection() is a no-op returning nullptr; the templated -/// derived class overrides it with a real implementation. +/// Abstract: the sub-collection type, its creation and the field holding the sub-collections are +/// pure virtuals that caf::PdmNestedCollection<> implements. Registered with +/// CAF_PDM_ABSTRACT_SOURCE_INIT so the Python generator still places the generic methods here. /// //================================================================================================== class PdmNestedCollectionBase : public PdmObject @@ -56,20 +56,27 @@ public: // action when this is false. virtual bool canAddSubCollection() const { return true; } - // Creates a subcollection, adds it to this collection, and returns it. Default returns - // nullptr; concrete derivations (typically PdmNestedCollection<>) override. - virtual PdmObject* addNewSubCollection() { return nullptr; } + // Class keyword of the folder created by addNewSubCollection(). Empty when canAddSubCollection() + // is false. Has no side effects, so the Python generator can read the folder type from it. + virtual QString subCollectionClassKeyword() const = 0; + + // Creates a subcollection, adds it to this collection, and returns it. Returns nullptr when + // canAddSubCollection() is false, otherwise delegates to createSubCollection(). + PdmNestedCollectionBase* addNewSubCollection(); // Type-erased access to the field holding the sub-collections, for generic code that must - // inspect the folders without knowing the concrete collection type. Default returns nullptr; - // PdmNestedCollection<> overrides. - virtual PdmChildArrayFieldHandle* subCollectionsField() { return nullptr; } + // inspect the folders without knowing the concrete collection type. + virtual PdmChildArrayFieldHandle* subCollectionsField() = 0; // Marks this instance as the topmost folder: hides and disables IO on the collection name, // makes the object non-deletable. void setAsTopmostFolder(); protected: + // Creates the subcollection, adds it to this collection, and returns it. Called by + // addNewSubCollection() when canAddSubCollection() is true. + virtual PdmNestedCollectionBase* createSubCollection() = 0; + PdmFieldHandle* userDescriptionField() override; PdmField m_collectionName; diff --git a/GrpcInterface/Python/rips/__init__.py b/GrpcInterface/Python/rips/__init__.py index fa7ecc1907..d96340f20a 100644 --- a/GrpcInterface/Python/rips/__init__.py +++ b/GrpcInterface/Python/rips/__init__.py @@ -30,6 +30,7 @@ from .surface import RegularSurface as RegularSurface # noqa: E402 from . import well_events as well_events # noqa: F401, E402 from . import category_mapping as category_mapping # noqa: F401, E402 from . import summary_ensemble as summary_ensemble # noqa: F401, E402 +from . import nested_collection as nested_collection # noqa: F401, E402 __all__: List[str] = [] for key in class_dict(): # noqa: F405 diff --git a/GrpcInterface/Python/rips/nested_collection.py b/GrpcInterface/Python/rips/nested_collection.py new file mode 100644 index 0000000000..45f59ddf39 --- /dev/null +++ b/GrpcInterface/Python/rips/nested_collection.py @@ -0,0 +1,15 @@ +from .pdmobject import add_method +from .resinsight_classes import PdmNestedCollectionBase + + +@add_method(PdmNestedCollectionBase) +def collection_name(self: PdmNestedCollectionBase) -> str: + """Get the name of this folder + + The same for every folder class. The class specific attributes + (surface_user_description, polygon_collection_name) remain for existing scripts. + + Returns: + The folder name + """ + return self.collection_name_internal().values[0] diff --git a/GrpcInterface/Python/rips/tests/test_polygon.py b/GrpcInterface/Python/rips/tests/test_polygon.py index 154f72b673..e822e2f43b 100644 --- a/GrpcInterface/Python/rips/tests/test_polygon.py +++ b/GrpcInterface/Python/rips/tests/test_polygon.py @@ -1,6 +1,7 @@ import sys import os import math +import typing import pytest @@ -158,3 +159,22 @@ def test_folder_name_uniqueness(rips_instance, initialize_test): on_name_conflict=rips.NameConflictPolicy.AUTO_RENAME, ) assert renamed.polygon_collection_name == "Folder A_1" + + +def test_add_folder_returns_polygon_collection(rips_instance, initialize_test): + rips_instance.project.open( + dataroot.PATH + "/TEST10K_FLT_LGR_NNC/10KWithWellLog.rsp" + ) + + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + folder = root.add_folder(folder_name="Folder A") + assert type(folder) is rips.PolygonCollection + assert folder.collection_name() == "Folder A" + assert folder.polygon_collection_name == "Folder A" + + # The generated classes declare the concrete folder type on each collection class + assert ( + typing.get_type_hints(rips.PolygonCollection.add_folder)["return"] + is rips.PolygonCollection + ) diff --git a/GrpcInterface/Python/rips/tests/test_surfaces.py b/GrpcInterface/Python/rips/tests/test_surfaces.py index e1f0c37535..37f300542d 100644 --- a/GrpcInterface/Python/rips/tests/test_surfaces.py +++ b/GrpcInterface/Python/rips/tests/test_surfaces.py @@ -1,6 +1,7 @@ import sys import os import tempfile +import typing import pytest from pathlib import Path @@ -367,3 +368,28 @@ def test_surface_folder_lookup(rips_instance, initialize_test): rips_instance.project.surface_folder("Folder A").address() == folder.address() ) assert rips_instance.project.surface_folder("Missing") is None + + +def test_add_folder_returns_surface_collection(rips_instance, initialize_test): + case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID" + rips_instance.project.load_case(path=case_path) + surface_collection = rips_instance.project.descendants(rips.SurfaceCollection)[0] + + folder = surface_collection.add_folder(folder_name="Folder A") + assert type(folder) is rips.SurfaceCollection + assert folder.collection_name() == "Folder A" + assert folder.surface_user_description == "Folder A" + + # The generated classes declare the concrete folder type on each collection class + assert ( + typing.get_type_hints(rips.SurfaceCollection.add_folder)["return"] + is rips.SurfaceCollection + ) + assert ( + typing.get_type_hints(rips.EnsembleSurface.add_folder)["return"] + is rips.SurfaceCollection + ) + assert ( + typing.get_type_hints(rips.PdmNestedCollectionBase.add_folder)["return"] + is rips.PdmNestedCollectionBase + )