<commit_before>// vi: set ts=2:
//
// $Id: mainframe.C,v 1.62.8.6 2007/06/12 05:42:24 oliver Exp $
//

#include "mainframe.h"
#include "icons.h"
#include "demoTutorialDialog.h"

#include <BALL/VIEW/RENDERING/POVRenderer.h>
#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/WIDGETS/molecularControl.h>
#include <BALL/VIEW/WIDGETS/geometricControl.h>
#include <BALL/VIEW/WIDGETS/logView.h>
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/WIDGETS/datasetControl.h>
#include <BALL/VIEW/WIDGETS/editableScene.h>
#include <BALL/VIEW/WIDGETS/fileObserver.h>
#include <BALL/VIEW/WIDGETS/testFramework.h>
#include <BALL/VIEW/DIALOGS/pubchemDialog.h>
#include <BALL/VIEW/DIALOGS/pluginDialog.h>
#include <BALL/VIEW/DIALOGS/downloadPDBFile.h>
#include <BALL/VIEW/DIALOGS/labelDialog.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>
#ifdef BALL_PYTHON_SUPPORT
#	include <BALL/VIEW/WIDGETS/pyWidget.h>
#endif

#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/COMMON/version.h>

#include <QtGui/QKeyEvent>
#include <QtGui/QTreeWidget>

#include <BALL/CONCEPT/moleculeObjectCreator.h>
#ifdef BALL_HAS_ASIO
#include <BALL/VIEW/KERNEL/serverWidget.h>
#endif

#ifdef BALL_COMPILER_MSVC
# include "ui_aboutDialog.h"
#else
# include "aboutDialog.h"
#endif
#include <BALL/VIEW/DIALOGS/pluginDialog.h>

using namespace std;
//#define BALL_VIEW_DEBUG

namespace BALL
{
	using namespace std;
	using namespace BALL::VIEW;

	Mainframe::Mainframe(QWidget* parent, const char* name)
		:	MainControl(parent, name, ".BALLView"),
			scene_(0)
	{
		#ifdef BALL_VIEW_DEBUG
		Log.error() << "new Mainframe " << this << std::endl;
		#endif

		// ---------------------
		// setup main window
		// ---------------------
		setWindowTitle("BALLView");
		setWindowIcon(QPixmap(bucky_64x64_xpm));
		// make sure submenus are the first
		initPopupMenu(FILE_OPEN);
		initPopupMenu(EDIT);
		initPopupMenu(BUILD);
		initPopupMenu(DISPLAY);
		initPopupMenu(MOLECULARMECHANICS);
		initPopupMenu(TOOLS);
	#ifdef BALL_PYTHON_SUPPORT
		initPopupMenu(TOOLS_PYTHON);
		initPopupMenu(MainControl::USER);
	#endif
		initPopupMenu(WINDOWS);
		initPopupMenu(MACRO);

		// ---------------------
		// Logstream setup -----
		// ---------------------
//   		Log.remove(std::cout);
//   		Log.remove(std::cerr);
		setLoggingFilename("BALLView.log");

		// Display Menu
		insertMenuEntry(MainControl::DISPLAY, "Toggle Fullscreen", this, SLOT(toggleFullScreen()),
										Qt::ALT+Qt::Key_X);
		insertPopupMenuSeparator(DISPLAY);
		initPopupMenu(DISPLAY_VIEWPOINT);

		new MolecularFileDialog(this, "MolecularFileDialog");
		new DownloadPDBFile(		this, "DownloadPDBFile", false);
		new PubChemDialog(this, "PubChemDialog");
		new PluginDialog(this, "PluginDialog");
 		addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, "Structures"));
		addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, "Representations"));
		addDockWidget(Qt::TopDockWidgetArea,  new DatasetControl(this, "Datasets"));
		DatasetControl* dc = DatasetControl::getInstance(0);
		dc->registerController(new RegularData3DController());
		dc->registerController(new TrajectoryController());
		dc->registerController(new VectorGridController());
		dc->registerController(new DockResultController());
		dc->registerController(new RaytraceableGridController());

		DatasetControl::getInstance(0)->hide();

		new DemoTutorialDialog(this, "BALLViewDemo");

		HelpViewer* BALL_docu = new HelpViewer(this, "BALL Docu");
		addDockWidget(Qt::BottomDockWidgetArea, BALL_docu);
		String dirp = getDataPath() + ".." + FileSystem::PATH_SEPARATOR + "doc" +
									FileSystem::PATH_SEPARATOR + "BALL" + FileSystem::PATH_SEPARATOR;
		BALL_docu->setBaseDirectory(dirp);
		BALL_docu->setWhatsThisEnabled(false);
		BALL_docu->setProject("BALL");
		BALL_docu->setDefaultPage("index.htm");

		addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu"));

		new LabelDialog(				this, "LabelDialog");
		new MolecularStructure(	this, "MolecularStructure");
 		addDockWidget(Qt::BottomDockWidgetArea, new LogView(this, "Logs"));
		addDockWidget(Qt::BottomDockWidgetArea, new FileObserver(  this, "FileObserver"));

		Scene::stereoBufferSupportTest();
		scene_ = new EditableScene(this, "3D View");
		setCentralWidget(scene_);
		setAcceptDrops(true);

		new DisplayProperties(	this, "DisplayProperties");

		// setup the VIEW server
		#ifdef BALL_HAS_ASIO
			ServerWidget* server = new ServerWidget(this);
		// registering object generator
		MoleculeObjectCreator* object_creator = new MoleculeObjectCreator;
		server->registerObjectCreator(*object_creator);
		#endif

		new TestFramework(this, "Test Framework");

		#ifdef BALL_PYTHON_SUPPORT
			addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, "Python Interpreter"));
		#endif

		// ---------------------
		// Menus ---------------
		// ---------------------
		String hint;

		insertMenuEntry(MainControl::FILE_OPEN, "Project", this, SLOT(loadBALLViewProjectFile()));

		save_project_action_ = insertMenuEntry(MainControl::FILE, "Save Project", this,
										SLOT(saveBALLViewProjectFile()));

			// Help-Menu -------------------------------------------------------------------
		QAction* action = 0;
		action = insertMenuEntry(MainControl::HELP, "About", this, SLOT(about()));
		setMenuHint(action, "Show informations on this version of BALLView");
		action = insertMenuEntry(MainControl::HELP, "How to cite", this, SLOT(howToCite()));
		setMenuHint(action, "Show infos on how to cite BALL and BALLView");

		stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, "Abort Calculation", this,
										SLOT(stopSimulation()), Qt::ALT+Qt::Key_C);
		stop_simulation_action_->setEnabled(false);
		insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);
		setMenuHint(stop_simulation_action_, "Abort a running simulation");
		Path path;
		String filename = path.find("graphics/stop.png");
		stop_simulation_action_->setIcon(QIcon(filename.c_str()));

		complement_selection_action_ = insertMenuEntry(MainControl::EDIT, "Toggle Selection", this, SLOT(complementSelection()));

 		qApp->installEventFilter(this);

		setStatusbarText("Ready.");

	}

	Mainframe::~Mainframe()
		throw()
	{
	}

	bool Mainframe::eventFilter(QObject* sender, QEvent* event)
	{
		if (event->type() != QEvent::KeyPress) return false;

		QKeyEvent* e = dynamic_cast<QKeyEvent*>(event);

		if (e->key() == Qt::Key_Escape &&
				HelpViewer::getInstance(1)->isWhatsThisEnabled())
		{
			HelpViewer::getInstance(1)->exitWhatsThisMode();
		}

		QPoint point = QCursor::pos();
		QWidget* widget = qApp->widgetAt(point);
		if (widget == scene_ &&
 				qApp->focusWidget() != scene_)
		{
 			scene_->keyPressEvent(e);
			return true;
		}

		if (widget != scene_ &&
        e->key() == Qt::Key_Escape)
		{
 			scene_->switchToLastMode();
			return true;
		}

 		if (e->key() == Qt::Key_Delete &&
				RTTI::isKindOf<QTreeWidget>(*sender))
 		{
 			deleteClicked();
			return true;
 		}

		if (e->key() == Qt::Key_Enter)
		{
			if (composite_manager_.getNumberOfComposites() == 0) return false;

			if (getMolecularControlSelection().size() == 0)
			{
				control_selection_.push_back(*composite_manager_.begin());
			}

			MolecularStructure::getInstance(0)->centerCamera();
			return true;
		}

		// check all menu entries if Alt or CTRL is pressed to enable shortcuts
		if (e->key() == Qt::Key_Alt ||
				e->key() == Qt::Key_Control)
		{
			checkMenus();
			return false;
		}

		#ifdef BALL_PYTHON_SUPPORT
 			PyWidget::getInstance(0)->reactTo(*e);
			e->accept();
		#endif

		return false;
	}

	void Mainframe::reset()
	{
		if (composites_locked_ || getRepresentationManager().updateRunning()) return;

		clearData();

		DisplayProperties* dp = DisplayProperties::getInstance(0);
		dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
		dp->selectModel(MODEL_STICK);
		dp->selectColoringMethod(COLORING_ELEMENT);
		dp->selectMode(DRAWING_MODE_SOLID);
		dp->setTransparency(0);
		dp->setSurfaceDrawingPrecision(6.5);
	}

	void Mainframe::howToCite()
	{
		HelpViewer::getInstance(1)->showHelp("tips.html", "cite");
	}

	void Mainframe::show()
	{
		// prevent multiple inserting of menu entries, by calls of showFullScreen(), ...
		if (preferences_action_ != 0)
		{
			MainControl::show();
			return;
		}

		QToolBar* tb = new QToolBar("Main Toolbar", this);
		tb->setObjectName("Main Toolbar");
		tb->setIconSize(QSize(23,23));
		tb->layout()->setMargin(2);
		tb->layout()->setSpacing(2);
		addToolBar(Qt::TopToolBarArea, tb);

		MainControl::show();

		initPopupMenu(MainControl::WINDOWS)->addSeparator();
		initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());
		MolecularFileDialog::getInstance(0)->addToolBarEntries(tb);
		DownloadPDBFile::getInstance(0)->addToolBarEntries(tb);
		PubChemDialog::getInstance(0)->addToolBarEntries(tb);
		Path path;

		QIcon load_icon(path.find("graphics/quickload.png").c_str());
		qload_action_ = new QAction(load_icon, "quickload", this);
		qload_action_->setObjectName("quickload");
		connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));
		HelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, "tips.html#quickload");
		tb->addAction(qload_action_);

		QIcon save_icon(path.find("graphics/quicksave.png").c_str());
		qsave_action_ = new QAction(save_icon, "quicksave", this);
		qsave_action_->setObjectName("quicksave");
		connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));
		HelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, "tips.html#quickload");
		tb->addAction(qsave_action_);

		tb->addSeparator();
		DisplayProperties::getInstance(0)->addToolBarEntries(tb);
		MolecularStructure::getInstance(0)->addToolBarEntries(tb);
		scene_->addToolBarEntries(tb);
		tb->addAction(stop_simulation_action_);
		tb->addAction(preferences_action_);
		HelpViewer::getInstance(1)->addToolBarEntries(tb);

		// we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have
		// to restore the window state again!
		restoreWindows();

		// finally, apply all values our modular widgets have fetched from their preferences
		applyPreferences();
	}

	void Mainframe::about()
	{
		// Display about dialog
		QDialog w;
 		Ui_AboutDialog about;
		about.setupUi(&w);
		QString version = QString("QT ") + qVersion();
#ifdef BALL_QT_HAS_THREADS
		version += "(mt)";
#endif
		about.qt_version_label->setText(version);
		QFont font = about.BALLView_version_label->font();
		about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING);
		font.setPixelSize(18);
		about.BALLView_version_label->setFont(font);
		about.BALL_version_label->setText(__DATE__);
		w.exec();
	}

}
<commit_msg>Disabled plugin dialog on Windows as long as we have never tested that.<commit_after>// vi: set ts=2:
//
// $Id: mainframe.C,v 1.62.8.6 2007/06/12 05:42:24 oliver Exp $
//

#include "mainframe.h"
#include "icons.h"
#include "demoTutorialDialog.h"

#include <BALL/VIEW/RENDERING/POVRenderer.h>
#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/WIDGETS/molecularControl.h>
#include <BALL/VIEW/WIDGETS/geometricControl.h>
#include <BALL/VIEW/WIDGETS/logView.h>
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/WIDGETS/datasetControl.h>
#include <BALL/VIEW/WIDGETS/editableScene.h>
#include <BALL/VIEW/WIDGETS/fileObserver.h>
#include <BALL/VIEW/WIDGETS/testFramework.h>
#include <BALL/VIEW/DIALOGS/pubchemDialog.h>
#include <BALL/VIEW/DIALOGS/downloadPDBFile.h>
#include <BALL/VIEW/DIALOGS/labelDialog.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>
#ifdef BALL_PYTHON_SUPPORT
#	include <BALL/VIEW/WIDGETS/pyWidget.h>
#endif

#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/COMMON/version.h>

#include <QtGui/QKeyEvent>
#include <QtGui/QTreeWidget>

#include <BALL/CONCEPT/moleculeObjectCreator.h>
#ifdef BALL_HAS_ASIO
#include <BALL/VIEW/KERNEL/serverWidget.h>
#endif

#ifdef BALL_COMPILER_MSVC
# include "ui_aboutDialog.h"
#else
# include "aboutDialog.h"
#endif

// NOTE: this does not yet work correctly on windows
#ifndef BALL_COMPILER_MSVC
#include <BALL/VIEW/DIALOGS/pluginDialog.h>
#endif

using namespace std;
//#define BALL_VIEW_DEBUG

namespace BALL
{
	using namespace std;
	using namespace BALL::VIEW;

	Mainframe::Mainframe(QWidget* parent, const char* name)
		:	MainControl(parent, name, ".BALLView"),
			scene_(0)
	{
		#ifdef BALL_VIEW_DEBUG
		Log.error() << "new Mainframe " << this << std::endl;
		#endif

		// ---------------------
		// setup main window
		// ---------------------
		setWindowTitle("BALLView");
		setWindowIcon(QPixmap(bucky_64x64_xpm));
		// make sure submenus are the first
		initPopupMenu(FILE_OPEN);
		initPopupMenu(EDIT);
		initPopupMenu(BUILD);
		initPopupMenu(DISPLAY);
		initPopupMenu(MOLECULARMECHANICS);
		initPopupMenu(TOOLS);
	#ifdef BALL_PYTHON_SUPPORT
		initPopupMenu(TOOLS_PYTHON);
		initPopupMenu(MainControl::USER);
	#endif
		initPopupMenu(WINDOWS);
		initPopupMenu(MACRO);

		// ---------------------
		// Logstream setup -----
		// ---------------------
//   		Log.remove(std::cout);
//   		Log.remove(std::cerr);
		setLoggingFilename("BALLView.log");

		// Display Menu
		insertMenuEntry(MainControl::DISPLAY, "Toggle Fullscreen", this, SLOT(toggleFullScreen()),
										Qt::ALT+Qt::Key_X);
		insertPopupMenuSeparator(DISPLAY);
		initPopupMenu(DISPLAY_VIEWPOINT);

		new MolecularFileDialog(this, "MolecularFileDialog");
		new DownloadPDBFile(		this, "DownloadPDBFile", false);
		new PubChemDialog(this, "PubChemDialog");
#ifndef BALL_COMPILER_MSVC
		new PluginDialog(this, "PluginDialog");
#endif
 		addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, "Structures"));
		addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, "Representations"));
		addDockWidget(Qt::TopDockWidgetArea,  new DatasetControl(this, "Datasets"));
		DatasetControl* dc = DatasetControl::getInstance(0);
		dc->registerController(new RegularData3DController());
		dc->registerController(new TrajectoryController());
		dc->registerController(new VectorGridController());
		dc->registerController(new DockResultController());
		dc->registerController(new RaytraceableGridController());

		DatasetControl::getInstance(0)->hide();

		new DemoTutorialDialog(this, "BALLViewDemo");

		HelpViewer* BALL_docu = new HelpViewer(this, "BALL Docu");
		addDockWidget(Qt::BottomDockWidgetArea, BALL_docu);
		String dirp = getDataPath() + ".." + FileSystem::PATH_SEPARATOR + "doc" +
									FileSystem::PATH_SEPARATOR + "BALL" + FileSystem::PATH_SEPARATOR;
		BALL_docu->setBaseDirectory(dirp);
		BALL_docu->setWhatsThisEnabled(false);
		BALL_docu->setProject("BALL");
		BALL_docu->setDefaultPage("index.htm");

		addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu"));

		new LabelDialog(				this, "LabelDialog");
		new MolecularStructure(	this, "MolecularStructure");
 		addDockWidget(Qt::BottomDockWidgetArea, new LogView(this, "Logs"));
		addDockWidget(Qt::BottomDockWidgetArea, new FileObserver(  this, "FileObserver"));

		Scene::stereoBufferSupportTest();
		scene_ = new EditableScene(this, "3D View");
		setCentralWidget(scene_);
		setAcceptDrops(true);

		new DisplayProperties(	this, "DisplayProperties");

		// setup the VIEW server
		#ifdef BALL_HAS_ASIO
			ServerWidget* server = new ServerWidget(this);
		// registering object generator
		MoleculeObjectCreator* object_creator = new MoleculeObjectCreator;
		server->registerObjectCreator(*object_creator);
		#endif

		new TestFramework(this, "Test Framework");

		#ifdef BALL_PYTHON_SUPPORT
			addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, "Python Interpreter"));
		#endif

		// ---------------------
		// Menus ---------------
		// ---------------------
		String hint;

		insertMenuEntry(MainControl::FILE_OPEN, "Project", this, SLOT(loadBALLViewProjectFile()));

		save_project_action_ = insertMenuEntry(MainControl::FILE, "Save Project", this,
										SLOT(saveBALLViewProjectFile()));

			// Help-Menu -------------------------------------------------------------------
		QAction* action = 0;
		action = insertMenuEntry(MainControl::HELP, "About", this, SLOT(about()));
		setMenuHint(action, "Show informations on this version of BALLView");
		action = insertMenuEntry(MainControl::HELP, "How to cite", this, SLOT(howToCite()));
		setMenuHint(action, "Show infos on how to cite BALL and BALLView");

		stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, "Abort Calculation", this,
										SLOT(stopSimulation()), Qt::ALT+Qt::Key_C);
		stop_simulation_action_->setEnabled(false);
		insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);
		setMenuHint(stop_simulation_action_, "Abort a running simulation");
		Path path;
		String filename = path.find("graphics/stop.png");
		stop_simulation_action_->setIcon(QIcon(filename.c_str()));

		complement_selection_action_ = insertMenuEntry(MainControl::EDIT, "Toggle Selection", this, SLOT(complementSelection()));

 		qApp->installEventFilter(this);

		setStatusbarText("Ready.");

	}

	Mainframe::~Mainframe()
		throw()
	{
	}

	bool Mainframe::eventFilter(QObject* sender, QEvent* event)
	{
		if (event->type() != QEvent::KeyPress) return false;

		QKeyEvent* e = dynamic_cast<QKeyEvent*>(event);

		if (e->key() == Qt::Key_Escape &&
				HelpViewer::getInstance(1)->isWhatsThisEnabled())
		{
			HelpViewer::getInstance(1)->exitWhatsThisMode();
		}

		QPoint point = QCursor::pos();
		QWidget* widget = qApp->widgetAt(point);
		if (widget == scene_ &&
 				qApp->focusWidget() != scene_)
		{
 			scene_->keyPressEvent(e);
			return true;
		}

		if (widget != scene_ &&
        e->key() == Qt::Key_Escape)
		{
 			scene_->switchToLastMode();
			return true;
		}

 		if (e->key() == Qt::Key_Delete &&
				RTTI::isKindOf<QTreeWidget>(*sender))
 		{
 			deleteClicked();
			return true;
 		}

		if (e->key() == Qt::Key_Enter)
		{
			if (composite_manager_.getNumberOfComposites() == 0) return false;

			if (getMolecularControlSelection().size() == 0)
			{
				control_selection_.push_back(*composite_manager_.begin());
			}

			MolecularStructure::getInstance(0)->centerCamera();
			return true;
		}

		// check all menu entries if Alt or CTRL is pressed to enable shortcuts
		if (e->key() == Qt::Key_Alt ||
				e->key() == Qt::Key_Control)
		{
			checkMenus();
			return false;
		}

		#ifdef BALL_PYTHON_SUPPORT
 			PyWidget::getInstance(0)->reactTo(*e);
			e->accept();
		#endif

		return false;
	}

	void Mainframe::reset()
	{
		if (composites_locked_ || getRepresentationManager().updateRunning()) return;

		clearData();

		DisplayProperties* dp = DisplayProperties::getInstance(0);
		dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
		dp->selectModel(MODEL_STICK);
		dp->selectColoringMethod(COLORING_ELEMENT);
		dp->selectMode(DRAWING_MODE_SOLID);
		dp->setTransparency(0);
		dp->setSurfaceDrawingPrecision(6.5);
	}

	void Mainframe::howToCite()
	{
		HelpViewer::getInstance(1)->showHelp("tips.html", "cite");
	}

	void Mainframe::show()
	{
		// prevent multiple inserting of menu entries, by calls of showFullScreen(), ...
		if (preferences_action_ != 0)
		{
			MainControl::show();
			return;
		}

		QToolBar* tb = new QToolBar("Main Toolbar", this);
		tb->setObjectName("Main Toolbar");
		tb->setIconSize(QSize(23,23));
		tb->layout()->setMargin(2);
		tb->layout()->setSpacing(2);
		addToolBar(Qt::TopToolBarArea, tb);

		MainControl::show();

		initPopupMenu(MainControl::WINDOWS)->addSeparator();
		initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());
		MolecularFileDialog::getInstance(0)->addToolBarEntries(tb);
		DownloadPDBFile::getInstance(0)->addToolBarEntries(tb);
		PubChemDialog::getInstance(0)->addToolBarEntries(tb);
		Path path;

		QIcon load_icon(path.find("graphics/quickload.png").c_str());
		qload_action_ = new QAction(load_icon, "quickload", this);
		qload_action_->setObjectName("quickload");
		connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));
		HelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, "tips.html#quickload");
		tb->addAction(qload_action_);

		QIcon save_icon(path.find("graphics/quicksave.png").c_str());
		qsave_action_ = new QAction(save_icon, "quicksave", this);
		qsave_action_->setObjectName("quicksave");
		connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));
		HelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, "tips.html#quickload");
		tb->addAction(qsave_action_);

		tb->addSeparator();
		DisplayProperties::getInstance(0)->addToolBarEntries(tb);
		MolecularStructure::getInstance(0)->addToolBarEntries(tb);
		scene_->addToolBarEntries(tb);
		tb->addAction(stop_simulation_action_);
		tb->addAction(preferences_action_);
		HelpViewer::getInstance(1)->addToolBarEntries(tb);

		// we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have
		// to restore the window state again!
		restoreWindows();

		// finally, apply all values our modular widgets have fetched from their preferences
		applyPreferences();
	}

	void Mainframe::about()
	{
		// Display about dialog
		QDialog w;
 		Ui_AboutDialog about;
		about.setupUi(&w);
		QString version = QString("QT ") + qVersion();
#ifdef BALL_QT_HAS_THREADS
		version += "(mt)";
#endif
		about.qt_version_label->setText(version);
		QFont font = about.BALLView_version_label->font();
		about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING);
		font.setPixelSize(18);
		about.BALLView_version_label->setFont(font);
		about.BALL_version_label->setText(__DATE__);
		w.exec();
	}

}
<|endoftext|>


<commit_before>#ifndef __STRICT_FSTREAM_HPP
#define __STRICT_FSTREAM_HPP

#include <cassert>
#include <fstream>
#include <cstring>
#include <string>

/**
 * This namespace defines wrappers for std::ifstream, std::ofstream, and
 * std::fstream objects. The wrappers perform the following steps:
 * - check the open modes make sense
 * - check that the call to open() is successful
 * - (for input streams) check that the opened file is peek-able
 * - turn on the badbit in the exception mask
 */
namespace strict_fstream
{

/// Overload of error-reporting function, to enable use with VS.
/// Ref: http://stackoverflow.com/a/901316/717706
static std::string strerror()
{
    std::string buff(80, '\0');
#ifdef _WIN32
    if (strerror_s(&buff[0], buff.size(), errno) != 0)
    {
        buff = "Unknown error";
    }
#elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
// XSI-compliant strerror_r()
    if (strerror_r(errno, &buff[0], buff.size()) != 0)
    {
        buff = "Unknown error";
    }
#else
// GNU-specific strerror_r()
    auto p = strerror_r(errno, &buff[0], buff.size());
    std::string tmp(p, std::strlen(p));
    std::swap(buff, tmp);
#endif
    buff.resize(buff.find('\0'));
    return buff;
}

/// Exception class thrown by failed operations.
class Exception
    : public std::exception
{
public:
    Exception(const std::string& msg) : _msg(msg) {}
    const char * what() const noexcept { return _msg.c_str(); }
private:
    std::string _msg;
}; // class Exception

namespace detail
{

struct static_method_holder
{
    static std::string mode_to_string(std::ios_base::openmode mode)
    {
        static const int n_modes = 6;
        static const std::ios_base::openmode mode_val_v[n_modes] =
            {
                std::ios_base::in,
                std::ios_base::out,
                std::ios_base::app,
                std::ios_base::ate,
                std::ios_base::trunc,
                std::ios_base::binary
            };

        static const char * mode_name_v[n_modes] =
            {
                "in",
                "out",
                "app",
                "ate",
                "trunc",
                "binary"
            };
        std::string res;
        for (int i = 0; i < n_modes; ++i)
        {
            if (mode & mode_val_v[i])
            {
                res += (! res.empty()? "|" : "");
                res += mode_name_v[i];
            }
        }
        if (res.empty()) res = "none";
        return res;
    }
    static void check_mode(const std::string& filename, std::ios_base::openmode mode)
    {
        if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out");
        }
        else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out");
        }
        else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app");
        }
     }
    static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode)
    {
        if (s_p->fail())
        {
            throw Exception(std::string("strict_fstream: open('")
                            + filename + "'," + mode_to_string(mode) + "): open failed: "
                            + strerror());
        }
    }
    static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode)
    {
        bool peek_failed = true;
        try
        {
            is_p->peek();
            peek_failed = is_p->fail();
        }
        catch (std::ios_base::failure e) {}
        if (peek_failed)
        {
            throw Exception(std::string("strict_fstream: open('")
                            + filename + "'," + mode_to_string(mode) + "): peek failed: "
                            + strerror());
        }
        is_p->clear();
    }
}; // struct static_method_holder

} // namespace detail

class ifstream
    : public std::ifstream
{
public:
    ifstream() = default;
    ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        mode |= std::ios_base::in;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::ifstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
        detail::static_method_holder::check_peek(this, filename, mode);
    }
}; // class ifstream

class ofstream
    : public std::ofstream
{
public:
    ofstream() = default;
    ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
    {
        mode |= std::ios_base::out;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::ofstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
    }
}; // class ofstream

class fstream
    : public std::fstream
{
public:
    fstream() = default;
    fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        if (! (mode & std::ios_base::out)) mode |= std::ios_base::in;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::fstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
        detail::static_method_holder::check_peek(this, filename, mode);
    }
}; // class fstream

} // namespace strict_fstream

#endif
<commit_msg>Fix compilation on gcc 8<commit_after>#ifndef __STRICT_FSTREAM_HPP
#define __STRICT_FSTREAM_HPP

#include <cassert>
#include <fstream>
#include <cstring>
#include <string>

/**
 * This namespace defines wrappers for std::ifstream, std::ofstream, and
 * std::fstream objects. The wrappers perform the following steps:
 * - check the open modes make sense
 * - check that the call to open() is successful
 * - (for input streams) check that the opened file is peek-able
 * - turn on the badbit in the exception mask
 */
namespace strict_fstream
{

/// Overload of error-reporting function, to enable use with VS.
/// Ref: http://stackoverflow.com/a/901316/717706
static std::string strerror()
{
    std::string buff(80, '\0');
#ifdef _WIN32
    if (strerror_s(&buff[0], buff.size(), errno) != 0)
    {
        buff = "Unknown error";
    }
#elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
// XSI-compliant strerror_r()
    if (strerror_r(errno, &buff[0], buff.size()) != 0)
    {
        buff = "Unknown error";
    }
#else
// GNU-specific strerror_r()
    auto p = strerror_r(errno, &buff[0], buff.size());
    std::string tmp(p, std::strlen(p));
    std::swap(buff, tmp);
#endif
    buff.resize(buff.find('\0'));
    return buff;
}

/// Exception class thrown by failed operations.
class Exception
    : public std::exception
{
public:
    Exception(const std::string& msg) : _msg(msg) {}
    const char * what() const noexcept { return _msg.c_str(); }
private:
    std::string _msg;
}; // class Exception

namespace detail
{

struct static_method_holder
{
    static std::string mode_to_string(std::ios_base::openmode mode)
    {
        static const int n_modes = 6;
        static const std::ios_base::openmode mode_val_v[n_modes] =
            {
                std::ios_base::in,
                std::ios_base::out,
                std::ios_base::app,
                std::ios_base::ate,
                std::ios_base::trunc,
                std::ios_base::binary
            };

        static const char * mode_name_v[n_modes] =
            {
                "in",
                "out",
                "app",
                "ate",
                "trunc",
                "binary"
            };
        std::string res;
        for (int i = 0; i < n_modes; ++i)
        {
            if (mode & mode_val_v[i])
            {
                res += (! res.empty()? "|" : "");
                res += mode_name_v[i];
            }
        }
        if (res.empty()) res = "none";
        return res;
    }
    static void check_mode(const std::string& filename, std::ios_base::openmode mode)
    {
        if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out");
        }
        else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out");
        }
        else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app))
        {
            throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app");
        }
     }
    static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode)
    {
        if (s_p->fail())
        {
            throw Exception(std::string("strict_fstream: open('")
                            + filename + "'," + mode_to_string(mode) + "): open failed: "
                            + strerror());
        }
    }
    static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode)
    {
        bool peek_failed = true;
        try
        {
            is_p->peek();
            peek_failed = is_p->fail();
        }
        catch (const std::ios_base::failure &e) {}
        if (peek_failed)
        {
            throw Exception(std::string("strict_fstream: open('")
                            + filename + "'," + mode_to_string(mode) + "): peek failed: "
                            + strerror());
        }
        is_p->clear();
    }
}; // struct static_method_holder

} // namespace detail

class ifstream
    : public std::ifstream
{
public:
    ifstream() = default;
    ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        mode |= std::ios_base::in;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::ifstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
        detail::static_method_holder::check_peek(this, filename, mode);
    }
}; // class ifstream

class ofstream
    : public std::ofstream
{
public:
    ofstream() = default;
    ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
    {
        mode |= std::ios_base::out;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::ofstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
    }
}; // class ofstream

class fstream
    : public std::fstream
{
public:
    fstream() = default;
    fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        open(filename, mode);
    }
    void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
    {
        if (! (mode & std::ios_base::out)) mode |= std::ios_base::in;
        exceptions(std::ios_base::badbit);
        detail::static_method_holder::check_mode(filename, mode);
        std::fstream::open(filename, mode);
        detail::static_method_holder::check_open(this, filename, mode);
        detail::static_method_holder::check_peek(this, filename, mode);
    }
}; // class fstream

} // namespace strict_fstream

#endif
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>

#include <dune/xt/grid/type_traits.hh>

#include <dune/gdt/local/integrands/interfaces.hh>

#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>

#ifndef PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH
#  define PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH

namespace Dune {
namespace GDT {
namespace bindings {

template <class E, size_t r = 1, size_t rC = 1, class RF = double, class F = double>
class LocalUnaryElementIntegrandInterface
{
protected:
  using G = XT::Grid::extract_grid_t<E>;
  static const size_t d = G::dimension;
  using type = GDT::LocalUnaryElementIntegrandInterface<E, r, rC, RF, F>;
  using bound_type = pybind11::class_<type>;

  template <class T, typename... options>
  static void bind_methods(pybind11::class_<T, options...>& c)
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    c.def("copy_as_unary_element_integrand", [](const type& self) { return self.copy_as_unary_element_integrand(); });
    c.def("__add__", [](type& self, type& other) { return self + other; }, "other"_a, py::is_operator());
    c.def("__iadd__", [](type& self, type& other) { return self + other; }, "other"_a, py::is_operator());
    // order/evaluate
    // ...
    //    c.def("__repr__", [](const type& self) {
    //      std::stringstream ss;
    //      ss << self;
    //      return ss.str();
    //    });
  } // ... bind_methods(...)

  static std::string id(const std::string& grid_id, const std::string& layer_id)
  {
    std::string ret = grid_id;
    if (!layer_id.empty())
      ret += "_" + layer_id;
    ret += "_" + XT::Common::to_string(r) + "d";
    if (rC > 1)
      ret += "x" + XT::Common::to_string(rC) + "d";
    if (!std::is_same<RF, double>::value)
      ret += "_" + XT::Common::Typename<RF>::value(/*fail_wo_typeid=*/true);
    ret += "_test_basis";
    ret += ret;
    ret += "_to_scalar";
    if (!std::is_same<F, double>::value)
      ret += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
    return ret;
  } // ... id(...)

public:
  static bound_type bind(pybind11::module& m,
                         const std::string& class_id = "local_unary_element_integrand",
                         const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
                         const std::string& layer_id = "")
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    const auto class_name = class_id + "_" + id(grid_id, layer_id) + "_interfaces";
    const auto ClassName = XT::Common::to_camel_case(class_name);
    bound_type c(m, ClassName.c_str(), ClassName.c_str());
    // static information about dims
    // ...
    bind_methods(c);

    return c;
  } // ... bind(...)
}; // class LocalUnaryElementIntegrandInterface

} // namespace bindings
} // namespace GDT
} // namespace Dune

#endif // PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH
<commit_msg>fix header guard<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#ifndef PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH
#define PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH

#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>

#include <dune/xt/grid/type_traits.hh>

#include <dune/gdt/local/integrands/interfaces.hh>

#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>

namespace Dune {
namespace GDT {
namespace bindings {

template <class E, size_t r = 1, size_t rC = 1, class RF = double, class F = double>
class LocalUnaryElementIntegrandInterface
{
protected:
  using G = XT::Grid::extract_grid_t<E>;
  static const size_t d = G::dimension;
  using type = GDT::LocalUnaryElementIntegrandInterface<E, r, rC, RF, F>;
  using bound_type = pybind11::class_<type>;

  template <class T, typename... options>
  static void bind_methods(pybind11::class_<T, options...>& c)
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    c.def("copy_as_unary_element_integrand", [](const type& self) { return self.copy_as_unary_element_integrand(); });
    c.def("__add__", [](type& self, type& other) { return self + other; }, "other"_a, py::is_operator());
    c.def("__iadd__", [](type& self, type& other) { return self + other; }, "other"_a, py::is_operator());
    // order/evaluate
    // ...
    //    c.def("__repr__", [](const type& self) {
    //      std::stringstream ss;
    //      ss << self;
    //      return ss.str();
    //    });
  } // ... bind_methods(...)

  static std::string id(const std::string& grid_id, const std::string& layer_id)
  {
    std::string ret = grid_id;
    if (!layer_id.empty())
      ret += "_" + layer_id;
    ret += "_" + XT::Common::to_string(r) + "d";
    if (rC > 1)
      ret += "x" + XT::Common::to_string(rC) + "d";
    if (!std::is_same<RF, double>::value)
      ret += "_" + XT::Common::Typename<RF>::value(/*fail_wo_typeid=*/true);
    ret += "_test_basis";
    ret += ret;
    ret += "_to_scalar";
    if (!std::is_same<F, double>::value)
      ret += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
    return ret;
  } // ... id(...)

public:
  static bound_type bind(pybind11::module& m,
                         const std::string& class_id = "local_unary_element_integrand",
                         const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
                         const std::string& layer_id = "")
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    const auto class_name = class_id + "_" + id(grid_id, layer_id) + "_interfaces";
    const auto ClassName = XT::Common::to_camel_case(class_name);
    bound_type c(m, ClassName.c_str(), ClassName.c_str());
    // static information about dims
    // ...
    bind_methods(c);

    return c;
  } // ... bind(...)
}; // class LocalUnaryElementIntegrandInterface

} // namespace bindings
} // namespace GDT
} // namespace Dune

#endif // PYTHON_DUNE_GDT_LOCAL_INTEGRANDS_UNARY_ELEMENT_INTERFACE_HH
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements.  See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/// @file
/// IronBee - Unit testing utility functions implementation.
/// @brief IronBee --- String Util Test Functions
///
/// @author Nick LeRoy <nleroy@qualys.com>
//////////////////////////////////////////////////////////////////////////////
#ifndef __IBTEST_STRBASE_HH__
#define __IBTEST_STRBASE_HH__

#include "ironbee_config_auto.h"

#include <ironbee/flags.h>
#include <ironbee/mm_mpool.h>
#include <ironbee/types.h>
#include <ironbee/string.h>
#include <ironbee/util.h>
#include "ibtest_textbuf.hpp"

#include "gtest/gtest.h"

#include <stdexcept>
#include <assert.h>
#include <stdio.h>

// Single test data point
class BaseTestDatum
{
public:
    BaseTestDatum()
        : m_end(true),
          m_lineno(0),
          m_inbuf(1, "")
    { };

    BaseTestDatum(size_t lno, size_t bufsize, const char *in)
        : m_end(false),
          m_lineno(lno),
          m_inbuf(bufsize, in)
    { };

    BaseTestDatum(size_t lno, size_t bufsize, const char *in, size_t len)
        : m_end(false),
          m_lineno(lno),
          m_inbuf(bufsize, in, len)
    {
    };

    // Accessors
    size_t LineNo() const { return m_lineno; };
    bool IsEnd() const { return m_end; };
    const TextBuf &InBuf() const { return m_inbuf; };

private:
    bool               m_end;         // Special case: End marker.
    size_t             m_lineno;      // Test's line number
    TextBuf            m_inbuf;       // Input text buffer
};

// Formatted call text buffer
class CallTextBuf : public TextBuf
{
public:
    CallTextBuf(size_t bufsize, const char *fn) :
        TextBuf(bufsize, fn)
    {
    };

    const char *Stringize(const char *op, const BaseTestDatum &datum)
    {
        snprintf(m_fmtbuf, m_size,
                 "%s(%s, \"%s\", ...)", m_buf, op, datum.InBuf().GetFmt());
        return m_fmtbuf;
    };
};

// Class to test simple string manipulations.  This class is designed to work
// with string manipulation function families that have the following
// implementation functions:
// - in-place manipulation of NUL-terminated strings
// - in-place manipulation of byte strings (_ex version)
// - copy-on-write manipulation of NUL-terminated strings
// - copy-on-write manipulation of byte strings (_ex version)
class TestSimpleStringManipulation : public ::testing::Test
{
public:
    TestSimpleStringManipulation()
        : m_mpool(NULL)
    {
    };

    virtual void SetUp()
    {
        ib_status_t rc = ib_mpool_create(&m_mpool, NULL, NULL);
        if (rc != IB_OK) {
            throw std::runtime_error("Could not create memory pool");
        }
    }

    virtual void TearDown()
    {
        if (m_mpool != NULL) {
            ib_mpool_destroy(m_mpool);
        }
        m_mpool = NULL;
    }

    typedef enum { TYPE_NUL, TYPE_EX, TYPE_EX_TO_STR } test_type_t;

    virtual const char *TestName(
        ib_strop_t strop,
        test_type_t ex) = 0;

    virtual ib_status_t ExecInplaceNul(
        char *buf,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecInplaceEx(
        uint8_t *data_in,
        size_t dlen_in,
        size_t &dlen_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecCowNul(
        const char *data_in,
        char **data_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecCowEx(
        const uint8_t *data_in,
        size_t dlen_in,
        uint8_t **data_out,
        size_t &dlen_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecCopyNul(
        const char *data_in,
        char **data_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecCopyEx(
        const uint8_t *data_in,
        size_t dlen_in,
        uint8_t **data_out,
        size_t &dlen_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecCopyExToNul(
        const uint8_t *data_in,
        size_t dlen_in,
        char **data_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecNulToNulBuf(
        const char *data_in,
        char *data_out,
        size_t dsize_out,
        size_t &dlen_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    virtual ib_status_t ExecExToNulBuf(
        const uint8_t *data_in,
        size_t dlen_in,
        char *data_out,
        size_t dsize_out,
        size_t &dlen_out,
        ib_flags_t &result)
    {
        return IB_ENOTIMPL;
    }

    void RunTest(const uint8_t *in, size_t inlen,
                 const uint8_t *out = NULL, size_t outlen = 0)
    {
        TextBuf input(in, inlen);
        if (out == NULL) {
            out = in;
            outlen = inlen;
        }
        TextBuf expected(out, outlen);
        RunTestInplaceEx(input, expected);
        RunTestCowEx(input, expected);
    }

    void RunTest(const uint8_t *in, size_t inlen, const char *out)
    {
        TextBuf input(in, inlen);
        TextBuf expected(out);
        RunTestCopyEx(input, expected);
        RunTestCopyExToNul(input, expected);
        RunTestBuf(in, inlen, out, strlen(out)+1, IB_OK);
    }

    void RunTestBuf(const char *in,
                    const char *out,
                    size_t bufsize,
                    ib_status_t rc = IB_OK)
    {
        TextBuf input(in);
        if (out == NULL) {
            out = in;
        }
        TextBuf expected(out);
        if ( (rc == IB_OK) && (bufsize <= expected.GetLen()) ) {
            rc = IB_ETRUNC;
        }
        RunTestNulToNulBuf(input, expected, bufsize, rc);
        RunTestExToNulBuf(input, expected, bufsize, rc);
    }

    void RunTestBuf(const uint8_t *in,
                    size_t inlen,
                    const char *out,
                    size_t bufsize,
                    ib_status_t rc = IB_OK)
    {
        TextBuf input(in, inlen);
        if (out == NULL) {
            out = (const char *)in;
        }
        TextBuf expected(out);
        if ( (rc == IB_OK) && (bufsize <= expected.GetLen()) ) {
            rc = IB_ETRUNC;
        }
        RunTestExToNulBuf(input, expected, bufsize, rc);
    }

protected:
    const char *TestOpName(ib_strop_t op)
    {
        static const char *ops[] = { "", "_copy", "_cow", "_buf" };
        return ops[op];
    }
    const char *TestTypeName(test_type_t tt)
    {
        static const char *types[] = { "nul", "ex", "ex_to_str" };
        return types[tt];
    }
    const char *TestNameImpl(const char *test, ib_strop_t op, test_type_t tt)
    {
        static char buf[128];
        snprintf(buf, sizeof(buf),
                 "%s%s_%s()", test, TestOpName(op), TestTypeName(tt) );
        return buf;
    }

    void CheckResult(const char *name,
                     const TextBuf &input,
                     const TextBuf &expected,
                     ib_flags_t expected_unmodified_result,
                     ib_flags_t expected_modified_result,
                     ib_status_t rc,
                     ib_flags_t result,
                     const TextBuf &output)
    {
        const char *modstr;
        ib_flags_t eresult;

        if ( (rc == IB_ETRUNC) || (input != expected) ) {
            eresult = expected_modified_result;
            modstr = "should be modified";
        }
        else {
            eresult = expected_unmodified_result;
            modstr = "should not be modified";
        }
        ASSERT_EQ(eresult, result)
            << name << " " << modstr << " " << std::endl
            << " Expected: "
            << " [" << expected.GetLen() << "]"
            << " \"" << expected.GetFmt() << "\"" << std::endl
            << " Actual:   "
            << " [" << output.GetLen() << "]"
            << " \"" << output.GetFmt() << "\"";

        if (rc != IB_ETRUNC) {
            ASSERT_TRUE(expected == output)
                << name << std::endl
                << " Expected: "
                << " [" << expected.GetLen() << "]"
                << " \"" << expected.GetFmt() << "\"" << std::endl
                << " Actual:   "
                << " [" << output.GetLen() << "]"
                << " \"" << output.GetFmt() << "\"";
        }
    }

    void RunTestInplaceNul(const TextBuf &input, const TextBuf &expected)
    {
        size_t len = input.GetLen();
        char buf[len ? len : 1];
        ib_status_t rc;
        ib_flags_t result;

        strcpy(buf, input.GetStr());

        rc = ExecInplaceNul(buf, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_INPLACE, TYPE_NUL);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(buf);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_ALIAS,
                    (IB_STRFLAG_ALIAS | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestInplaceEx(const TextBuf &input, const TextBuf &expected)
    {
        size_t len = input.GetLen();
        uint8_t buf[len ? len : 1];
        ib_status_t rc;
        size_t outlen;
        ib_flags_t result;

        memcpy(buf, input.GetBuf(), len);

        rc = ExecInplaceEx(buf, len, outlen, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_INPLACE, TYPE_EX);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(buf, outlen);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_ALIAS,
                    (IB_STRFLAG_ALIAS | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestCowNul(const TextBuf &input, const TextBuf &expected)
    {
        char *out;
        ib_status_t rc;
        ib_flags_t result;

        rc = ExecCowNul(input.GetStr(), &out, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_COW, TYPE_NUL);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(out);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_ALIAS,
                    (IB_STRFLAG_NEWBUF | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestCowEx(const TextBuf &input, const TextBuf &expected)
    {
        size_t len = input.GetLen();
        uint8_t *out;
        ib_status_t rc;
        size_t outlen;
        ib_flags_t result;

        rc = ExecCowEx(input.GetUBuf(), len, &out, outlen, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_COW, TYPE_EX);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(out, outlen);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_ALIAS,
                    (IB_STRFLAG_NEWBUF | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestCopyNul(const TextBuf &input, const TextBuf &expected)
    {
        char *out;
        ib_status_t rc;
        ib_flags_t result;

        rc = ExecCopyNul(input.GetStr(), &out, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_COPY, TYPE_NUL);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(out);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_NEWBUF,
                    (IB_STRFLAG_NEWBUF | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestCopyEx(const TextBuf &input, const TextBuf &expected)
    {
        size_t len = input.GetLen();
        uint8_t *out;
        ib_status_t rc;
        size_t outlen;
        ib_flags_t result;

        rc = ExecCopyEx(input.GetUBuf(), len, &out, outlen, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_COPY, TYPE_EX);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(out, outlen);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_NEWBUF,
                    (IB_STRFLAG_NEWBUF | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestCopyExToNul(const TextBuf &input, const TextBuf &expected)
    {
        ib_status_t rc;
        size_t len = input.GetLen();
        char *out;
        ib_flags_t result;

        rc = ExecCopyExToNul(input.GetUBuf(), len, &out, result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_COPY, TYPE_NUL);
        ASSERT_EQ(IB_OK, rc) << name;

        TextBuf output(out);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_NEWBUF,
                    (IB_STRFLAG_NEWBUF | IB_STRFLAG_MODIFIED),
                    rc, result, output);
    }

    void RunTestNulToNulBuf(const TextBuf &input,
                            const TextBuf &expected,
                            size_t bufsize,
                            ib_status_t expected_rc)
    {
        char buf[bufsize];
        size_t len;
        ib_status_t rc;
        ib_flags_t result;

        rc = ExecNulToNulBuf(input.GetBuf(),
                             buf, bufsize, len,
                             result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_BUF, TYPE_NUL);
        ASSERT_EQ(expected_rc, rc) << name;

        TextBuf output(buf);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_NONE,
                    IB_STRFLAG_MODIFIED,
                    rc, result, output);
    }

    void RunTestExToNulBuf(const TextBuf &input,
                           const TextBuf &expected,
                           size_t bufsize,
                           ib_status_t expected_rc)
    {
        char buf[bufsize];
        size_t len;
        ib_status_t rc;
        ib_flags_t result;

        rc = ExecExToNulBuf(input.GetUBuf(), input.GetLen(),
                            buf, bufsize, len,
                            result);
        if (rc == IB_ENOTIMPL) {
            return;
        }
        const char *name = TestName(IB_STROP_BUF, TYPE_EX_TO_STR);
        ASSERT_EQ(expected_rc, rc) << name;

        TextBuf output(buf);
        CheckResult(name, input,
                    expected,
                    IB_STRFLAG_NONE,
                    IB_STRFLAG_MODIFIED,
                    rc, result, output);
    }

public:
    ib_mpool_t *m_mpool;
};

// Base class for string modification tests.  This class is specifically for
// testing string modification tests that use the ib_strmod_fn_t and
// ib_strmod_ex_fn_t interfaces.
class TestStringModification : public ::testing::Test
{
public:
    TestStringModification(size_t call_buf_size, size_t buf_size,
                           ib_strmod_fn_t fn, const char *fn_name,
                           ib_strmod_ex_fn_t ex_fn, const char *ex_fn_name)
        : m_strmod_fn(fn),
          m_callbuf(call_buf_size, fn_name),
          m_strmod_ex_fn(ex_fn),
          m_ex_callbuf(call_buf_size, ex_fn_name),
          m_op(IB_STROP_INPLACE),
          m_inbuf(buf_size),
          m_outbuf(buf_size)
    {
        ib_status_t rc = ib_mpool_create(&m_mpool, NULL, NULL);
        if (rc != IB_OK) {
            throw std::runtime_error("Could not create mpool.");
        }
    }

    virtual ~TestStringModification() {
        if (m_mpool != NULL) {
            ib_mpool_destroy(m_mpool);
        }
    }

    void SetOp(ib_strop_t op) { m_op = op; };
    ib_strop_t Op() const { return m_op; };
    const char *OpStr() const { return OpStr(m_op); };
    const char *OpStr( ib_strop_t op ) const
    {
        switch (op) {
        case IB_STROP_INPLACE:
            return "INPLACE";
        case IB_STROP_COW:
            return "COW";
        case IB_STROP_COPY:
            return "COPY";
        case IB_STROP_BUF:
            return "BUF";
        }
        assert(0);
    }

    virtual const char *FnName() const = 0;
    ib_mpool_t *MemPool() { return m_mpool; };
    ib_mm_t MM() { return ib_mm_mpool(MemPool()); };

    const char *BoolStr(bool v) const
    {
        return (v ? "true" : "false");
    }

    virtual bool ExpectCowAlias(bool mod) const
    {
        return (! mod);
    }

    ib_flags_t ExpectedResult(ib_strop_t op, bool mod) const
    {
        ib_flags_t result = 0;

        switch (op) {
        case IB_STROP_INPLACE:
            result = IB_STRFLAG_ALIAS;
            break;

        case IB_STROP_COPY:
            result = IB_STRFLAG_NEWBUF;
            break;

        case IB_STROP_COW:
            result = ExpectCowAlias(mod) ? IB_STRFLAG_ALIAS : IB_STRFLAG_NEWBUF;
            break;

        case IB_STROP_BUF:
            result = IB_STRFLAG_NONE;
            break;
        }
        if (mod) {
            result |= IB_STRFLAG_MODIFIED;
        }
        return result;
    }

    bool AllSpace( const TextBuf *buf=NULL ) const
    {
        if (buf == NULL) {
            buf = &m_inbuf;
        }
        const char *p = buf->GetBuf();
        const char *end = p + buf->GetLen();
        while(p < end) {
            if (isspace(*p) == 0) {
                return false;
            }
            ++p;
        }
        return true;
    }

    bool LeftSpace( const TextBuf *buf=NULL ) const
    {
        if (buf == NULL) {
            buf = &m_inbuf;
        }
        const char *p = buf->GetBuf();
        if ( (buf->GetLen() > 0) && (isspace(*p) != 0) ) {
            return true;
        }
        else {
            return false;
        }
    }

    bool RightSpace( const TextBuf *buf=NULL ) const
    {
        if (buf == NULL) {
            buf = &m_inbuf;
        }
        const char *p = buf->GetBuf() + buf->GetLen() - 1;
        if ( (buf->GetLen() > 0) && (isspace(*p) != 0) ) {
            return true;
        }
        else {
            return false;
        }
    }

    const std::string &ResultStr(ib_flags_t result) const
    {
        std::string s;
        return ResultStr(result, s);
    }
    const std::string &ResultStr(ib_flags_t result, std::string &s) const
    {
        int n = 0;
        if (result == IB_STRFLAG_NONE) {
            s = "<None>";
            return s;
        }
        s = "<";
        if (ib_flags_all(result, IB_STRFLAG_MODIFIED)) {
            if (n++ > 0) {
                s += ",";
            }
            s += "MODIFIED";
        }
        if (ib_flags_all(result, IB_STRFLAG_NEWBUF)) {
            if (n++ > 0) {
                s += ",";
            }
            s += "NEWBUF";
        }
        if (ib_flags_all(result, IB_STRFLAG_ALIAS)) {
            if (n++ > 0) {
                s += ",";
            }
            s += "ALIAS";
        }
        s += ">";
        return s;
    }

    ib_status_t RunTest(const BaseTestDatum &test, ib_flags_t &result)
    {
        if (m_strmod_fn != NULL) {
            return RunTestStr(test, result);
        }
        else if (m_strmod_ex_fn != NULL) {
            return RunTestEx(test, result);
        }
        else {
            assert (0);
        }
    }

    ib_status_t RunTestStr(const BaseTestDatum &test, ib_flags_t &result)
    {
        char *out = NULL;
        char *in;
        ib_status_t rc;

        m_inbuf.Set(test.InBuf());
        in = const_cast<char *>(m_inbuf.GetBuf());
        assert(in != NULL);
        assert(m_strmod_fn != NULL);
        rc = m_strmod_fn(m_op, MM(), in, &out, &result);
        if (rc == IB_OK) {
            m_outbuf.SetStr(out);
        }
        return rc;
    }

    virtual ib_status_t RunTestEx(const BaseTestDatum &test, ib_flags_t &result)
    {
        uint8_t *out;
        size_t outlen;
        ib_status_t rc;

        m_inbuf.Set(test.InBuf());

        rc = m_strmod_ex_fn(m_op, MM(),
                            const_cast<uint8_t *>(m_inbuf.GetText()),
                            m_inbuf.GetLen(),
                            &out, &outlen,
                            &result);
        if (rc == IB_OK) {
            m_outbuf.SetText((char *)out, outlen);
        }
        return rc;
    }

    void CheckResult(int lineno,
                     const BaseTestDatum &test,
                     ib_status_t rc,
                     ib_flags_t exresult,
                     ib_flags_t result)
    {
        std::string s1, s2;
        EXPECT_EQ(IB_OK, rc)
            << "Line " << lineno << ": "
            << Stringize(test) << " returned " << rc;
        if (rc != IB_OK) {
            return;
        }

        // NEWBUF and ALIAS result flags should never both be set
        bool both =
            ib_flags_all(result, IB_STRFLAG_NEWBUF|IB_STRFLAG_ALIAS);
        ASSERT_FALSE(both)
            << "Line " << lineno << ": " << Stringize(test)
            << " both NEWBUF and ALIAS result flags are set!"
            << ResultStr(result, s1);

        // Build the expected output
        EXPECT_EQ(exresult, result)
            << "Line " << lineno << ": " << Stringize(test)
            << " expected result=" << ResultStr(exresult, s1) << exresult
            << " actual=" << ResultStr(result, s2) << result;
    }

    const char *Stringize(const BaseTestDatum &test)
    {
        return m_callbuf.Stringize(OpStr(m_op), test);
    }

protected:
    ib_strmod_fn_t    m_strmod_fn;     // String mod function
    CallTextBuf       m_callbuf;       // Call string buffer
    ib_strmod_ex_fn_t m_strmod_ex_fn;  // ex version of string mod function
    CallTextBuf       m_ex_callbuf;       // Call string buffer
    ib_strop_t        m_op;            // String operation
    ib_mpool_t       *m_mpool;         // Memory pool to use
    TextBuf           m_inbuf;         // Copy of input
    TextBuf           m_outbuf;        // Output buffer
};

#endif
<commit_msg>tests/ibtest_strbase.hpp: Remove.<commit_after><|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_studio_console_controller.cpp
  \author      (lord.tiran@gmail.com)
  \date      26.10.2011
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_console/rdo_studio_console_controller.h"
// --------------------------------------------------------------------------------

void test_fun()
{
	int i = 0;
	UNUSED(i);
}

RDOStudioConsoleController::RDOStudioConsoleController()
	: RDOThread(_T("RDOThreadRDOStudioConsoleController"))
	, m_state  (SS_UNDEFINED)
{
	notifies.push_back(RT_REPOSITORY_MODEL_OPEN_ERROR       );
	notifies.push_back(RT_RUNTIME_MODEL_START_BEFORE        );
	notifies.push_back(RT_RUNTIME_MODEL_STOP_AFTER          );
	notifies.push_back(RT_SIMULATOR_PARSE_OK                );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR             );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR         );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY   );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_OK           );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR);

	after_constructor();
}

RDOStudioConsoleController::~RDOStudioConsoleController()
{
}

rbool RDOStudioConsoleController::finished() const
{
	rbool res = true;
	m_stateMutex.lock();
	res = m_state == SS_FINISHED;
	m_stateMutex.unlock();
	return res;
}

rbool RDOStudioConsoleController::errorOccurred() const
{
	/// @todo added errors controle
	return false;
}

rbool RDOStudioConsoleController::simulationSuccessfully() const
{
	bool res = false;
	m_stateMutex.lock();
	//! @todo      (RT_SIMULATOR_GET_MODEL_EXITCODE)
	res = true;
	m_stateMutex.unlock();
	return res;
}

void RDOStudioConsoleController::proc(REF(RDOThread::RDOMessageInfo) msg)
{
	switch (msg.message)
	{
	case RDOThread::RT_REPOSITORY_MODEL_OPEN_ERROR:
		test_fun();
		break;

	case RDOThread::RT_RUNTIME_MODEL_START_BEFORE:
		m_stateMutex.lock();
		m_state = SS_IN_PROGRESS;
		m_stateMutex.unlock();
		test_fun();
		break;

	case RDOThread::RT_RUNTIME_MODEL_STOP_AFTER:
		m_stateMutex.lock();
		m_state = SS_FINISHED;
		m_stateMutex.unlock();
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_OK:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_OK:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR:
		test_fun();
		break;
	}
}
<commit_msg> - использован lock_guard<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_studio_console_controller.cpp
  \author      (lord.tiran@gmail.com)
  \date      26.10.2011
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <boost/thread/locks.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_console/rdo_studio_console_controller.h"
// --------------------------------------------------------------------------------

#define MUTEXT_PROTECTION(A) boost::lock_guard<boost::mutex> lg_##__LINE__(A);

void test_fun()
{
	int i = 0;
	UNUSED(i);
}

RDOStudioConsoleController::RDOStudioConsoleController()
	: RDOThread(_T("RDOThreadRDOStudioConsoleController"))
	, m_state  (SS_UNDEFINED)
{
	notifies.push_back(RT_REPOSITORY_MODEL_OPEN_ERROR       );
	notifies.push_back(RT_RUNTIME_MODEL_START_BEFORE        );
	notifies.push_back(RT_RUNTIME_MODEL_STOP_AFTER          );
	notifies.push_back(RT_SIMULATOR_PARSE_OK                );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR             );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR         );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY   );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_OK           );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR);

	after_constructor();
}

RDOStudioConsoleController::~RDOStudioConsoleController()
{
}

rbool RDOStudioConsoleController::finished() const
{
	rbool res = true;
	{
		MUTEXT_PROTECTION(m_stateMutex);
		res = m_state == SS_FINISHED;
	}
	return res;
}

rbool RDOStudioConsoleController::errorOccurred() const
{
	/// @todo added errors controle
	return false;
}

rbool RDOStudioConsoleController::simulationSuccessfully() const
{
	bool res = false;
	{
		MUTEXT_PROTECTION(m_stateMutex);
		//! @todo      (RT_SIMULATOR_GET_MODEL_EXITCODE)
		res = true;
	}
	return res;
}

void RDOStudioConsoleController::proc(REF(RDOThread::RDOMessageInfo) msg)
{
	switch (msg.message)
	{
	case RDOThread::RT_REPOSITORY_MODEL_OPEN_ERROR:
		test_fun();
		break;

	case RDOThread::RT_RUNTIME_MODEL_START_BEFORE:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_IN_PROGRESS;
		}
		test_fun();
		break;

	case RDOThread::RT_RUNTIME_MODEL_STOP_AFTER:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_FINISHED;
		}
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_OK:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_OK:
		test_fun();
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR:
		test_fun();
		break;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "StackingContext.h"

// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>

#include <new>
#include <iostream>

#include "Box.h"
#include "ViewCSSImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

StackingContext* StackingContext::removeChild(StackingContext* item)
{
    StackingContext* next = item->nextSibling;
    StackingContext* prev = item->previousSibling;
    if (!next)
        lastChild = prev;
    else
        next->previousSibling = prev;
    if (!prev)
        firstChild = next;
    else
        prev->nextSibling = next;
    item->parent = item->nextSibling = item->previousSibling = 0;
    --childCount;
    return item;
}

StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
    if (!after)
        return appendChild(item);
    item->previousSibling = after->previousSibling;
    item->nextSibling = after;
    after->previousSibling = item;
    if (!item->previousSibling)
        firstChild = item;
    else
        item->previousSibling->nextSibling = item;
    item->parent = this;
    ++childCount;
    return item;
}

StackingContext* StackingContext::appendChild(StackingContext* item)
{
    StackingContext* prev = lastChild;
    if (!prev)
        firstChild = item;
    else
        prev->nextSibling = item;
    item->previousSibling = prev;
    item->nextSibling = 0;
    lastChild = item;
    item->parent = this;
    ++childCount;
    return item;
}

StackingContext::StackingContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
    count(0),
    style(style),
    needStaticPosition(false),
    auto_(auto_),
    zIndex(zIndex),
    parent(0),
    firstChild(0),
    lastChild(0),
    previousSibling(0),
    nextSibling(0),
    childCount(0),
    positioned(0),
    firstBase(0),
    lastBase(0),
    clipBox(0),
    firstFloat(0),
    lastFloat(0),
    currentFloat(0)
{
}

StackingContext::~StackingContext()
{
    if (parent)
        parent->removeChild(this);
    while (0 < childCount) {
        StackingContext* child = removeChild(firstChild);
        delete child;
    }
}

StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
    StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
    if (item)
        insertContext(item);
    return item;
}

void StackingContext::insertContext(StackingContext* item)
{
    assert(item);
    if (isAuto()) {
        parent->insertContext(item);
        item->positioned = this;
        return;
    }
    // TODO: Preserve the order in the DOM tree
    StackingContext* after = 0;
    for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
        if (item->zIndex < i->zIndex) {
            after = i;
            break;
        }
    }
    insertBefore(item, after);
    item->positioned = this;
}

void StackingContext::reparent(StackingContext* target)
{
    auto child = parent->getFirstChild();
    while (child) {
        auto next = child->getNextSibling();
        if (child->positioned == target) {
            parent->removeChild(child);
            target->insertContext(child);
            if (child->isAuto())
                reparent(child);
        }
        child = next;
    }
}

void StackingContext::setZIndex(bool auto_, int index)
{
    if (isAuto() == auto_ && zIndex == index)
        return;
    bool updateChildren = (this->auto_ != auto_);
    this->auto_ = auto_;
    zIndex = index;
    if (parent) {
        parent->removeChild(this);
        positioned->insertContext(this);
        if (updateChildren) {
            if (isAuto()) {
                while (StackingContext* child = getFirstChild()) {
                    removeChild(child);
                    child->positioned->insertContext(child);
                }
            } else
                reparent(this);
        }
    }
}

void StackingContext::clip(StackingContext* s)
{
    float scrollLeft = 0.0f;
    float scrollTop = 0.0f;
    for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
        if (clip->stackingContext == s)
            continue;
        Element element = interface_cast<Element>(clip->node);
        scrollLeft += element.getScrollLeft();
        scrollTop += element.getScrollTop();
        if (clipWidth == HUGE_VALF) {
            clipLeft = scrollLeft + clip->x + clip->marginLeft + clip->borderLeft;
            clipTop = scrollTop + clip->y + clip->marginTop + clip->borderTop;
            clipWidth = clip->getPaddingWidth();
            clipHeight = clip->getPaddingHeight();
        } else {
            Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
                           scrollLeft + clip->x + clip->marginLeft + clip->borderLeft,
                           scrollTop + clip->y + clip->marginTop + clip->borderTop,
                           clip->getPaddingWidth(), clip->getPaddingHeight());
        }
    }
    glTranslatef(-scrollLeft, -scrollTop, 0.0f);
}

bool StackingContext::resolveRelativeOffset(ViewCSSImp* view, float& x, float &y)
{
    bool result = false;
    for (StackingContext* s = this; s != parent; s = s->positioned) {
        assert(s->style);
        CSSStyleDeclarationImp* style = s->style;
        if (!style->isResolved()) {
            if (Box* b = style->getBox()) {
                if (auto c = b->getContainingBlock(view)) {
                    style->left.resolve(view, style, c->width);
                    style->right.resolve(view, style, c->width);
                    style->top.resolve(view, style, c->height);
                    style->bottom.resolve(view, style, c->height);
                }
            }
        }
        result |= style->resolveRelativeOffset(x, y);
        clip(s);
        clipLeft -= x;
        clipTop -= y;
    }
    return result;
}

void StackingContext::renderFloats(ViewCSSImp* view, Box* last, Box* current)
{
    if (current && current == currentFloat)
        return;
    if (!last)
        currentFloat = firstFloat;
    else if (last->nextFloat)
        currentFloat = last->nextFloat;
    else
        return;
    while (currentFloat) {
        currentFloat->render(view, this);;
        currentFloat = currentFloat->nextFloat;
    }
    if (!last)
        firstFloat = lastFloat = 0;
    else {
        last->nextFloat = 0;
        lastFloat = last;
    }
    currentFloat = 0;
}

void StackingContext::render(ViewCSSImp* view)
{
    clipLeft = clipTop = 0.0f;
    clipWidth = clipHeight = HUGE_VALF;
    glPushMatrix();
    float relativeX = 0.0f;
    float relativeY = 0.0f;
    if (resolveRelativeOffset(view, relativeX, relativeY))
        glTranslatef(relativeX, relativeY, 0.0f);
    if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
        view->clip(clipLeft, clipTop, clipWidth, clipHeight);

    if (firstBase) {
        currentFloat = firstFloat = lastFloat = 0;
        for (Box* base = firstBase; base; base = base->nextBase) {
            glPushMatrix();
            Block* block = dynamic_cast<Block*>(base);
            unsigned overflow = CSSOverflowValueImp::Visible;
            if (block) {
                overflow = block->renderBegin(view);
            }

            GLfloat mtx[16];
            glGetFloatv(GL_MODELVIEW_MATRIX, mtx);
            glPopMatrix();
            glPushMatrix();
            StackingContext* childContext = getFirstChild();
            for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) {
                childContext->render(view);
            }
            glLoadMatrixf(mtx);

            if (block) {
                block->renderNonInline(view, this);
                renderFloats(view, 0, 0);
                block->renderInline(view, this);
            } else
                base->render(view, this);

            glPopMatrix();
            glPushMatrix();
            for (; childContext; childContext = childContext->getNextSibling()) {
                    childContext->render(view);
            }
            glLoadMatrixf(mtx);

            if (block) {
                if (0.0f < block->getOutlineWidth())
                    block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
                block->renderEnd(view, overflow);
            }
            glPopMatrix();
        }
    } else {
        glPushMatrix();
        for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
            childContext->render(view);
        glPopMatrix();
    }

    if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
        view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
    glPopMatrix();
}

void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
    for (Box* i = firstBase; i; i = i->nextBase)
        assert(box != i);
#endif
    if (!firstBase)
        firstBase = lastBase = box;
    else {
        lastBase->nextBase = box;
        lastBase = box;
    }
    box->nextBase = 0;
}

void StackingContext::addBox(Box* box, Box* parentBox)
{
    assert(parentBox);
    if (parentBox->stackingContext != this)
        addBase(box);
}

void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
    for (Box* i = firstFloat; i; i = i->nextFloat) {
        assert(box != i);
    }
#endif
    if (currentFloat) {
        box->nextFloat = currentFloat->nextFloat;
        currentFloat->nextFloat = box;
        return;
    }
    if (!firstFloat)
        firstFloat = lastFloat = box;
    else {
        lastFloat->nextFloat = box;
        lastFloat = box;
    }
    box->nextFloat = 0;
}

void StackingContext::removeBox(Box* box)
{
    Box* p = 0;
    for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
        if (i == box) {
            if (!p)
                firstBase = i->nextBase;
            else
                p->nextBase = i->nextBase;
            if (lastBase == box)
                lastBase = p;
            break;
        }
    }
}

void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
    for (Box* base = firstBase; base; base = base->nextBase) {
        Block* block = dynamic_cast<Block*>(base);
        if (!block || !block->isAbsolutelyPositioned())
            continue;
        block->layOutAbsolute(view);
        block->resolveXY(view, block->x, block->y, block->clipBox);
    }
    needStaticPosition = false;

    for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
        childContext->needStaticPosition = true;
    bool repeat;
    do {
        repeat = false;
        for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling()) {
            if (childContext->needStaticPosition) {
                if (!childContext->positioned->needStaticPosition)
                    childContext->layOutAbsolute(view);
                else
                    repeat = true;
            }
        }
    } while (repeat);
}

void StackingContext::dump(std::string indent)
{
    std::cout << indent << "z-index: ";
    if (isAuto())
        std::cout << "auto";
    else
        std::cout << zIndex;
    std::cout << '\n';
    indent += "  ";
    for (auto child = getFirstChild(); child; child = child->getNextSibling())
        child->dump(indent);
}

}}}}  // org::w3c::dom::bootstrap
<commit_msg>(StackingContext::render) : Fix a bug<commit_after>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "StackingContext.h"

// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>

#include <new>
#include <iostream>

#include "Box.h"
#include "ViewCSSImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

StackingContext* StackingContext::removeChild(StackingContext* item)
{
    StackingContext* next = item->nextSibling;
    StackingContext* prev = item->previousSibling;
    if (!next)
        lastChild = prev;
    else
        next->previousSibling = prev;
    if (!prev)
        firstChild = next;
    else
        prev->nextSibling = next;
    item->parent = item->nextSibling = item->previousSibling = 0;
    --childCount;
    return item;
}

StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
    if (!after)
        return appendChild(item);
    item->previousSibling = after->previousSibling;
    item->nextSibling = after;
    after->previousSibling = item;
    if (!item->previousSibling)
        firstChild = item;
    else
        item->previousSibling->nextSibling = item;
    item->parent = this;
    ++childCount;
    return item;
}

StackingContext* StackingContext::appendChild(StackingContext* item)
{
    StackingContext* prev = lastChild;
    if (!prev)
        firstChild = item;
    else
        prev->nextSibling = item;
    item->previousSibling = prev;
    item->nextSibling = 0;
    lastChild = item;
    item->parent = this;
    ++childCount;
    return item;
}

StackingContext::StackingContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
    count(0),
    style(style),
    needStaticPosition(false),
    auto_(auto_),
    zIndex(zIndex),
    parent(0),
    firstChild(0),
    lastChild(0),
    previousSibling(0),
    nextSibling(0),
    childCount(0),
    positioned(0),
    firstBase(0),
    lastBase(0),
    clipBox(0),
    firstFloat(0),
    lastFloat(0),
    currentFloat(0)
{
}

StackingContext::~StackingContext()
{
    if (parent)
        parent->removeChild(this);
    while (0 < childCount) {
        StackingContext* child = removeChild(firstChild);
        delete child;
    }
}

StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
    StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
    if (item)
        insertContext(item);
    return item;
}

void StackingContext::insertContext(StackingContext* item)
{
    assert(item);
    if (isAuto()) {
        parent->insertContext(item);
        item->positioned = this;
        return;
    }
    // TODO: Preserve the order in the DOM tree
    StackingContext* after = 0;
    for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
        if (item->zIndex < i->zIndex) {
            after = i;
            break;
        }
    }
    insertBefore(item, after);
    item->positioned = this;
}

void StackingContext::reparent(StackingContext* target)
{
    auto child = parent->getFirstChild();
    while (child) {
        auto next = child->getNextSibling();
        if (child->positioned == target) {
            parent->removeChild(child);
            target->insertContext(child);
            if (child->isAuto())
                reparent(child);
        }
        child = next;
    }
}

void StackingContext::setZIndex(bool auto_, int index)
{
    if (isAuto() == auto_ && zIndex == index)
        return;
    bool updateChildren = (this->auto_ != auto_);
    this->auto_ = auto_;
    zIndex = index;
    if (parent) {
        parent->removeChild(this);
        positioned->insertContext(this);
        if (updateChildren) {
            if (isAuto()) {
                while (StackingContext* child = getFirstChild()) {
                    removeChild(child);
                    child->positioned->insertContext(child);
                }
            } else
                reparent(this);
        }
    }
}

void StackingContext::clip(StackingContext* s)
{
    float scrollLeft = 0.0f;
    float scrollTop = 0.0f;
    for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
        if (clip->stackingContext == s)
            continue;
        Element element = interface_cast<Element>(clip->node);
        scrollLeft += element.getScrollLeft();
        scrollTop += element.getScrollTop();
        if (clipWidth == HUGE_VALF) {
            clipLeft = scrollLeft + clip->x + clip->marginLeft + clip->borderLeft;
            clipTop = scrollTop + clip->y + clip->marginTop + clip->borderTop;
            clipWidth = clip->getPaddingWidth();
            clipHeight = clip->getPaddingHeight();
        } else {
            Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
                           scrollLeft + clip->x + clip->marginLeft + clip->borderLeft,
                           scrollTop + clip->y + clip->marginTop + clip->borderTop,
                           clip->getPaddingWidth(), clip->getPaddingHeight());
        }
    }
    glTranslatef(-scrollLeft, -scrollTop, 0.0f);
}

bool StackingContext::resolveRelativeOffset(ViewCSSImp* view, float& x, float &y)
{
    bool result = false;
    for (StackingContext* s = this; s != parent; s = s->positioned) {
        assert(s->style);
        CSSStyleDeclarationImp* style = s->style;
        if (!style->isResolved()) {
            if (Box* b = style->getBox()) {
                if (auto c = b->getContainingBlock(view)) {
                    style->left.resolve(view, style, c->width);
                    style->right.resolve(view, style, c->width);
                    style->top.resolve(view, style, c->height);
                    style->bottom.resolve(view, style, c->height);
                }
            }
        }
        result |= style->resolveRelativeOffset(x, y);
        clip(s);
        clipLeft -= x;
        clipTop -= y;
    }
    return result;
}

void StackingContext::renderFloats(ViewCSSImp* view, Box* last, Box* current)
{
    if (current && current == currentFloat)
        return;
    if (!last)
        currentFloat = firstFloat;
    else if (last->nextFloat)
        currentFloat = last->nextFloat;
    else
        return;
    while (currentFloat) {
        currentFloat->render(view, this);;
        currentFloat = currentFloat->nextFloat;
    }
    if (!last)
        firstFloat = lastFloat = 0;
    else {
        last->nextFloat = 0;
        lastFloat = last;
    }
    currentFloat = 0;
}

void StackingContext::render(ViewCSSImp* view)
{
    clipLeft = clipTop = 0.0f;
    clipWidth = clipHeight = HUGE_VALF;
    glPushMatrix();
    float relativeX = 0.0f;
    float relativeY = 0.0f;
    if (resolveRelativeOffset(view, relativeX, relativeY))
        glTranslatef(relativeX, relativeY, 0.0f);
    if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
        view->clip(clipLeft, clipTop, clipWidth, clipHeight);

    if (firstBase) {
        currentFloat = firstFloat = lastFloat = 0;
        GLfloat mtx[16];
        glGetFloatv(GL_MODELVIEW_MATRIX, mtx);
        for (Box* base = firstBase; base; base = base->nextBase) {
            glPushMatrix();
            Block* block = dynamic_cast<Block*>(base);
            unsigned overflow = CSSOverflowValueImp::Visible;
            if (block) {
                overflow = block->renderBegin(view);
            }

            glPushMatrix();
            glLoadMatrixf(mtx);
            StackingContext* childContext = getFirstChild();
            for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) {
                childContext->render(view);
            }
            glPopMatrix();

            if (block) {
                block->renderNonInline(view, this);
                renderFloats(view, 0, 0);
                block->renderInline(view, this);
            } else
                base->render(view, this);

            glPushMatrix();
            glLoadMatrixf(mtx);
            for (; childContext; childContext = childContext->getNextSibling()) {
                    childContext->render(view);
            }
            glPopMatrix();

            if (block) {
                if (0.0f < block->getOutlineWidth())
                    block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
                block->renderEnd(view, overflow);
            }
            glPopMatrix();
        }
    } else {
        glPushMatrix();
        for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
            childContext->render(view);
        glPopMatrix();
    }

    if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
        view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
    glPopMatrix();
}

void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
    for (Box* i = firstBase; i; i = i->nextBase)
        assert(box != i);
#endif
    if (!firstBase)
        firstBase = lastBase = box;
    else {
        lastBase->nextBase = box;
        lastBase = box;
    }
    box->nextBase = 0;
}

void StackingContext::addBox(Box* box, Box* parentBox)
{
    assert(parentBox);
    if (parentBox->stackingContext != this)
        addBase(box);
}

void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
    for (Box* i = firstFloat; i; i = i->nextFloat) {
        assert(box != i);
    }
#endif
    if (currentFloat) {
        box->nextFloat = currentFloat->nextFloat;
        currentFloat->nextFloat = box;
        return;
    }
    if (!firstFloat)
        firstFloat = lastFloat = box;
    else {
        lastFloat->nextFloat = box;
        lastFloat = box;
    }
    box->nextFloat = 0;
}

void StackingContext::removeBox(Box* box)
{
    Box* p = 0;
    for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
        if (i == box) {
            if (!p)
                firstBase = i->nextBase;
            else
                p->nextBase = i->nextBase;
            if (lastBase == box)
                lastBase = p;
            break;
        }
    }
}

void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
    for (Box* base = firstBase; base; base = base->nextBase) {
        Block* block = dynamic_cast<Block*>(base);
        if (!block || !block->isAbsolutelyPositioned())
            continue;
        block->layOutAbsolute(view);
        block->resolveXY(view, block->x, block->y, block->clipBox);
    }
    needStaticPosition = false;

    for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
        childContext->needStaticPosition = true;
    bool repeat;
    do {
        repeat = false;
        for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling()) {
            if (childContext->needStaticPosition) {
                if (!childContext->positioned->needStaticPosition)
                    childContext->layOutAbsolute(view);
                else
                    repeat = true;
            }
        }
    } while (repeat);
}

void StackingContext::dump(std::string indent)
{
    std::cout << indent << "z-index: ";
    if (isAuto())
        std::cout << "auto";
    else
        std::cout << zIndex;
    std::cout << '\n';
    indent += "  ";
    for (auto child = getFirstChild(); child; child = child->getNextSibling())
        child->dump(indent);
}

}}}}  // org::w3c::dom::bootstrap
<|endoftext|>