Example #1
0
void showPage(const QString &str)
{
    if (str.isEmpty())
        QDesktopServices::openUrl(QUrl::fromLocalFile(datadir() + "/resources/help/index.html"));
    else
        QDesktopServices::openUrl(QUrl::fromLocalFile(datadir() + "/resources/help/" + str));
}
Example #2
0
void PythonEngine::init()
{
    m_isRunning = false;
    m_stdOut = "";

    // connect stdout
    connect(this, SIGNAL(pythonShowMessage(QString)), this, SLOT(stdOut(QString)));

    // init python
    Py_Initialize();

    // read functions
    m_functions = readFileContent(datadir() + "/functions.py");

    m_dict = PyDict_New();
    PyDict_SetItemString(m_dict, "__builtins__", PyEval_GetBuiltins());

    // init engine extensions
    Py_InitModule("pythonlab", pythonEngineFuntions);

    addCustomExtensions();

    // custom modules
    PyRun_String(QString("import sys; sys.path.insert(0, \"" + datadir() + "/resources/python" + "\")").toStdString().c_str(), Py_file_input, m_dict, m_dict);

    // functions.py
    PyRun_String(m_functions.toStdString().c_str(), Py_file_input, m_dict, m_dict);
}
Example #3
0
QStringList availableLanguages()
{
    QDir dir;
    dir.setPath(datadir() + LANGUAGEROOT);

    // add all translations
    QStringList filters;
    filters << "*.qm";
    dir.setNameFilters(filters);
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);

    // remove extension
    QStringList list = dir.entryList();
    list.replaceInStrings(".qm", "");

    // remove system translations
    foreach (QString str, list)
    {
        if (str.startsWith("qt_"))
            list.removeOne(str);
        if (str.startsWith("plugin_"))
            list.removeOne(str);
    }

    return list;
}
Example #4
0
void PythonEngine::init()
{
    m_isScriptRunning = false;
    m_isExpressionRunning = false;

    // init python
    PyEval_InitThreads();
    Py_Initialize();

    // args
    /// \todo Better
    int argc = 1;
    char ** argv = new char*[1];
    argv[0] = new char[1]();
    PySys_SetArgv(argc, argv);
    delete [] argv[0];
    delete [] argv;

    // read pythonlab functions
    addFunctions(readFileContent(datadir() + "/resources/python/functions_pythonlab.py"));
    addCustomFunctions();

    // m_dict = PyDict_New();
    // PyDict_SetItemString(m_dict, "__builtins__", PyEval_GetBuiltins());

    PyObject *main = PyImport_ImportModule("__main__");
    Py_INCREF(main);
    m_dict = PyModule_GetDict(main);
    Py_INCREF(m_dict);

    // init engine extensions
    Py_InitModule("pythonlab", pythonEngineFuntions);

    addCustomExtensions();

    // custom modules
    PyObject *import = PyRun_String(QString("import sys; sys.path.insert(0, \"" + datadir() + "/resources/python" + "\")").toLatin1().data(), Py_file_input, m_dict, m_dict);
    Py_XDECREF(import);

    // functions.py
    PyObject *func = PyRun_String(m_functions.toLatin1().data(), Py_file_input, m_dict, m_dict);
    Py_XDECREF(func);
}
Example #5
0
PluginInterface *Agros2D::loadPlugin(const QString &pluginName)
{
    QPluginLoader *loader = NULL;

#ifdef Q_WS_X11
    if (QFile::exists(QString("%1/libs/libagros2d_plugin_%2.so").arg(datadir()).arg(pluginName)))
        loader = new QPluginLoader(QString("%1/libs/libagros2d_plugin_%2.so").arg(datadir()).arg(pluginName));

    if (!loader)
    {
        if (QFile::exists(QString("/usr/local/lib/libagros2d_plugin_%1.so").arg(pluginName)))
            loader = new QPluginLoader(QString("/usr/local/lib/libagros2d_plugin_%1.so").arg(pluginName));
        else if (QFile::exists(QString("/usr/lib/libagros2d_plugin_%1.so").arg(pluginName)))
            loader = new QPluginLoader(QString("/usr/lib/libagros2d_plugin_%1.so").arg(pluginName));
    }
#endif

#ifdef Q_WS_WIN
    if (QFile::exists(QString("%1/libs/agros2d_plugin_%2.dll").arg(datadir()).arg(pluginName)))
        loader = new QPluginLoader(QString("%1/libs/agros2d_plugin_%2.dll").arg(datadir()).arg(pluginName));
#endif

    if (!loader)
    {
        throw AgrosPluginException(QObject::tr("Could not find 'agros2d_plugin_%1'").arg(pluginName));
    }

    if (!loader->load())
    {
        QString error = loader->errorString();
        delete loader;
        throw AgrosPluginException(QObject::tr("Could not load 'agros2d_plugin_%1' (%2)").arg(pluginName).arg(error));
    }

    assert(loader->instance());
    PluginInterface *plugin = qobject_cast<PluginInterface *>(loader->instance());

    // loader->unload();
    delete loader;

    return plugin;
}
Example #6
0
void ReportDialog::defaultValues()
{
    logMessage("ReportDialog::defaultValues()");

    chkProblemInformation->setChecked(true);
    chkPhysicalProperties->setChecked(true);
    chkGeometry->setChecked(true);
    chkScript->setChecked(true);

    chkFigureGeometry->setChecked(true);
    chkShowGrid->setChecked(true);
    chkShowRulers->setChecked(true);

    txtFigureWidth->setValue(Value("600"));
    txtFigureHeight->setValue(Value("400"));

    txtTemplate->setText(QString("%1/doc/report/default.html").arg(datadir()));
    txtStyleSheet->setText(QString("%1/doc/report/default.css").arg(datadir()));

    checkPaths();
}
Example #7
0
bool MaterialEditDialog::writeMaterial()
{
    if (lstProperties->currentItem())
        m_properties.replace(lstProperties->currentRow(), writeProperty());

    QFileInfo fileInfo(m_fileName);
    if (fileInfo.baseName() != txtName->text())
    {
        bool move = true;

        // rename file
        QString newFilename = fileInfo.absolutePath() + "/" + txtName->text() + ".mat";
        if (QFile::exists(newFilename))
            move = (QMessageBox::question(this, tr("File exists"), tr("Material '%1' already exists. Do you wish replace this file?").arg(newFilename)) == 0);

        if (move)
        {
            QFile::remove(m_fileName);
            m_fileName = newFilename;
        }
    }

    try
    {
        // general
        XMLMaterial::general general(txtName->text().toStdString());
        general.description().set(txtDescription->text().toStdString());

        // properties
        XMLMaterial::properties properties;
        foreach(XMLMaterial::property prop, m_properties)
        {
            // add property
            properties.property().push_back(prop);
        }

        // material
        XMLMaterial::material material(general, properties);

        std::string mesh_schema_location("");

        // TODO: set path more general
        mesh_schema_location.append(QString("%1/material_xml.xsd").arg(QFileInfo(datadir() + XSDROOT).absoluteFilePath()).toStdString());
        ::xml_schema::namespace_info namespace_info_mesh("XMLMaterial", mesh_schema_location);

        ::xml_schema::namespace_infomap namespace_info_map;
        namespace_info_map.insert(std::pair<std::basic_string<char>, xml_schema::namespace_info>("material", namespace_info_mesh));

        std::ofstream out(compatibleFilename(m_fileName).toStdString().c_str());
        XMLMaterial::material_(out, material, namespace_info_map);

        return true;
    }
Example #8
0
void setLocale(const QString &locale)
{
    // non latin-1 chars
#if QT_VERSION < 0x050000
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8"));
#endif

    QTranslator *qtTranslator = new QTranslator();
    QTranslator *appTranslator = new QTranslator();
    QTranslator *pluginTranslator = new QTranslator();

    QString country = locale.section('_',0,0);
    if (QFile::exists(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + country + ".qm"))
        qtTranslator->load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + country + ".qm");
    else if (QFile::exists(datadir() + LANGUAGEROOT + "/qt_" + country + ".qm"))
        qtTranslator->load(datadir() + LANGUAGEROOT + "/qt_" + country + ".qm");
    else
        qDebug() << "Qt locale file not found.";

    if (QFile::exists(datadir() + LANGUAGEROOT + QDir::separator() + locale + ".qm"))
        appTranslator->load(datadir() + LANGUAGEROOT + QDir::separator() + locale + ".qm");
    else if (QFile::exists(datadir() + LANGUAGEROOT + "/en_US.qm"))
        appTranslator->load(datadir() + LANGUAGEROOT + "/en_US.qm");
    else
        qDebug() << "Locale file not found.";

    if (QFile::exists(datadir() + LANGUAGEROOT + QDir::separator() + "plugin_" + locale + ".qm"))
        pluginTranslator->load(datadir() + LANGUAGEROOT + QDir::separator() + "plugin_" + locale + ".qm");
    else if (QFile::exists(datadir() + LANGUAGEROOT + "/plugin_en_US.qm"))
        pluginTranslator->load(datadir() + LANGUAGEROOT + "/plugin_en_US.qm");
    else
        qDebug() << "Plugin locale file not found.";

    QApplication::installTranslator(qtTranslator);
    QApplication::installTranslator(appTranslator);
    QApplication::installTranslator(pluginTranslator);
}
Example #9
0
/***********************************************************
PostManagement
***********************************************************/
QString FileDialogOptionsModel::PostManagement(const QString & selectedfile)
{
	QString outfile;

	// check if choosen file is in the directory data
	QDir datadir(DataDirHandler::getInstance()->GetDataDirPath().c_str());
	if(selectedfile.contains(datadir.absolutePath()))
	{
		outfile = selectedfile;
		outfile = outfile.remove(datadir.absolutePath() + "/");
	}
	else
	{
		//copy the file over
		try
		{
			// get all files with same name
			std::vector<std::string> files;
			QString fpath = selectedfile.section('/', 0, -2 );
			{
				QString filenoext = selectedfile.section('/', -1);
				filenoext = filenoext.section('.', 0, 0);

				FileUtil::ListFilesInDir(fpath.toAscii().data(), files, filenoext.toAscii().data());
			}

			for(size_t curs=0; curs<files.size(); ++curs)
			{
				QString tmp = fpath + "/";
				tmp += files[curs].c_str();
				QString tmp2 = StartingDirectory + "/";
				tmp2 += files[curs].c_str();
				FileUtil::MakeFileCopy(tmp.toAscii().data(), tmp2.toAscii().data());
			}

			QString filename = StartingDirectory + "/" + selectedfile.section('/', -1);
			outfile = filename.section('/', 1);
		}
		catch(...)
		{
			QErrorMessage msgdial;
			msgdial.showMessage ( "Error copying the file to the data directory!" );
			outfile = "";
		}
	}

	return outfile;
}
Example #10
0
/***********************************************************
PostManagement
***********************************************************/
QString FileDialogOptionsIcon::PostManagement(const QString & selectedfile)
{
	QString outfile;

	// check if choosen file is in the directory data
	QDir datadir(DataDirHandler::getInstance()->GetDataDirPath().c_str());
	if(selectedfile.contains(datadir.absolutePath()))
	{
		outfile = selectedfile;
		outfile = outfile.remove(datadir.absolutePath() + "/");
	}
	else
	{
		//copy the file over and resize it
		try
		{
			QString filename = selectedfile.section('/', -1);
			filename = filename.section('.', 0, 0);

			outfile = OutDirectory + "/" + filename + ".png";
			QString outfile2 = OutDirectory + "/" + filename + "_mini.png";


			QImage image(selectedfile);
			QImage scaledimg = image.scaled(QSize(100, 100), Qt::KeepAspectRatio, Qt::SmoothTransformation );
			scaledimg.save(QDir::currentPath()+"/"+outfile);

			QImage smallscaledimg = image.scaled(QSize(25, 25), Qt::KeepAspectRatio, Qt::SmoothTransformation );
			smallscaledimg.save(QDir::currentPath()+"/"+outfile2);

			outfile = outfile.section('/', 1);
		}
		catch(...)
		{
			QErrorMessage msgdial;
			msgdial.showMessage ( "Error copying the file to the data directory!" );
			outfile = "";
		}
	}

	return outfile;
}
Example #11
0
// read forms
void readCustomForms(QMenu *menu)
{
    QDir dir(datadir() + "/libs/");

    QStringList filter;
    filter << "*agros2d_forms_*";
    QStringList list = dir.entryList(filter);

    foreach (QString filename, list)
    {
        QString fn = QString("%1/%2").arg(dir.absolutePath()).arg(filename);
        if (QFile::exists(fn))
        {
            QPluginLoader *loader = new QPluginLoader(fn);

            if (!loader)
            {
                throw AgrosException(QObject::tr("Could not find '%1'").arg(fn));
            }


            if (!loader->load())
            {
                qDebug() << loader->errorString();
                delete loader;
                throw AgrosException(QObject::tr("Could not load '%1'. %2").arg(fn).arg(loader->errorString()));
            }

            assert(loader->instance());
            FormInterface *form = qobject_cast<FormInterface *>(loader->instance());
            delete loader;

            if (form)
            {
                qDebug() << QString("Form '%1' loaded.").arg(form->formId());
                menu->addAction(form->action());
            }
        }
    }
Example #12
0
// This function loads the file and verifies that it
// looks like a valid LCDHost layout class.
// Returns error message or QString() if we have it loaded.
QString LH_LuaClass::load( lua_State *L, QFileInfo fi, const char *datapath )
{
#ifndef QT_NO_DEBUG
    int old_top = lua_gettop(L);
#endif

    QString retv;
    QString filename = fi.fileName();
    QByteArray filename_array = filename.toLocal8Bit();
    const char *magic = NULL;

    if( datapath && *datapath )
    {
        QDir datadir(datapath);
        filename = datadir.relativeFilePath( fi.filePath() );
    }

    Q_ASSERT( L != NULL );

    // Check to see if the file is already loaded,
    // and if so, if it's been changed.
    foreach( LH_LuaClass *alc, list_ )
    {
        if( fi == alc->fi_ )
        {
            // Already loaded.
            if( (fi.lastModified() == alc->fi_.lastModified()) &&
                (fi.size() == alc->fi_.size() ) )
            {
                // Already loaded and not modified, so we're done
                Q_ASSERT( old_top == lua_gettop(L) );
                return retv;
            }

            // It's loaded, but it has been modified, so unload it
            delete alc;
            break;
        }
    }

    // Load the file contents
    QFile file( fi.filePath() );
    QByteArray contents;
    if( file.open( QIODevice::ReadOnly ) )
    {
        contents = file.readAll();
        file.close();
        if( contents.size() != fi.size() )
        {
            // Not ready for this yet, it seems
            retv = QString("%1 size mismatch %2 != %3").arg( filename ).arg(contents.size()).arg(fi.size());
            Q_ASSERT( old_top == lua_gettop(L) );
            goto bail_out;
        }
    }

    // Load the file contents into Lua
    if( luaL_loadbuffer( L, contents.constData(), contents.size(), filename_array.constData() ) )
    {
        // Meh, got an error
        const char *errormsg = lua_tostring(L,-1);
        retv = QString::fromLocal8Bit(errormsg);
        lua_pop(L,1);
        Q_ASSERT( old_top == lua_gettop(L) );
        goto bail_out;
    }

    // Compiled ok, now run it to build the module
    if( lua_pcall(L,0,1,0) )
    {
        // Well, that didn't work
        const char *errormsg = lua_tostring(L,-1);
        retv = QString::fromLocal8Bit(errormsg);
        lua_pop(L,1);
        Q_ASSERT( old_top == lua_gettop(L) );
        goto bail_out;
    }

    // Make sure that got us a table
    if( !lua_istable(L,-1) )
    {
        // this is probably a utility file then
        lua_pop(L,1);
        Q_ASSERT( old_top == lua_gettop(L) );
        return QString();
    }

    // Ensure the table has a 'magic' field
    lua_pushliteral(L,"magic");
    lua_rawget(L,-2);
    if( !lua_isstring(L,-1) )
    {
        retv = QString("%1 doesn't have a magic field").arg(filename);
        lua_pop(L,2);
        Q_ASSERT( old_top == lua_gettop(L) );
        goto bail_out;
    }

    // Check the magic value
    magic = lua_tostring(L,-1);
    if( !magic || strcmp(magic,LUA_MAGIC) )
    {
        retv = QString("%1 has the wrong magic").arg(filename);
        lua_pop(L,2);
        Q_ASSERT( old_top == lua_gettop(L) );
        goto bail_out;
    }
    lua_pop(L,1); // get rid of the magic value, leaving module on top

    // Make sure it has a reasonable id field
    lua_pushliteral(L,"class_id");
    lua_rawget(L,-2);
    if( !lua_isstring(L,-1) )
    {
        retv = QString("%1 doesn't have an id").arg(filename);
        lua_pop(L,2);
        Q_ASSERT( old_top == lua_gettop(L) );
        goto bail_out;
    }
    lua_pop(L,1); // looked good, pop it so the module is at top again

    // Create the class (needs module at stack top)
    new LH_LuaClass(L,fi,filename);
    lua_pop(L,1); // pop module

bail_out:
    Q_ASSERT( old_top == lua_gettop(L) );
    return retv;
}
Example #13
0
UnitTestsWidget::UnitTestsWidget(QWidget *parent)
    : QDialog(parent), m_test(XMLTest::tests()), m_isAborted(false)
{
    setWindowTitle(tr("Unit tests"));
    setModal(true);

    webView = new QWebView();
    webView->page()->setNetworkAccessManager(new QNetworkAccessManager());
    webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    webView->setMinimumSize(200, 200);

    logWidget = new LogWidget(this);
    logWidget->setMemoryLabelVisible(false);

    trvTests = new QTreeWidget(this);
    trvTests->setMouseTracking(true);
    trvTests->setColumnCount(1);
    trvTests->setIndentation(15);
    trvTests->setIconSize(QSize(24, 24));
    trvTests->setHeaderHidden(true);
    trvTests->setMinimumWidth(360);
    trvTests->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(trvTests, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(doContextMenu(const QPoint &)));
    // connect(trvTests, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(doItemDoubleClicked(QTreeWidgetItem *, int)));
    // connect(trvTests, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(doItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));

    btnRunTests = new QPushButton(tr("Run tests"));
    connect(btnRunTests, SIGNAL(clicked()), this, SLOT(runTestsFromSuite()));

    // dialog buttons
    btnScenarios = new QPushButton(tr("Scenarios..."));
    btnUncheckTests = new QPushButton(tr("Uncheck tests"));
    connect(btnUncheckTests, SIGNAL(clicked()), this, SLOT(uncheckTests()));
    btnStopTest = new QPushButton(tr("Stop"));
    btnStopTest->setEnabled(false);
    connect(btnStopTest, SIGNAL(clicked()), this, SLOT(stopTest()));

    QGridLayout *leftLayout = new QGridLayout();
    leftLayout->setContentsMargins(0, 0, 0, 0);
    leftLayout->addWidget(trvTests, 0, 0, 1, 5);
    leftLayout->addWidget(btnScenarios, 1, 0);
    leftLayout->addWidget(btnUncheckTests, 1, 1);
    leftLayout->setColumnStretch(2, 1);
    leftLayout->addWidget(btnStopTest, 1, 3);
    leftLayout->addWidget(btnRunTests, 1, 4);

    QWidget *leftWidget = new QWidget();
    leftWidget->setLayout(leftLayout);

    QVBoxLayout *rightLayout = new QVBoxLayout();
    rightLayout->addWidget(webView, 3);
    rightLayout->addWidget(logWidget, 1);

    QWidget *rightWidget = new QWidget();
    rightWidget->setLayout(rightLayout);

    splitter = new QSplitter(this);
    splitter->setOrientation(Qt::Horizontal);
    splitter->addWidget(leftWidget);
    splitter->addWidget(rightWidget);

    buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(doAccept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(doReject()));

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(splitter, 1);
    layout->addStretch();
    layout->addWidget(buttonBox);

    setLayout(layout);

    QSettings settings;
    splitter->restoreState(settings.value("UnitTestsWidget/SplitterState").toByteArray());
    splitter->restoreGeometry(settings.value("UnitTestsWidget/SplitterGeometry").toByteArray());
    restoreGeometry(settings.value("UnitTestsWidget/Geometry", saveGeometry()).toByteArray());

    // init ctemplate
    // stylesheet
    std::string style;
    ctemplate::TemplateDictionary stylesheet("style");
    stylesheet.SetValue("FONTFAMILY", htmlFontFamily().toStdString());
    stylesheet.SetValue("FONTSIZE", (QString("%1").arg(htmlFontSize() + 1).toStdString()));

    ctemplate::ExpandTemplate(compatibleFilename(datadir() + TEMPLATEROOT + "/panels/style_results.css").toStdString(), ctemplate::DO_NOT_STRIP, &stylesheet, &style);
    m_cascadeStyleSheet = QString::fromStdString(style);

    // read tests from test_suite
    readTestsFromSuite();
    readScenariosFromSuite();

    // read last test
    QDir dirUser(QString("%1/tests").arg(userDataDir()));
    if (!dirUser.exists())
        QDir(userDataDir()).mkpath(dirUser.absolutePath());

    dirUser.setFilter(QDir::Files | QDir::NoSymLinks);
    if (!dirUser.entryInfoList().isEmpty())
    {
        QString file = QString("%1").arg(dirUser.entryInfoList().last().absoluteFilePath());
        readTestFromDisk(file);
    }
}
Example #14
0
Config::Config()
{
    // set xml schemas dir
    Hermes::Hermes2D::Hermes2DApi.set_text_param_value(Hermes::Hermes2D::xmlSchemasDirPath, QString("%1/resources/xsd").arg(datadir()).toStdString());

    load();
}
Example #15
0
void PythonEngineAgros::addCustomFunctions()
{
    addFunctions(readFileContent(datadir() + "/resources/python/functions_agros2d.py"));
}
Example #16
0
QMap<QString, QString> Module::availableModules()
{
    static QMap<QString, QString> modules;

    // read modules
    if (modules.isEmpty())
    {
        QDir dir(datadir() + MODULEROOT);

        QStringList filter;
        filter << "*.xml";
        QStringList list = dir.entryList(filter);

        foreach (QString filename, list)
        {
            try
            {
                // todo: find a way to validate if required. If validated here, sensible error messages will be obtained
                bool validateAtTheBeginning = false;
                ::xml_schema::flags parsing_flags = xml_schema::flags::dont_validate;
                if(validateAtTheBeginning)
                {
                    parsing_flags = 0;
                    qDebug() << "Warning: Validating all XML files. This is time-consuming and should be switched off in module.cpp for release. Set validateAtTheBeginning = false.";
                }
                std::auto_ptr<XMLModule::module> module_xsd(XMLModule::module_(compatibleFilename(datadir() + MODULEROOT + "/" + filename).toStdString(), parsing_flags));

                XMLModule::module *mod = module_xsd.get();

                // module name
                modules[filename.left(filename.size() - 4)] = QString::fromStdString(mod->general().name());
            }
            catch (const xml_schema::expected_element& e)
            {
                QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.name()));
                qDebug() << str;
                throw AgrosException(str);
            }
            catch (const xml_schema::expected_attribute& e)
            {
                QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.name()));
                qDebug() << str;
                throw AgrosException(str);
            }
            catch (const xml_schema::unexpected_element& e)
            {
                QString str = QString("%1: %2 instead of %3").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.encountered_name())).arg(QString::fromStdString(e.expected_name()));
                qDebug() << str;
                throw AgrosException(str);
            }
            catch (const xml_schema::unexpected_enumerator& e)
            {
                QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.enumerator()));
                qDebug() << str;
                throw AgrosException(str);
            }
            catch (const xml_schema::expected_text_content& e)
            {
                QString str = QString("%1").arg(QString::fromStdString(e.what()));
                qDebug() << str;
                throw AgrosException(str);
            }
            catch (const xml_schema::parsing& e)
            {
                QString str = QString("%1").arg(QString::fromStdString(e.what()));
                qDebug() << str;
                xml_schema::diagnostics diagnostic = e.diagnostics();
                for(int i = 0; i < diagnostic.size(); i++)
                {
                    xml_schema::error err = diagnostic.at(i);
                    qDebug() << QString("%1, position %2:%3, %4").arg(QString::fromStdString(err.id())).arg(err.line()).arg(err.column()).arg(QString::fromStdString(err.message()));
                }
                throw AgrosException(str);
            }
            catch (const xml_schema::exception& e)
            {
                qDebug() << QString("Unknow parser exception: %1").arg(QString::fromStdString(e.what()));
                throw AgrosException(QString::fromStdString(e.what()));
            }
        }
    }
Example #17
0
CouplingList::CouplingList()
{
    // read couplings
    QDir dir(datadir() + COUPLINGROOT);

    QStringList filter;
    filter << "*.xml";
    QStringList list = dir.entryList(filter);

    foreach (QString filename, list)
    {
        try
        {
            // todo: this was copied from module. Find a way to do all catching at one place

            // todo: find a way to validate if required. If validated here, sensible error messages will be obtained
            bool validateAtTheBeginning = false;
            ::xml_schema::flags parsing_flags = xml_schema::flags::dont_validate;
            if(validateAtTheBeginning)
            {
                parsing_flags = 0;
                qDebug() << "Warning: Validating all XML files. This is time-consuming and should be switched off in coupling.cpp for release. Set validateAtTheBeginning = false.";
            }

            std::auto_ptr<XMLCoupling::coupling> coupling_xsd = XMLCoupling::coupling_(compatibleFilename(datadir() + COUPLINGROOT + "/" + filename).toStdString(),
                                                                                   xml_schema::flags::dont_validate & xml_schema::flags::dont_initialize);
            XMLCoupling::coupling *coup = coupling_xsd.get();

            // check whether coupling is available for values of source and target fields such as analysis type
            for (int i = 0; i < coup->volume().weakforms_volume().weakform_volume().size(); i++)
            {
                XMLCoupling::weakform_volume wf = coup->volume().weakforms_volume().weakform_volume().at(i);

                CouplingList::Item item;

                item.sourceField = QString::fromStdString(coup->general().modules().source().id());
                item.sourceAnalysisType = analysisTypeFromStringKey(QString::fromStdString(wf.sourceanalysis()));
                item.targetField = QString::fromStdString(coup->general().modules().target().id());
                item.targetAnalysisType = analysisTypeFromStringKey(QString::fromStdString(wf.targetanalysis()));
                item.couplingType = couplingTypeFromStringKey(QString::fromStdString(wf.couplingtype()));

                m_couplings.append(item);
            }
        }
        catch (const xml_schema::expected_element& e)
        {
            QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.name()));
            qDebug() << str;
            throw AgrosException(str);
        }
        catch (const xml_schema::expected_attribute& e)
        {
            QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.name()));
            qDebug() << str;
            throw AgrosException(str);
        }
        catch (const xml_schema::unexpected_element& e)
        {
            QString str = QString("%1: %2 instead of %3").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.encountered_name())).arg(QString::fromStdString(e.expected_name()));
            qDebug() << str;
            throw AgrosException(str);
        }
        catch (const xml_schema::unexpected_enumerator& e)
        {
            QString str = QString("%1: %2").arg(QString::fromStdString(e.what())).arg(QString::fromStdString(e.enumerator()));
            qDebug() << str;
            throw AgrosException(str);
        }
        catch (const xml_schema::expected_text_content& e)
        {
            QString str = QString("%1").arg(QString::fromStdString(e.what()));
            qDebug() << str;
            throw AgrosException(str);
        }
        catch (const xml_schema::parsing& e)
        {
            QString str = QString("%1").arg(QString::fromStdString(e.what()));
            qDebug() << str;
            xml_schema::diagnostics diagnostic = e.diagnostics();
            for(int i = 0; i < diagnostic.size(); i++)
            {
                xml_schema::error err = diagnostic.at(i);
                qDebug() << QString("%1, position %2:%3, %4").arg(QString::fromStdString(err.id())).arg(err.line()).arg(err.column()).arg(QString::fromStdString(err.message()));
            }
            throw AgrosException(str);
        }
        catch (const xml_schema::exception& e)
        {
            qDebug() << QString("Unknow parser exception: %1").arg(QString::fromStdString(e.what()));
            throw AgrosException(QString::fromStdString(e.what()));
        }
    }
}