[libcalamares] Factor out Python helper

- the strange construction of Helper and treating it as a singleton
  can be factored out into a separate singleton-handling instance()
  function. The Helper should never be destroyed.
This commit is contained in:
Adriaan de Groot 2020-03-09 10:05:01 -05:00
parent 3025c5383b
commit 9b5a391c86
4 changed files with 37 additions and 56 deletions

View File

@ -204,8 +204,6 @@ variantHashFromPyDict( const boost::python::dict& pyDict )
}
Helper* Helper::s_instance = nullptr;
static inline void
add_if_lib_exists( const QDir& dir, const char* name, QStringList& list )
{
@ -221,12 +219,10 @@ add_if_lib_exists( const QDir& dir, const char* name, QStringList& list )
}
}
Helper::Helper( QObject* parent )
: QObject( parent )
Helper::Helper()
: QObject( nullptr )
{
// Let's make extra sure we only call Py_Initialize once
if ( !s_instance )
{
if ( !Py_IsInitialized() )
{
Py_Initialize();
@ -249,20 +245,20 @@ Helper::Helper( QObject* parent )
sys.attr( "path" ).attr( "append" )( dir );
}
}
else
Helper::~Helper() {}
Helper*
Helper::instance()
{
cWarning() << "creating PythonHelper more than once. This is very bad.";
return;
}
static Helper* s_helper = nullptr;
s_instance = this;
}
Helper::~Helper()
if ( !s_helper )
{
s_instance = nullptr;
s_helper = new Helper;
}
return s_helper;
}
boost::python::dict
Helper::createCleanNamespace()

View File

@ -50,16 +50,15 @@ class Helper : public QObject
{
Q_OBJECT
public:
virtual ~Helper();
boost::python::dict createCleanNamespace();
QString handleLastError();
static Helper* instance();
private:
friend Helper* Calamares::PythonJob::helper();
explicit Helper( QObject* parent = nullptr );
static Helper* s_instance;
virtual ~Helper();
explicit Helper();
boost::python::object m_mainModule;
boost::python::object m_mainNamespace;

View File

@ -233,7 +233,7 @@ PythonJob::exec()
try
{
bp::dict scriptNamespace = helper()->createCleanNamespace();
bp::dict scriptNamespace = CalamaresPython::Helper::instance()->createCleanNamespace();
bp::object calamaresModule = bp::import( "libcalamares" );
bp::dict calamaresNamespace = bp::extract< bp::dict >( calamaresModule.attr( "__dict__" ) );
@ -299,7 +299,7 @@ PythonJob::exec()
QString msg;
if ( PyErr_Occurred() )
{
msg = helper()->handleLastError();
msg = CalamaresPython::Helper::instance()->handleLastError();
}
bp::handle_exception();
PyErr_Clear();
@ -315,17 +315,4 @@ PythonJob::emitProgress( qreal progressValue )
emit progress( progressValue );
}
CalamaresPython::Helper*
PythonJob::helper()
{
auto ptr = CalamaresPython::Helper::s_instance;
if ( !ptr )
{
ptr = new CalamaresPython::Helper;
}
return ptr;
}
} // namespace Calamares

View File

@ -57,7 +57,6 @@ private:
friend class CalamaresPython::PythonJobInterface;
void emitProgress( double progressValue );
CalamaresPython::Helper* helper();
QString m_scriptFile;
QString m_workingPath;
QString m_description;