Files
ResInsight/ApplicationLibCode/Application/RiaConsoleApplication.cpp
T
Magne Sjaastad 56e98ba1c4 #14476 ApplicationLibCode: Replace CVF_ASSERT with CAF_ASSERT
Migrate all assert macros in ApplicationLibCode to CAF_ASSERT and remove every
use of cvfAssert.h.

CVF_ASSERT is replaced one to one. CVF_TIGHT_ASSERT is also replaced by
CAF_ASSERT, which is semantically exact: CVF_ENABLE_TIGHT_ASSERTS is 1 only
under _DEBUG, and that is what CAF_ASSERT now does. The two CVF_FAIL_MSG sites
become CAF_ASSERT( false && "message" ), preserving the message with the idiom
already used elsewhere in the code base.

Counts before and after: CVF_ASSERT 1044 to 0, CVF_TIGHT_ASSERT 66 to 0,
CVF_FAIL_MSG 2 to 0, cvfAssert.h references 154 to 0.

Include handling: files that included cvfAssert.h directly now include
cafAssert.h instead, includes left dead by the migration are removed, and files
that were relying on cvfAssert.h transitively get an explicit cafAssert.h. Files
that reach cafAssert.h through another caf header are left unchanged; a missing
include here is a compile error, not a silently disabled assert.

ResultStatisticsCache links only LibCore and therefore had no path to
cafAssert.h. Add the cafPdmCore directory as a private include path rather than
linking the library, since cafAssert.h is header only.

Note that this stops these asserts from firing in Release and RelWithDebInfo,
where CVF_ASSERT was previously active.
2026-08-07 15:05:57 +02:00

466 lines
17 KiB
C++

////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2019- 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 "RiaConsoleApplication.h"
#include "Cloud/RiaConnectorTools.h"
#include "RiaArgumentParser.h"
#include "RiaLogging.h"
#include "RiaPreferences.h"
#include "RiaPreferencesGrid.h"
#include "RiaProjectModifier.h"
#include "RiaQStringFormatter.h"
#include "RiaSocketServer.h"
#include "RiaVersionInfo.h"
#include "RiuRecentFileActionProvider.h"
#include "RicImportEclipseCaseFeature.h"
#include "RicImportGeneralDataFeature.h"
#include "cvfProgramOptions.h"
#include "cvfqtUtils.h"
#include "cafAssert.h"
#include <QFileInfo>
#ifdef WIN32
#include <windows.h>
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaConsoleApplication* RiaConsoleApplication::instance()
{
RiaConsoleApplication* currentConsoleApp = dynamic_cast<RiaConsoleApplication*>( RiaApplication::instance() );
CAF_ASSERT( currentConsoleApp && "Should never be called from a method that isn't within the Console context" );
return currentConsoleApp;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaConsoleApplication::RiaConsoleApplication( int& argc, char** argv )
: QCoreApplication( argc, argv )
, RiaApplication()
{
installEventFilter( this );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaConsoleApplication::~RiaConsoleApplication()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::initialize()
{
#ifdef _WIN32
#pragma warning( push ) // Saves the current warning state.
#pragma warning( disable : 4996 ) // Temporarily disables warning 4996.
bool isReOpenStdToConsoleNeeded = false;
if ( AttachConsole( ATTACH_PARENT_PROCESS ) )
{
int fileType = GetFileType( GetStdHandle( STD_OUTPUT_HANDLE ) );
// FILE_TYPE_CHAR indicates a windows console buffer.
// FILE_TYPE_PIPE indicates redirection imposed by the starting shell (eg migw shell)
// If we are dealing with a pipe, we do not want to do the reopen, and destroy the connection.
if ( fileType == FILE_TYPE_CHAR )
{
isReOpenStdToConsoleNeeded = true;
}
}
else if ( AllocConsole() )
{
isReOpenStdToConsoleNeeded = true;
}
if ( isReOpenStdToConsoleNeeded )
{
freopen( "conout$", "w", stdout );
freopen( "conout$", "w", stderr );
freopen( "conin$", "r", stdin );
}
#pragma warning( pop )
#endif
RiaApplication::initialize();
m_socketServer = new RiaSocketServer( this );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::initializeLoggers()
{
auto logger = std::make_unique<RiaStdOutLogger>();
// Use command line log level if provided, otherwise use preference-based level
if ( m_logLevelFromCommandLine.has_value() )
{
logger->setLevel( m_logLevelFromCommandLine.value() );
}
else
{
logger->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) );
}
RiaLogging::appendLoggerInstance( std::move( logger ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments( cvf::ProgramOptions* progOpt )
{
// Handling of the actual command line options
// --------------------------------------------------------
if ( cvf::Option o = progOpt->option( "ignoreArgs" ) )
{
return ApplicationStatus::KEEP_GOING;
}
if ( progOpt->option( "help" ) || progOpt->option( "?" ) )
{
showFormattedTextInMessageBoxOrConsole( "\nThe current command line options in ResInsight are:\n" + commandLineParameterHelp() );
return RiaApplication::ApplicationStatus::EXIT_COMPLETED;
}
if ( progOpt->option( "version" ) )
{
QString text = QString( STRPRODUCTVER ) + "\n";
text += "SHA " + QString( RESINSIGHT_GIT_HASH ) + "\n";
showFormattedTextInMessageBoxOrConsole( text );
return RiaApplication::ApplicationStatus::EXIT_COMPLETED;
}
if ( cvf::Option o = progOpt->option( "threadcount" ) )
{
if ( o.valueCount() == 1 )
{
auto value = o.value( 0 ).toInt();
if ( value > 0 )
{
m_threadCountFromCommandLine = value;
}
else
{
RiaLogging::error( "Error: Invalid value for --threadcount. Must be a positive integer." );
return RiaApplication::ApplicationStatus::EXIT_WITH_ERROR;
}
}
}
// Code generation
// -----------------
if ( cvf::Option o = progOpt->option( "generate" ) )
{
CAF_ASSERT( o.valueCount() == 1 );
QString outputFile = cvfqt::Utils::toQString( o.value( 0 ) );
QString errMsg;
if ( !RiaApplication::generateCode( outputFile, &errMsg ) )
{
RiaLogging::error( std::format( "Error: {}", errMsg ) );
return RiaApplication::ApplicationStatus::EXIT_WITH_ERROR;
}
return RiaApplication::ApplicationStatus::EXIT_COMPLETED;
}
if ( cvf::Option o = progOpt->option( "preferences" ) )
{
CAF_ASSERT( o.valueCount() == 1 );
m_preferencesFileName = cvfqt::Utils::toQString( o.value( 0 ) );
RiaApplication::initialize();
onProjectClosed();
}
if ( cvf::Option o = progOpt->option( "startdir" ) )
{
CAF_ASSERT( o.valueCount() == 1 );
setStartDir( cvfqt::Utils::toQString( o.value( 0 ) ) );
}
if ( cvf::Option o = progOpt->option( "egridReader" ) )
{
CAF_ASSERT( o.valueCount() == 1 );
std::string readerName = o.value( 0 ).toLower().toStdString();
m_preferences->gridPreferences()->setGridModelReaderOverride( readerName );
}
QString projectFileName;
if ( progOpt->hasOption( "last" ) )
{
projectFileName = RiuRecentFileActionProvider::lastUsedProjectFileName();
}
if ( cvf::Option o = progOpt->option( "project" ) )
{
CAF_ASSERT( o.valueCount() == 1 );
projectFileName = cvfqt::Utils::toQString( o.value( 0 ) );
}
if ( !projectFileName.isEmpty() )
{
cvf::ref<RiaProjectModifier> projectModifier;
RiaApplication::ProjectLoadAction projectLoadAction = RiaApplication::ProjectLoadAction::PLA_NONE;
if ( cvf::Option o = progOpt->option( "replaceCase" ) )
{
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if ( o.valueCount() == 1 )
{
// One argument is available, use replace case for first occurrence in the project
QString gridFileName = cvfqt::Utils::toQString( o.safeValue( 0 ) );
projectModifier->setReplaceCaseFirstOccurrence( gridFileName );
}
else
{
size_t optionIdx = 0;
while ( optionIdx < o.valueCount() )
{
const int caseId = o.safeValue( optionIdx++ ).toInt( -1 );
QString gridFileName = cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) );
if ( caseId != -1 && !gridFileName.isEmpty() )
{
projectModifier->setReplaceCase( caseId, gridFileName );
}
}
}
}
if ( cvf::Option o = progOpt->option( "replaceSourceCases" ) )
{
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if ( o.valueCount() == 1 )
{
// One argument is available, use replace case for first occurrence in the project
std::vector<QString> gridFileNames = readFileListFromTextFile( cvfqt::Utils::toQString( o.safeValue( 0 ) ) );
projectModifier->setReplaceSourceCasesFirstOccurrence( gridFileNames );
}
else
{
size_t optionIdx = 0;
while ( optionIdx < o.valueCount() )
{
const int groupId = o.safeValue( optionIdx++ ).toInt( -1 );
std::vector<QString> gridFileNames = readFileListFromTextFile( cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) ) );
if ( groupId != -1 && !gridFileNames.empty() )
{
projectModifier->setReplaceSourceCasesById( groupId, gridFileNames );
}
}
}
projectLoadAction = RiaApplication::ProjectLoadAction::PLA_CALCULATE_STATISTICS;
}
if ( cvf::Option o = progOpt->option( "replacePropertiesFolder" ) )
{
if ( projectModifier.isNull() ) projectModifier = new RiaProjectModifier;
if ( o.valueCount() == 1 )
{
QString propertiesFolder = cvfqt::Utils::toQString( o.safeValue( 0 ) );
projectModifier->setReplacePropertiesFolderFirstOccurrence( propertiesFolder );
}
else
{
size_t optionIdx = 0;
while ( optionIdx < o.valueCount() )
{
const int caseId = o.safeValue( optionIdx++ ).toInt( -1 );
QString propertiesFolder = cvfqt::Utils::toQString( o.safeValue( optionIdx++ ) );
if ( caseId != -1 && !propertiesFolder.isEmpty() )
{
projectModifier->setReplacePropertiesFolder( caseId, propertiesFolder );
}
}
}
}
loadProject( projectFileName, projectLoadAction, projectModifier.p() );
}
if ( cvf::Option o = progOpt->option( "case" ) )
{
QStringList fileNames = RicImportGeneralDataFeature::fileNamesFromCaseNames( cvfqt::Utils::toQStringList( o.values() ) );
bool createView = true;
bool createPlot = true;
auto results = RicImportGeneralDataFeature::openEclipseFilesFromFileNames( fileNames, createPlot, createView );
if ( results )
{
RicImportEclipseCaseFeature::importPvdSurfacesForGridFiles( fileNames, {} );
}
}
if ( cvf::Option o = progOpt->option( "commandFile" ) )
{
QString commandFile = cvfqt::Utils::toQString( o.safeValue( 0 ) );
if ( !progOpt->hasOption( "startdir" ) )
{
QFileInfo commandFileInfo( commandFile );
QString commandDir = commandFileInfo.absolutePath();
setStartDir( commandDir );
}
cvf::Option projectOption = progOpt->option( "commandFileProject" );
cvf::Option caseOption = progOpt->option( "commandFileReplaceCases" );
if ( projectOption && caseOption )
{
projectFileName = cvfqt::Utils::toQString( projectOption.value( 0 ) );
std::vector<int> caseIds;
std::vector<QString> caseListFiles;
if ( caseOption.valueCount() == 1 )
{
caseListFiles.push_back( cvfqt::Utils::toQString( caseOption.safeValue( 0 ) ) );
}
else
{
size_t optionIdx = 0;
while ( optionIdx < caseOption.valueCount() )
{
const int caseId = caseOption.safeValue( optionIdx++ ).toInt( -1 );
QString caseListFile = cvfqt::Utils::toQString( caseOption.safeValue( optionIdx++ ) );
if ( caseId != -1 && !caseListFile.isEmpty() )
{
caseIds.push_back( caseId );
caseListFiles.push_back( caseListFile );
}
}
}
if ( caseIds.empty() && !caseListFiles.empty() )
{
QString caseListFile = caseListFiles[0];
std::vector<QString> caseFiles = readFileListFromTextFile( caseListFile );
for ( const QString& caseFile : caseFiles )
{
RiaProjectModifier projectModifier;
projectModifier.setReplaceCaseFirstOccurrence( caseFile );
loadProject( projectFileName, RiaApplication::ProjectLoadAction::PLA_NONE, &projectModifier );
executeCommandFile( commandFile );
}
}
else
{
CAF_ASSERT( caseIds.size() == caseListFiles.size() );
std::vector<std::vector<QString>> allCaseFiles;
size_t maxFiles = 0;
for ( size_t i = 0; i < caseIds.size(); ++i )
{
std::vector<QString> caseFiles = readFileListFromTextFile( caseListFiles[i] );
allCaseFiles.push_back( caseFiles );
maxFiles = std::max( caseFiles.size(), maxFiles );
}
for ( size_t i = 0; i < caseIds.size(); ++i )
{
RiaProjectModifier projectModifier;
for ( size_t j = 0; j < maxFiles; ++j )
{
if ( allCaseFiles[i].size() > j )
{
projectModifier.setReplaceCase( caseIds[i], allCaseFiles[i][j] );
}
}
loadProject( projectFileName, RiaApplication::ProjectLoadAction::PLA_NONE, &projectModifier );
executeCommandFile( commandFile );
}
}
}
else
{
executeCommandFile( commandFile );
}
return ApplicationStatus::EXIT_COMPLETED;
}
return ApplicationStatus::KEEP_GOING;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::showFormattedTextInMessageBoxOrConsole( const QString& errMsg )
{
std::cout << errMsg.toStdString();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::invokeProcessEvents( QEventLoop::ProcessEventsFlags flags /*= QEventLoop::AllEvents*/ )
{
processEvents( flags );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::onProjectOpeningError( const QString& errMsg )
{
RiaLogging::error( errMsg.toStdString() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::onProjectOpened()
{
loadAndUpdatePlotData();
processEvents();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaConsoleApplication::onProjectClosed()
{
processEvents();
}