#14772 Python: Add snapshot export object methods and forward exportSnapshots to them

- Add RimViewWindow_exportSnapshot on RimViewWindow (3D views and
  plots) with explicit ExportFolder, Prefix, Width, Height and
  FileFormat parameters. Generated as ViewWindow.export_snapshot().
- Add RimProject_exportSnapshots for exporting all views and/or plots
  with a ContentType parameter. Generated as Project.export_snapshots().
- Add RiaDefines::SnapshotFileFormat and SnapshotContentType enums,
  registered as Python StrEnums.
- Extract single-item exportSnapshotOfView()/exportSnapshotOfPlot()
  from the RicSnapshotAll*ToFileFeature loops so the object methods
  and the legacy loops share the implementation.
- RicfExportSnapshots resolves the export folder from the command file
  executor and forwards to the object methods.

Python: the hand-written ViewWindow.export_snapshot() wrapper is
removed (generated method is compatible). PlotWindow.export_snapshot()
and Project.export_snapshots() keep their legacy argument names
(file_prefix, output_format, snapshot_type, plot_format) as deprecated
aliases. Case.export_snapshots_of_all_views() is deprecated in favor
of View.export_snapshot().

Also fix Case.views(), which compared the view id to the case id and
therefore never returned any views.
This commit is contained in:
Kristian Bendiksen committed 2026-09-22 14:19:23 +02:00
1 parent ee28576c48
commit 77c32a3fa5
17 files changed
+711 -170

No files matched your search

@@ -188,6 +188,23 @@ void caf::AppEnum<RiaDefines::NameConflictPolicy>::setUp()
setDefault( RiaDefines::NameConflictPolicy::FAIL );
}
template <>
void caf::AppEnum<RiaDefines::SnapshotFileFormat>::setUp()
{
addItem( RiaDefines::SnapshotFileFormat::PNG, "PNG", "PNG" );
addItem( RiaDefines::SnapshotFileFormat::PDF, "PDF", "PDF" );
setDefault( RiaDefines::SnapshotFileFormat::PNG );
}
template <>
void caf::AppEnum<RiaDefines::SnapshotContentType>::setUp()
{
addItem( RiaDefines::SnapshotContentType::ALL, "ALL", "All" );
addItem( RiaDefines::SnapshotContentType::VIEWS, "VIEWS", "Views" );
addItem( RiaDefines::SnapshotContentType::PLOTS, "PLOTS", "Plots" );
setDefault( RiaDefines::SnapshotContentType::ALL );
}
} // namespace caf
namespace
@@ -202,6 +219,8 @@ struct RegisterScriptEnumNames
caf::PdmScriptEnumNameRegistry::registerName<RiaDefines::ResultCatType>( "PropertyType" );
caf::PdmScriptEnumNameRegistry::registerName<RiaDefines::PorosityModelType>( "PorosityModelType" );
caf::PdmScriptEnumNameRegistry::registerName<RiaDefines::NameConflictPolicy>( "NameConflictPolicy" );
caf::PdmScriptEnumNameRegistry::registerName<RiaDefines::SnapshotFileFormat>( "SnapshotFileFormat" );
caf::PdmScriptEnumNameRegistry::registerName<RiaDefines::SnapshotContentType>( "SnapshotContentType" );
}
};
const RegisterScriptEnumNames s_registerScriptEnumNames;
@@ -275,6 +275,19 @@ enum class ItemIn3dView
ALL = 0b00000111
};
enum class SnapshotFileFormat
{
PNG,
PDF
};
enum class SnapshotContentType
{
ALL,
VIEWS,
PLOTS
};
QString betaFeaturePostfix();
}; // namespace RiaDefines
@@ -19,23 +19,18 @@
#include "RicfExportSnapshots.h"
#include "RicfCommandFileExecutor.h"
#include "RicfCommandForwarding.h"
#include "ExportCommands/RicSnapshotAllPlotsToFileFeature.h"
#include "ExportCommands/RicSnapshotAllViewsToFileFeature.h"
#include "RiaGuiApplication.h"
#include "RiaLogging.h"
#include "RiaRegressionTestRunner.h"
#include "RiuDockWidgetTools.h"
#include "RiuMainWindow.h"
#include "DockManager.h"
#include "Rim3dView.h"
#include "RimCase.h"
#include "RimMainPlotCollection.h"
#include "RimProject.h"
#include "RimViewWindow.h"
#include "RimcProject.h"
#include "RimcViewWindow.h"
#include "cafPdmFieldScriptingCapability.h"
#include <QFileInfo>
CAF_PDM_SOURCE_INIT( RicfExportSnapshots, "exportSnapshots" );
namespace caf
@@ -78,73 +73,81 @@ RicfExportSnapshots::RicfExportSnapshots()
//--------------------------------------------------------------------------------------------------
caf::PdmScriptResponse RicfExportSnapshots::execute()
{
if ( !RiaGuiApplication::isRunning() )
const QString commandName = classKeyword();
// Resolve the export folder from the command file executor state. The Rimc methods only accept explicit folders.
QString exportFolder = m_exportFolder();
if ( exportFolder.isEmpty() )
{
QString error( "RicfExportSnapshot: Command cannot run without a GUI" );
RiaLogging::error( error.toStdString() );
return caf::PdmScriptResponse( caf::PdmScriptResponse::COMMAND_ERROR, error );
exportFolder = RicfCommandFileExecutor::instance()->getExportPath( RicfCommandFileExecutor::ExportType::SNAPSHOTS );
}
int width = m_width();
int height = m_height();
const RiaDefines::SnapshotFileFormat plotFileFormat =
m_plotOutputFormat() == PlotOutputFormat::PDF ? RiaDefines::SnapshotFileFormat::PDF : RiaDefines::SnapshotFileFormat::PNG;
RiuMainWindow* mainWnd = RiuMainWindow::instance();
if ( !mainWnd )
const bool exportViews = m_type() != SnapshotsType::PLOTS;
const bool exportPlots = m_type() != SnapshotsType::VIEWS;
// No case or view filtering: export everything of the requested type through the project method
if ( m_caseId() == -1 && m_viewId() == -1 )
{
QString error( "RicfExportSnapshot: No main window available" );
RiaLogging::error( error.toStdString() );
return caf::PdmScriptResponse( caf::PdmScriptResponse::COMMAND_ERROR, error );
RimProject_exportSnapshots method( RimProject::current() );
method.setContentType( m_type() == SnapshotsType::ALL ? RiaDefines::SnapshotContentType::ALL
: exportViews ? RiaDefines::SnapshotContentType::VIEWS
: RiaDefines::SnapshotContentType::PLOTS );
method.setExportFolder( exportFolder );
method.setPrefix( m_prefix() );
method.setWidth( m_width() );
method.setHeight( m_height() );
method.setPlotFileFormat( plotFileFormat );
return RicfForwarding::toScriptResponse( method.execute(), commandName );
}
QString absolutePathToSnapshotDir = RicfCommandFileExecutor::instance()->getExportPath( RicfCommandFileExecutor::ExportType::SNAPSHOTS );
// Collect the view windows matching the case and view filters
std::vector<RimViewWindow*> viewWindows;
if ( !m_exportFolder().isEmpty() )
if ( exportViews )
{
absolutePathToSnapshotDir = m_exportFolder;
}
if ( absolutePathToSnapshotDir.isNull() )
{
absolutePathToSnapshotDir = RiaApplication::instance()->createAbsolutePathFromProjectRelativePath( "snapshots" );
}
if ( m_type == RicfExportSnapshots::SnapshotsType::VIEWS || m_type == RicfExportSnapshots::SnapshotsType::ALL )
{
if ( RiaRegressionTestRunner::instance()->isRunningRegressionTests() )
RimProject* project = RimProject::current();
for ( RimCase* gridCase : project->allGridCases() )
{
QSize defaultSize = RiaRegressionTestRunner::regressionDefaultImageSize();
width = defaultSize.width();
height = defaultSize.height();
}
if ( !gridCase ) continue;
if ( m_caseId() != -1 && m_caseId() != gridCase->caseId() ) continue;
RicSnapshotAllViewsToFileFeature::exportSnapshotOfViewsIntoFolder( absolutePathToSnapshotDir,
width,
height,
m_prefix,
m_caseId(),
m_viewId() );
for ( Rim3dView* view : gridCase->views() )
{
if ( view && view->viewer() && ( m_viewId() == -1 || m_viewId() == view->id() ) )
{
viewWindows.push_back( view );
}
}
}
}
if ( m_type == RicfExportSnapshots::SnapshotsType::PLOTS || m_type == RicfExportSnapshots::SnapshotsType::ALL )
{
bool activateWidget = false;
if ( RiaRegressionTestRunner::instance()->isRunningRegressionTests() )
{
QSize defaultSize = RiaRegressionTestRunner::regressionDefaultImageSize();
width = defaultSize.width();
height = defaultSize.height();
}
else
{
activateWidget = true;
}
QString fileSuffix = ".png";
if ( m_plotOutputFormat == PlotOutputFormat::PDF ) fileSuffix = ".pdf";
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfPlotsIntoFolder( absolutePathToSnapshotDir,
width,
height,
activateWidget,
m_prefix,
m_viewId(),
fileSuffix );
if ( exportPlots )
{
// Plots are not associated with a case id, so only the view id filter applies
for ( RimViewWindow* viewWindow : RimMainPlotCollection::current()->descendantsIncludingThisOfType<RimViewWindow>() )
{
if ( viewWindow->isMainDockedWindow() && viewWindow->viewWidget() && ( m_viewId() == -1 || m_viewId() == viewWindow->id() ) )
{
viewWindows.push_back( viewWindow );
}
}
}
for ( RimViewWindow* viewWindow : viewWindows )
{
RimViewWindow_exportSnapshot method( viewWindow );
method.setExportFolder( exportFolder );
method.setPrefix( m_prefix() );
method.setWidth( m_width() );
method.setHeight( m_height() );
method.setFileFormat( plotFileFormat );
auto result = method.execute();
if ( !result ) return RicfForwarding::errorResponse( result.error(), commandName );
}
return caf::PdmScriptResponse();
@@ -85,34 +85,55 @@ void RicSnapshotAllPlotsToFileFeature::exportSnapshotOfPlotsIntoFolder( const QS
if ( !snapshotPath.mkpath( "." ) ) return;
}
const QString absSnapshotPath = snapshotPath.absolutePath();
std::vector<RimViewWindow*> viewWindows = RimMainPlotCollection::current()->descendantsIncludingThisOfType<RimViewWindow>();
for ( auto viewWindow : viewWindows )
{
if ( viewWindow->isMainDockedWindow() && viewWindow->viewWidget() && ( viewId == -1 || viewId == viewWindow->id() ) )
{
QString fileName = RicSnapshotFilenameGenerator::generateSnapshotFileName( viewWindow );
if ( !prefix.isEmpty() )
{
fileName = prefix + fileName;
}
fileName.replace( " ", "_" );
if ( activateWidget )
{
RiuPlotMainWindowTools::selectAsCurrentItem( viewWindow );
QApplication::processEvents();
}
QString absoluteFileName = caf::Utils::constructFullFileName( absSnapshotPath, fileName, preferredFileSuffix );
RicSnapshotViewToFileFeature::saveSnapshotAs( absoluteFileName, viewWindow, width, height );
exportSnapshotOfPlot( viewWindow, snapshotPath.absolutePath(), width, height, activateWidget, prefix, preferredFileSuffix );
}
}
}
//--------------------------------------------------------------------------------------------------
/// Export a snapshot of a single plot window into the given folder. The folder is created if it does not exist.
/// <= 0 for width and height means to use the existing size
//--------------------------------------------------------------------------------------------------
void RicSnapshotAllPlotsToFileFeature::exportSnapshotOfPlot( RimViewWindow* viewWindow,
const QString& snapshotFolderName,
int width,
int height,
bool activateWidget,
const QString& prefix,
const QString& preferredFileSuffix )
{
if ( !viewWindow ) return;
QDir snapshotPath( snapshotFolderName );
if ( !snapshotPath.exists() )
{
if ( !snapshotPath.mkpath( "." ) ) return;
}
QString fileName = RicSnapshotFilenameGenerator::generateSnapshotFileName( viewWindow );
if ( !prefix.isEmpty() )
{
fileName = prefix + fileName;
}
fileName.replace( " ", "_" );
if ( activateWidget )
{
RiuPlotMainWindowTools::selectAsCurrentItem( viewWindow );
QApplication::processEvents();
}
QString absoluteFileName = caf::Utils::constructFullFileName( snapshotPath.absolutePath(), fileName, preferredFileSuffix );
RicSnapshotViewToFileFeature::saveSnapshotAs( absoluteFileName, viewWindow, width, height );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -40,6 +40,14 @@ public:
int viewId = -1,
const QString& preferredFileSuffix = ".png" );
static void exportSnapshotOfPlot( RimViewWindow* viewWindow,
const QString& snapshotFolderName,
int width = -1,
int height = -1,
bool activateWidget = false,
const QString& prefix = "",
const QString& preferredFileSuffix = ".png" );
protected:
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
@@ -111,37 +111,57 @@ void RicSnapshotAllViewsToFileFeature::exportSnapshotOfViewsIntoFolder( const QS
}
}
const QString absSnapshotPath = snapshotPath.absolutePath();
RiaLogging::info( std::format( "Exporting snapshot of all views to {}", snapshotFolderName ) );
for ( auto riv : viewsForSnapshot )
{
RiuViewer* viewer = riv->viewer();
if ( !viewer ) continue;
if ( !viewer->ownerViewWindow() ) continue;
RiaApplication::instance()->setActiveReservoirView( riv );
Riu3DMainWindowTools::setActiveViewer( viewer->ownerViewWindow()->dockWindowName() );
RiaViewRedrawScheduler::instance()->clearViewsScheduledForUpdate();
RiaPlotWindowRedrawScheduler::instance()->clearAllScheduledUpdates();
riv->createDisplayModelAndRedraw();
viewer->repaint();
QString fileName = RicSnapshotFilenameGenerator::generateSnapshotFileName( riv );
if ( !prefix.isEmpty() )
{
fileName = prefix + fileName;
}
QString absoluteFileName = caf::Utils::constructFullFileName( absSnapshotPath, fileName, ".png" );
RicSnapshotViewToFileFeature::saveSnapshotAs( absoluteFileName, riv, width, height );
exportSnapshotOfView( riv, snapshotPath.absolutePath(), width, height, prefix );
}
}
//--------------------------------------------------------------------------------------------------
/// Export a snapshot of a single view into the given folder. The folder is created if it does not exist.
/// <= 0 for width and height means to use the existing view size
//--------------------------------------------------------------------------------------------------
void RicSnapshotAllViewsToFileFeature::exportSnapshotOfView( Rim3dView* riv,
const QString& snapshotFolderName,
int width,
int height,
const QString& prefix )
{
if ( !riv ) return;
RiuViewer* viewer = riv->viewer();
if ( !viewer ) return;
if ( !viewer->ownerViewWindow() ) return;
QDir snapshotPath( snapshotFolderName );
if ( !snapshotPath.exists() )
{
if ( !snapshotPath.mkpath( "." ) ) return;
}
RiaApplication::instance()->setActiveReservoirView( riv );
Riu3DMainWindowTools::setActiveViewer( viewer->ownerViewWindow()->dockWindowName() );
RiaViewRedrawScheduler::instance()->clearViewsScheduledForUpdate();
RiaPlotWindowRedrawScheduler::instance()->clearAllScheduledUpdates();
riv->createDisplayModelAndRedraw();
viewer->repaint();
QString fileName = RicSnapshotFilenameGenerator::generateSnapshotFileName( riv );
if ( !prefix.isEmpty() )
{
fileName = prefix + fileName;
}
QString absoluteFileName = caf::Utils::constructFullFileName( snapshotPath.absolutePath(), fileName, ".png" );
RicSnapshotViewToFileFeature::saveSnapshotAs( absoluteFileName, riv, width, height );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@@ -19,6 +19,8 @@
#include "cafCmdFeature.h"
class Rim3dView;
//==================================================================================================
///
//==================================================================================================
@@ -36,6 +38,9 @@ public:
int caseId = -1,
int viewId = -1 );
static void
exportSnapshotOfView( Rim3dView* view, const QString& snapshotFolderName, int width = -1, int height = -1, const QString& prefix = "" );
protected:
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
@@ -46,6 +46,7 @@ set(SOURCE_GROUP_SOURCE_FILES
${CMAKE_CURRENT_LIST_DIR}/RimcColorLegend.cpp
${CMAKE_CURRENT_LIST_DIR}/RimcNestedCollectionBase.cpp
${CMAKE_CURRENT_LIST_DIR}/RimcCase.cpp
${CMAKE_CURRENT_LIST_DIR}/RimcViewWindow.cpp
)
list(APPEND CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES})
@@ -17,6 +17,7 @@
/////////////////////////////////////////////////////////////////////////////////
#include "RimcProject.h"
#include "RimcViewWindow.h"
#include "Ensemble/RiaEnsembleImportTools.h"
#include "KeyValueStore/RiaKeyValueStoreUtil.h"
@@ -24,8 +25,11 @@
#include "RiaGuiApplication.h"
#include "RiaLogging.h"
#include "RiaQStringFormatter.h"
#include "RiaRegressionTestRunner.h"
#include "RiaResultNames.h"
#include "ExportCommands/RicSnapshotAllPlotsToFileFeature.h"
#include "ExportCommands/RicSnapshotAllViewsToFileFeature.h"
#include "RicImportSummaryCasesFeature.h"
#include "ViewLink/RicLinkVisibleViewsFeature.h"
#include "ViewLink/RicUnLinkViewFeature.h"
@@ -467,3 +471,127 @@ std::expected<caf::PdmObjectHandle*, QString> RimProject_unlinkViews::execute()
RicUnLinkViewFeature::unlinkViews( uniqueViews );
return nullptr;
}
CAF_PDM_OBJECT_METHOD_SOURCE_INIT( RimProject, RimProject_exportSnapshots, "exportSnapshots" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimProject_exportSnapshots::RimProject_exportSnapshots( caf::PdmObjectHandle* self )
: caf::PdmVoidObjectMethod( self )
{
CAF_PDM_InitObject( "Export Snapshots", "", "", "Export snapshots of all 3D views and/or plots in the project" );
CAF_PDM_InitScriptableField( &m_contentType,
"ContentType",
RiaDefines::SnapshotContentType::ALL,
"Content Type",
"",
"",
"Export 3D views, plots or both" );
CAF_PDM_InitScriptableField( &m_exportFolder,
"ExportFolder",
QString(),
"Export Folder",
"",
"",
"Folder to export to. Defaults to the 'snapshots' folder next to the project file." );
CAF_PDM_InitScriptableField( &m_prefix, "Prefix", QString(), "Prefix", "", "", "Prefix for the generated file names" );
CAF_PDM_InitScriptableField( &m_width, "Width", -1, "Width", "", "", "Image width in pixels. Use -1 for the current size." );
CAF_PDM_InitScriptableField( &m_height, "Height", -1, "Height", "", "", "Image height in pixels. Use -1 for the current size." );
CAF_PDM_InitScriptableField( &m_plotFileFormat,
"PlotFileFormat",
RiaDefines::SnapshotFileFormat::PNG,
"Plot File Format",
"",
"",
"Output file format for plots. 3D views are always exported as PNG." );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setContentType( RiaDefines::SnapshotContentType contentType )
{
m_contentType = contentType;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setExportFolder( const QString& exportFolder )
{
m_exportFolder = exportFolder;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setPrefix( const QString& prefix )
{
m_prefix = prefix;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setWidth( int width )
{
m_width = width;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setHeight( int height )
{
m_height = height;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject_exportSnapshots::setPlotFileFormat( RiaDefines::SnapshotFileFormat fileFormat )
{
m_plotFileFormat = fileFormat;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::expected<caf::PdmObjectHandle*, QString> RimProject_exportSnapshots::execute()
{
if ( !RiaGuiApplication::isRunning() ) return std::unexpected( "Snapshots cannot be exported without a GUI." );
auto* project = self<RimProject>();
if ( !project ) return std::unexpected( "No project is available." );
const QString exportFolder = RimViewWindow_exportSnapshot::resolveExportFolder( m_exportFolder() );
int width = m_width();
int height = m_height();
if ( RiaRegressionTestRunner::instance()->isRunningRegressionTests() )
{
QSize defaultSize = RiaRegressionTestRunner::regressionDefaultImageSize();
width = defaultSize.width();
height = defaultSize.height();
}
const bool exportViews = m_contentType() != RiaDefines::SnapshotContentType::PLOTS;
const bool exportPlots = m_contentType() != RiaDefines::SnapshotContentType::VIEWS;
if ( exportViews )
{
RicSnapshotAllViewsToFileFeature::exportSnapshotOfViewsIntoFolder( exportFolder, width, height, m_prefix() );
}
if ( exportPlots )
{
const bool activateWidget = !RiaRegressionTestRunner::instance()->isRunningRegressionTests();
const QString fileSuffix = m_plotFileFormat() == RiaDefines::SnapshotFileFormat::PDF ? ".pdf" : ".png";
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfPlotsIntoFolder( exportFolder, width, height, activateWidget, m_prefix(), -1, fileSuffix );
}
return nullptr;
}
@@ -18,6 +18,9 @@
#pragma once
#include "RiaDefines.h"
#include "cafAppEnum.h"
#include "cafPdmField.h"
#include "cafPdmObjectHandle.h"
#include "cafPdmObjectMethod.h"
@@ -175,3 +178,31 @@ public:
private:
caf::PdmPtrArrayField<Rim3dView*> m_views;
};
//==================================================================================================
/// Export snapshots of all 3D views and/or plots in the project.
//==================================================================================================
class RimProject_exportSnapshots : public caf::PdmVoidObjectMethod
{
CAF_PDM_HEADER_INIT;
public:
RimProject_exportSnapshots( caf::PdmObjectHandle* self );
void setContentType( RiaDefines::SnapshotContentType contentType );
void setExportFolder( const QString& exportFolder );
void setPrefix( const QString& prefix );
void setWidth( int width );
void setHeight( int height );
void setPlotFileFormat( RiaDefines::SnapshotFileFormat fileFormat );
std::expected<caf::PdmObjectHandle*, QString> execute() override;
private:
caf::PdmField<caf::AppEnum<RiaDefines::SnapshotContentType>> m_contentType;
caf::PdmField<QString> m_exportFolder;
caf::PdmField<QString> m_prefix;
caf::PdmField<int> m_width;
caf::PdmField<int> m_height;
caf::PdmField<caf::AppEnum<RiaDefines::SnapshotFileFormat>> m_plotFileFormat;
};
@@ -0,0 +1,149 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2026- Equinor 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 "RimcViewWindow.h"
#include "RiaApplication.h"
#include "RiaGuiApplication.h"
#include "RiaRegressionTestRunner.h"
#include "ExportCommands/RicSnapshotAllPlotsToFileFeature.h"
#include "ExportCommands/RicSnapshotAllViewsToFileFeature.h"
#include "Rim3dView.h"
#include "RimPlotWindow.h"
#include "RimViewWindow.h"
#include "cafPdmFieldScriptingCapability.h"
CAF_PDM_OBJECT_METHOD_SOURCE_INIT( RimViewWindow, RimViewWindow_exportSnapshot, "exportSnapshot" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimViewWindow_exportSnapshot::RimViewWindow_exportSnapshot( caf::PdmObjectHandle* self )
: caf::PdmVoidObjectMethod( self )
{
CAF_PDM_InitObject( "Export Snapshot", "", "", "Export a snapshot of the view or plot to a file" );
CAF_PDM_InitScriptableField( &m_exportFolder,
"ExportFolder",
QString(),
"Export Folder",
"",
"",
"Folder to export to. Defaults to the 'snapshots' folder next to the project file." );
CAF_PDM_InitScriptableField( &m_prefix, "Prefix", QString(), "Prefix", "", "", "Prefix for the generated file name" );
CAF_PDM_InitScriptableField( &m_width, "Width", -1, "Width", "", "", "Image width in pixels. Use -1 for the current size." );
CAF_PDM_InitScriptableField( &m_height, "Height", -1, "Height", "", "", "Image height in pixels. Use -1 for the current size." );
CAF_PDM_InitScriptableField( &m_fileFormat,
"FileFormat",
RiaDefines::SnapshotFileFormat::PNG,
"File Format",
"",
"",
"Output file format. PDF is only supported for plots." );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimViewWindow_exportSnapshot::setExportFolder( const QString& exportFolder )
{
m_exportFolder = exportFolder;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimViewWindow_exportSnapshot::setPrefix( const QString& prefix )
{
m_prefix = prefix;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimViewWindow_exportSnapshot::setWidth( int width )
{
m_width = width;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimViewWindow_exportSnapshot::setHeight( int height )
{
m_height = height;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimViewWindow_exportSnapshot::setFileFormat( RiaDefines::SnapshotFileFormat fileFormat )
{
m_fileFormat = fileFormat;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::expected<caf::PdmObjectHandle*, QString> RimViewWindow_exportSnapshot::execute()
{
if ( !RiaGuiApplication::isRunning() ) return std::unexpected( "Snapshots cannot be exported without a GUI." );
auto* viewWindow = self<RimViewWindow>();
if ( !viewWindow ) return std::unexpected( "No view window is available." );
const QString exportFolder = resolveExportFolder( m_exportFolder() );
int width = m_width();
int height = m_height();
if ( RiaRegressionTestRunner::instance()->isRunningRegressionTests() )
{
QSize defaultSize = RiaRegressionTestRunner::regressionDefaultImageSize();
width = defaultSize.width();
height = defaultSize.height();
}
if ( auto* view3d = dynamic_cast<Rim3dView*>( viewWindow ) )
{
if ( !view3d->viewer() ) return std::unexpected( QString( "View '%1' has no viewer." ).arg( view3d->name() ) );
RicSnapshotAllViewsToFileFeature::exportSnapshotOfView( view3d, exportFolder, width, height, m_prefix() );
return nullptr;
}
if ( !viewWindow->viewWidget() ) return std::unexpected( "The plot has no widget to export." );
const bool activateWidget = !RiaRegressionTestRunner::instance()->isRunningRegressionTests();
const QString fileSuffix = m_fileFormat() == RiaDefines::SnapshotFileFormat::PDF ? ".pdf" : ".png";
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfPlot( viewWindow, exportFolder, width, height, activateWidget, m_prefix(), fileSuffix );
return nullptr;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RimViewWindow_exportSnapshot::resolveExportFolder( const QString& exportFolder )
{
if ( !exportFolder.isEmpty() ) return exportFolder;
return RiaApplication::instance()->createAbsolutePathFromProjectRelativePath( "snapshots" );
}
@@ -0,0 +1,60 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2026- Equinor 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 "RiaDefines.h"
#include "cafAppEnum.h"
#include "cafPdmField.h"
#include "cafPdmObjectHandle.h"
#include "cafPdmObjectMethod.h"
#include <QString>
//==================================================================================================
/// Export a snapshot of a view window (3D view or plot) to a file in the given folder.
///
/// The file name is generated from the view window and prefixed with the given prefix. PDF output
/// is only supported for plots; 3D views are always exported as PNG. Requires a GUI.
//==================================================================================================
class RimViewWindow_exportSnapshot : public caf::PdmVoidObjectMethod
{
CAF_PDM_HEADER_INIT;
public:
RimViewWindow_exportSnapshot( caf::PdmObjectHandle* self );
void setExportFolder( const QString& exportFolder );
void setPrefix( const QString& prefix );
void setWidth( int width );
void setHeight( int height );
void setFileFormat( RiaDefines::SnapshotFileFormat fileFormat );
std::expected<caf::PdmObjectHandle*, QString> execute() override;
/// Resolve the export folder: an explicit folder if given, otherwise the project relative "snapshots" folder.
static QString resolveExportFolder( const QString& exportFolder );
private:
caf::PdmField<QString> m_exportFolder;
caf::PdmField<QString> m_prefix;
caf::PdmField<int> m_width;
caf::PdmField<int> m_height;
caf::PdmField<caf::AppEnum<RiaDefines::SnapshotFileFormat>> m_fileFormat;
};
+12 -11
View File
@@ -384,7 +384,8 @@ def views(self) -> List[View]:
views = project.views()
views_for_case = []
for view_object in views:
if view_object.id == self.id:
view_case = view_object.case()
if view_case is not None and view_case.id == self.id:
views_for_case.append(view_object)
return views_for_case
@@ -392,23 +393,23 @@ def views(self) -> List[View]:
@add_method(Case)
def export_snapshots_of_all_views(
self, prefix: str = "", export_folder: str = ""
) -> Any:
) -> None:
"""Export snapshots for all views in the case
Deprecated: loop over views() and call View.export_snapshot() instead.
Arguments:
prefix (str): Exported file name prefix
export_folder(str): The path to export to. By default will use the global export folder
export_folder(str): The path to export to. By default will use the 'snapshots' folder next to the project file.
"""
return self._execute_command(
exportSnapshots=Cmd.ExportSnapshotsRequest(
type="VIEWS",
prefix=prefix,
caseId=self.id,
viewId=-1,
exportFolder=export_folder,
)
warnings.warn(
"Case.export_snapshots_of_all_views() is deprecated, use View.export_snapshot() on each view instead",
DeprecationWarning,
stacklevel=3,
)
for view in self.views():
view.export_snapshot(export_folder=export_folder, prefix=prefix)
@add_method(Case)
+42 -15
View File
@@ -2,34 +2,61 @@
ResInsight 2d plot module
"""
import Commands_pb2
import warnings
from .pdmobject import add_method
from .resinsight_classes import PlotWindow as PlotWindow, Plot as Plot
from .resinsight_classes import (
PlotWindow as PlotWindow,
Plot as Plot,
SnapshotFileFormat,
)
@add_method(PlotWindow)
def export_snapshot(
self, export_folder="", file_prefix="", output_format="PNG", width=-1, height=-1
self,
export_folder="",
file_prefix="",
output_format="PNG",
width=-1,
height=-1,
prefix=None,
file_format=None,
):
"""Export snapshot for the current plot
Arguments:
export_folder(str): The path to export to. By default will use the global export folder
prefix (str): Exported file name prefix
output_format(str): Enum string. Can be 'PNG' or 'PDF'.
export_folder(str): The path to export to. By default will use the 'snapshots' folder next to the project file.
file_prefix (str): Deprecated, use prefix. Exported file name prefix
output_format(str): Deprecated, use file_format. Enum string. Can be 'PNG' or 'PDF'.
width (int): The width of the exported snapshot. By default will use the existing size.
height (int): The height of the exported snapshot. By default will use the existing size.
prefix (str): Exported file name prefix
file_format (SnapshotFileFormat): 'PNG' or 'PDF'
"""
return self._execute_command(
exportSnapshots=Commands_pb2.ExportSnapshotsRequest(
type="PLOTS",
prefix=file_prefix,
viewId=self.id,
exportFolder=export_folder,
plotOutputFormat=output_format,
width=width,
height=height,
if file_prefix:
warnings.warn(
"PlotWindow.export_snapshot(file_prefix=...) is deprecated, use prefix=...",
DeprecationWarning,
stacklevel=3,
)
if output_format != "PNG":
warnings.warn(
"PlotWindow.export_snapshot(output_format=...) is deprecated, use file_format=...",
DeprecationWarning,
stacklevel=3,
)
if prefix is None:
prefix = file_prefix
if file_format is None:
file_format = SnapshotFileFormat(output_format)
self._call_pdm_method_void(
"exportSnapshot",
export_folder=export_folder,
prefix=prefix,
width=width,
height=height,
file_format=file_format,
)
+43 -12
View File
@@ -6,6 +6,7 @@ The ResInsight project module
import grpc
import uuid
import warnings
from .case import Case
from .gridcasegroup import GridCaseGroup
@@ -24,6 +25,8 @@ from .resinsight_classes import (
PlotWindow,
Project,
Reservoir,
SnapshotContentType,
SnapshotFileFormat,
SummaryCase,
WellPath,
)
@@ -284,25 +287,53 @@ def export_multi_case_snapshots(self, grid_list_file):
@add_method(Project)
def export_snapshots(
self, snapshot_type="ALL", prefix="", plot_format="PNG", width=-1, height=-1
self,
snapshot_type="ALL",
prefix="",
plot_format="PNG",
width=-1,
height=-1,
content_type=None,
export_folder="",
plot_file_format=None,
):
"""Export all snapshots of a given type
Arguments:
snapshot_type (str): Enum string ('ALL', 'VIEWS' or 'PLOTS')
snapshot_type (str): Deprecated, use content_type. Enum string ('ALL', 'VIEWS' or 'PLOTS')
prefix (str): Exported file name prefix
plot_format(str): Enum string, 'PNG' or 'PDF'
plot_format(str): Deprecated, use plot_file_format. Enum string, 'PNG' or 'PDF'
width (int): The width of the exported snapshots. By default will use the existing size.
height (int): The height of the exported snapshots. By default will use the existing size.
content_type (SnapshotContentType): 'ALL', 'VIEWS' or 'PLOTS'
export_folder (str): The path to export to. By default will use the 'snapshots' folder next to the project file.
plot_file_format (SnapshotFileFormat): 'PNG' or 'PDF'
"""
return self._execute_command(
exportSnapshots=Commands_pb2.ExportSnapshotsRequest(
type=snapshot_type,
prefix=prefix,
caseId=-1,
viewId=-1,
plotOutputFormat=plot_format,
width=width,
height=height,
if snapshot_type != "ALL":
warnings.warn(
"Project.export_snapshots(snapshot_type=...) is deprecated, use content_type=...",
DeprecationWarning,
stacklevel=3,
)
if plot_format != "PNG":
warnings.warn(
"Project.export_snapshots(plot_format=...) is deprecated, use plot_file_format=...",
DeprecationWarning,
stacklevel=3,
)
if content_type is None:
content_type = SnapshotContentType(snapshot_type)
if plot_file_format is None:
plot_file_format = SnapshotFileFormat(plot_format)
self._call_pdm_method_void(
"exportSnapshots",
content_type=content_type,
export_folder=export_folder,
prefix=prefix,
width=width,
height=height,
plot_file_format=plot_file_format,
)
@@ -279,3 +279,49 @@ def test_exportSnapshots(rips_instance, initialize_test):
# assert(len(os.listdir(tmpdirname)) > 0)
for fileName in os.listdir(tmpdirname):
assert os.path.splitext(fileName)[1] == ".png"
def test_export_snapshot_of_view(rips_instance, initialize_test):
if not rips_instance.is_gui():
pytest.skip("Cannot run test without a GUI")
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.load_case(case_path)
view = case.create_view()
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
# Note: the export is a no-op when the view has no OpenGL viewer (e.g. offscreen Qt platform),
# so the number of files is not asserted. The call itself must succeed.
view.export_snapshot(
export_folder=tmpdirname, prefix="test_", width=320, height=240
)
for file_name in os.listdir(tmpdirname):
assert file_name.startswith("test_")
assert os.path.splitext(file_name)[1] == ".png"
# Case.views() must find the view through its case
assert len(case.views()) == 1
with pytest.warns(DeprecationWarning):
case.export_snapshots_of_all_views(export_folder=tmpdirname, prefix="all_")
def test_export_snapshots_content_type(rips_instance, initialize_test):
if not rips_instance.is_gui():
pytest.skip("Cannot run test without a GUI")
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.load_case(case_path)
case.create_view()
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
rips_instance.project.export_snapshots(
content_type=rips.SnapshotContentType.VIEWS,
export_folder=tmpdirname,
width=320,
height=240,
)
for file_name in os.listdir(tmpdirname):
assert os.path.splitext(file_name)[1] == ".png"
with pytest.warns(DeprecationWarning):
rips_instance.project.export_snapshots(
snapshot_type="VIEWS", export_folder=tmpdirname, prefix="old_"
)
-22
View File
@@ -222,25 +222,3 @@ def visible_cells(self, time_step=0):
finally:
# Clean up temporary key from key-value store
project.remove_key_values(visibility_key)
@add_method(ViewWindow)
def export_snapshot(self, prefix="", export_folder="", width=-1, height=-1):
"""Export snapshot for the current view
Arguments:
prefix (str): Exported file name prefix
export_folder(str): The path to export to. By default will use the global export folder
"""
case_id = self.case().id
return self._execute_command(
exportSnapshots=Cmd.ExportSnapshotsRequest(
type="VIEWS",
prefix=prefix,
caseId=case_id,
viewId=self.id,
exportFolder=export_folder,
width=width,
height=height,
)
)