/****************************************************************************
* MeshLab                                                           o o     *
* An extendible mesh processor                                    o     o   *
*                                                                _   O  _   *
* Copyright(C) 2005, 2006                                          \/)\/    *
* Visual Computing Lab                                            /\/|      *
* ISTI - Italian National Research Council                           |      *
*                                                                    \      *
* All rights reserved.                                                      *
*                                                                           *
* This program is free software; you can redistribute it and/or modify      *
* it under the terms of the GNU General Public License as published by      *
* the Free Software Foundation; either version 2 of the License, or         *
* (at your option) any later version.                                       *
*                                                                           *
* This program is distributed in the hope that it will be useful,           *
* but WITHOUT ANY WARRANTY; without even the implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)          *
* for more details.                                                         *
*                                                                           *
****************************************************************************/
/****************************************************************************
History

$Log: stdpardialog.cpp,v $

****************************************************************************/

#include <GL/glew.h>
#include <QToolBar>
#include <QActionGroup>
#include <QDebug>
#include <QFontMetrics>
#include <QSettings>

#include "mainwindow.h"
#include "ui_layerDialog.h"
#include "layerDialog.h"
#include "../common/mlexception.h"

using namespace std;

LayerDialog::LayerDialog(QWidget *parent )
	: QDockWidget(parent)
{
	ui = new Ui::layerDialog();
	setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint | Qt::SubWindow );
	this-> QWidget::setAttribute( Qt::WA_MacAlwaysShowToolWindow);
	setVisible(false);
	ui->setupUi(this);
	mw=qobject_cast<MainWindow *>(parent);
	_previd = -1;
	/*Horrible trick*/
	_docitem = new QTreeWidgetItem();
	_docitem->setHidden(true);

	_renderingtabcontainer = new QGroupBox(this);
	QVBoxLayout* groupboxlay = new QVBoxLayout();
	if (createRenderingParametersTab() != NULL)
	{
		_tabw->setVisible(true);
		groupboxlay->addWidget(_tabw);
	}
	_applytovis = new QCheckBox(QString("apply to all visible layers"),this);
	QString tooltip("When the option is activated all the following rendering actions (e.g. activating/deactivating rendering primitives, changing rendering parameters etc.) taken on a single mesh are propagated to all the other visible meshes (e.g. the ones having the \"open eye\" icon on the layer dialog).

 SHORTCUT: SHIFT");
	_applytovis->setToolTip(tooltip);
	_applytovis->setLayoutDirection(Qt::RightToLeft);
	_applytovis->setChecked(false);
	groupboxlay->addWidget(_applytovis);
	_renderingtabcontainer->setLayout(groupboxlay);
	ui->renderingLayout->addWidget(_renderingtabcontainer);

	// The following connection is used to associate the click with the change of the current mesh.
	connect(ui->meshTreeWidget, SIGNAL(itemPressed(QTreeWidgetItem * , int  )) , this,  SLOT(meshItemClicked(QTreeWidgetItem * , int ) ) );

	connect(ui->meshTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem * )) , this,  SLOT(adaptLayout(QTreeWidgetItem *)));
	connect(ui->meshTreeWidget, SIGNAL(itemCollapsed(QTreeWidgetItem * )) , this,  SLOT(adaptLayout(QTreeWidgetItem *)));

	// The following connection is used to associate the click with the switch between raster and mesh view.
	connect(ui->rasterTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem * , int  )) , this,  SLOT(rasterItemClicked(QTreeWidgetItem * , int ) ) );

	// state buttons
	isRecording = false;
	viewState[0] = viewState[1] = viewState[2] = viewState[3] = "";
	connect(ui->bW1, SIGNAL(clicked()), this, SLOT(clickW1()));
	connect(ui->bW2, SIGNAL(clicked()), this, SLOT(clickW2()));
	connect(ui->bW3, SIGNAL(clicked()), this, SLOT(clickW3()));
	connect(ui->bW4, SIGNAL(clicked()), this, SLOT(clickW4()));
	connect(ui->bV1, SIGNAL(clicked()), this, SLOT(clickV1()));
	connect(ui->bV2, SIGNAL(clicked()), this, SLOT(clickV2()));
	connect(ui->bV3, SIGNAL(clicked()), this, SLOT(clickV3()));
	connect(ui->bV4, SIGNAL(clicked()), this, SLOT(clickV4()));

	this->setContextMenuPolicy(Qt::CustomContextMenu);
	ui->meshTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	ui->rasterTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	ui->decParsTree->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui->meshTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(showContextMenu(const QPoint&)));
	connect(ui->rasterTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(showContextMenu(const QPoint&)));
	connect(ui->decParsTree, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(showContextMenu(const QPoint&)));
	setMinimumSize(_tabw->size().width() + 10, minimumSize().height());
}

void LayerDialog::keyPressEvent ( QKeyEvent * event )
{
	MeshDocument *md = mw->meshDoc();
	if((md != NULL) && (event->key() == Qt::Key_Space ))
	{
		RasterModel *rm= md->nextRaster(md->rm());
		if(rm!=0) md->setCurrentRaster(rm->id());
	}

	if (event->key() == Qt::Key_Shift)
	{
		if (_applytovis != NULL)
			_applytovis->setCheckState(Qt::Checked);
	}

	if (event->key() == Qt::Key_Control)
	{
		isRecording = true;
	}
}

void LayerDialog::keyReleaseEvent(QKeyEvent * event)
{
	if (event->key() == Qt::Key_Shift)
	{
		if (_applytovis != NULL)
			_applytovis->setCheckState(Qt::Unchecked);
	}

	if (event->key() == Qt::Key_Control)
	{
		isRecording = false;
	}
}

void LayerDialog::clickW1()
{
	if (isRecording)
	{
		viewState[0] = mw->GLA()->viewToText();
		isRecording = false;
		ui->bW1->setText(QChar(0x2460));
		mw->meshDoc()->Log.Log(0, "Stored View #1");
	}
	else if (viewState[0] != "")
	{
		QDomDocument doc("StringDoc");
		doc.setContent(viewState[0]);
		mw->GLA()->loadViewFromViewStateFile(doc);
		mw->meshDoc()->Log.Log(0, "Restored View #1");
	}
	else
		mw->meshDoc()->Log.Log(0, "No View to Restore");
}

void LayerDialog::clickW2()
{
	if (isRecording)
	{
		viewState[1] = mw->GLA()->viewToText();
		isRecording = false;
		ui->bW2->setText(QChar(0x2461));
		mw->meshDoc()->Log.Log(0, "Stored View #2");
	}
	else if (viewState[1] != "")
	{
		QDomDocument doc("StringDoc");
		doc.setContent(viewState[1]);
		mw->GLA()->loadViewFromViewStateFile(doc);
		mw->meshDoc()->Log.Log(0, "Restored View #2");
	}
	else
		mw->meshDoc()->Log.Log(0, "No View to Restore");
}

void LayerDialog::clickW3()
{
	if (isRecording)
	{
		viewState[2] = mw->GLA()->viewToText();
		isRecording = false;
		ui->bW3->setText(QChar(0x2462));
		mw->meshDoc()->Log.Log(0, "Stored View #3");
	}
	else if (viewState[2] != "")
	{
		QDomDocument doc("StringDoc");
		doc.setContent(viewState[2]);
		mw->GLA()->loadViewFromViewStateFile(doc);
		mw->meshDoc()->Log.Log(0, "Restored View #3");
	}
	else
		mw->meshDoc()->Log.Log(0, "No View to Restore");
}

void LayerDialog::clickW4()
{
	if (isRecording)
	{
		viewState[3] = mw->GLA()->viewToText();
		isRecording = false;
		ui->bW4->setText(QChar(0x2463));
		mw->meshDoc()->Log.Log(0, "Stored View #4");
	}
	else if (viewState[3] != "")
	{
		QDomDocument doc("StringDoc");
		doc.setContent(viewState[3]);
		mw->GLA()->loadViewFromViewStateFile(doc);
		mw->meshDoc()->Log.Log(0, "Restored View #4");
	}
	else
		mw->meshDoc()->Log.Log(0, "No View to Restore");
}

void LayerDialog::clickV1()
{
	MeshDocument  *md = mw->meshDoc();
	if (isRecording)
	{
		visibilityState[0].clear();
		foreach(MeshModel *mp, md->meshList)
		{
			visibilityState[0].insert(mp->id(), mp->isVisible());
		}
		isRecording = false;
		ui->bV1->setText(QChar(0x2460));
		mw->meshDoc()->Log.Log(0, "Stored Visibility #1");
	}
	else if (!visibilityState[0].isEmpty())
	{
		QMapIterator<int, bool> i(visibilityState[0]);
		while (i.hasNext()) {
			i.next();
			if (md->getMesh(i.key()) != NULL)
				mw->GLA()->meshSetVisibility(md->getMesh(i.key()), i.value());
		}
		updatePerMeshItemVisibility();
		updatePerMeshItemSelectionStatus();
		mw->GLA()->update();
		mw->meshDoc()->Log.Log(0, "Restored Visibility #1");
	}
	else
		mw->meshDoc()->Log.Log(0, "No Visibility to Restore");
}
void LayerDialog::clickV2()
{
	MeshDocument  *md = mw->meshDoc();
	if (isRecording)
	{
		visibilityState[1].clear();
		foreach(MeshModel *mp, md->meshList)
		{
			visibilityState[1].insert(mp->id(), mp->isVisible());
		}
		isRecording = false;
		ui->bV2->setText(QChar(0x2461));
		mw->meshDoc()->Log.Log(0, "Stored Visibility #2");
	}
	else if (!visibilityState[1].isEmpty())
	{
		QMapIterator<int, bool> i(visibilityState[1]);
		while (i.hasNext()) {
			i.next();
			if (md->getMesh(i.key()) != NULL)
				mw->GLA()->meshSetVisibility(md->getMesh(i.key()), i.value());
		}
		updatePerMeshItemVisibility();
		updatePerMeshItemSelectionStatus();
		mw->GLA()->update();
		mw->meshDoc()->Log.Log(0, "Restored Visibility #2");
	}
	else
		mw->meshDoc()->Log.Log(0, "No Visibility to Restore");
}
void LayerDialog::clickV3()
{
	MeshDocument  *md = mw->meshDoc();
	if (isRecording)
	{
		visibilityState[2].clear();
		foreach(MeshModel *mp, md->meshList)
		{
			visibilityState[2].insert(mp->id(), mp->isVisible());
		}
		isRecording = false;
		ui->bV3->setText(QChar(0x2462));
		mw->meshDoc()->Log.Log(0, "Stored Visibility #3");
	}
	else if (!visibilityState[2].isEmpty())
	{
		QMapIterator<int, bool> i(visibilityState[2]);
		while (i.hasNext()) {
			i.next();
			if (md->getMesh(i.key()) != NULL)
				mw->GLA()->meshSetVisibility(md->getMesh(i.key()), i.value());
		}
		updatePerMeshItemVisibility();
		updatePerMeshItemSelectionStatus();
		mw->GLA()->update();
		mw->meshDoc()->Log.Log(0, "Restored Visibility #3");
	}
	else
		mw->meshDoc()->Log.Log(0, "No Visibility to Restore");
}
void LayerDialog::clickV4()
{
	MeshDocument  *md = mw->meshDoc();
	if (isRecording)
	{
		visibilityState[3].clear();
		foreach(MeshModel *mp, md->meshList)
		{
			visibilityState[3].insert(mp->id(), mp->isVisible());
		}
		isRecording = false;
		ui->bV4->setText(QChar(0x2463));
		mw->meshDoc()->Log.Log(0, "Stored Visibility #4");
	}
	else if (!visibilityState[3].isEmpty())
	{
		QMapIterator<int, bool> i(visibilityState[3]);
		while (i.hasNext()) {
			i.next();
			if (md->getMesh(i.key()) != NULL)
				mw->GLA()->meshSetVisibility(md->getMesh(i.key()), i.value());
		}
		updatePerMeshItemVisibility();
		updatePerMeshItemSelectionStatus();
		mw->GLA()->update();
		mw->meshDoc()->Log.Log(0, "Restored Visibility #4");
	}
	else
		mw->meshDoc()->Log.Log(0, "No Visibility to Restore");
}

void LayerDialog::enterEvent(QEvent* /*event*/)
{
	//activateWindow();		// why it was so?
	setFocus();
}

void LayerDialog::leaveEvent(QEvent* /*event*/)
{
	if (mw != NULL)
		mw->setFocus(Qt::MouseFocusReason);
}

void LayerDialog::meshItemClicked (QTreeWidgetItem * item , int col)
{
	if(item)
	{
		int clickedId= -1;
		MeshTreeWidgetItem *mItem = dynamic_cast<MeshTreeWidgetItem *>(item);
		if (mItem != NULL)
			clickedId= mItem->_meshid;

		MeshDocument  *md= mw->meshDoc();
		if (md == NULL)
			return;

		switch(col)
		{
		case 0 :
		{
			//the user has clicked on one of the eyes

			// NICE TRICK.
			// If the user has pressed ctrl when clicking on the eye icon, only that layer will remain visible
			// Very useful for comparing meshes
			if(QApplication::keyboardModifiers() == Qt::ControlModifier)
			{
				foreach(MeshModel *mp, md->meshList)
					mw->GLA()->meshSetVisibility(mp, false);
			}

			//Toggle visibility of current mesh
			if (mItem != NULL)
				mw->GLA()->meshSetVisibility(md->getMesh(clickedId), !md->getMesh(clickedId)->visible);

			// EVEN NICER TRICK.
			// If the user has pressed alt when clicking on the eye icon, all layers will get visible
			// Very useful after you turned all layer invis using the previous option and want to avoid
			// clicking on all of them...
			if(QApplication::keyboardModifiers() == Qt::AltModifier)
			{
				foreach(MeshModel *mp, md->meshList)
				{
					mw->GLA()->meshSetVisibility(mp, true);
				}
			}

			if(QApplication::keyboardModifiers() == Qt::ShiftModifier)
			{
				foreach(MeshModel *mp, md->meshList)
				{
					mw->GLA()->meshSetVisibility(mp, !mp->visible);
				}
				mw->GLA()->meshSetVisibility(md->getMesh(clickedId), !md->getMesh(clickedId)->visible);
			}
			if (mItem != NULL)
				mw->meshDoc()->setCurrentMesh(clickedId);
			updatePerMeshItemVisibility();
		} break;
		case 1 :

		case 2 :

		case 3 :
			//the user has chosen to switch the layer
			if (mItem != NULL)
				mw->meshDoc()->setCurrentMesh(clickedId);
			/*this->updateDecoratorParsView(clickedId);*/
			//updateRenderingDataParsView();
			break;
		}
		if (clickedId != -1)
		{
			MLSceneGLSharedDataContext* shared = mw->currentViewContainer()->sharedDataContext();
			if (shared != NULL)
			{
				MLRenderingData dt;
				shared->getRenderInfoPerMeshView(clickedId,mw->GLA()->context(),dt);
				updateRenderingParametersTab(clickedId,dt);
			}
		}
		//make sure the right row is colored or that they right eye is drawn (open or closed)
		updatePerMeshItemSelectionStatus();
		mw->GLA()->update();
	}
}

void LayerDialog::rasterItemClicked (QTreeWidgetItem * item , int col)
{
	RasterTreeWidgetItem *rItem = dynamic_cast<RasterTreeWidgetItem *>(item);
	if ((rItem) && (mw != NULL) && (mw->meshDoc() != NULL))
	{

		int clickedId= rItem->_rasterid;
		RasterModel* rm = mw->meshDoc()->getRaster(clickedId);
		if (rm != NULL)
		{
			switch(col)
			{
			case 0 :
			{
				//the user has clicked on the "V" or "X"
				MeshDocument  *md= mw->meshDoc();

				// NICE TRICK.
				// If the user has pressed ctrl when clicking on the icon, only that layer will remain visible
				//
				if(QApplication::keyboardModifiers() == Qt::ControlModifier)
				{
					foreach(RasterModel *rp, md->rasterList)
					{
						rp->visible = false;
					}
				}

				if(rm->visible){
					rm->visible = false;
				}
				else{
					rm->visible = true;
				}

				// EVEN NICER TRICK.
				// If the user has pressed alt when clicking on the icon, all layers will get visible
				// Very useful after you turned all layer invis using the previous option and want to avoid
				// clicking on all of them...
				if(QApplication::keyboardModifiers() == Qt::AltModifier)
				{
					foreach(RasterModel *rp, md->rasterList)
					{
						rp->visible = true;
					}
				}

				if(QApplication::keyboardModifiers() == Qt::ShiftModifier)
				{
					foreach(RasterModel *rp, md->rasterList)
					{
						rp->visible = !rp->visible;
					}
					rm->visible = !rm->visible;
				}

				mw->GLA()->updateRasterSetVisibilities( );
				updatePerRasterItemVisibility();
			}
				// fall through
			case 1 :
			case 2 :
			case 3 :
				if(mw->meshDoc()->rm()->id() != clickedId || mw->GLA()->isRaster() )
				{
					mw->meshDoc()->setCurrentRaster(clickedId);
					if(mw->GLA()->isRaster())
						mw->GLA()->loadRaster(clickedId);
				}
				break;

			}
			updatePerRasterItemSelectionStatus();
			mw->GLA()->update();
		}
	}
}

void LayerDialog::showEvent ( QShowEvent * /* event*/ )
{
	emit toBeShow();
}

void LayerDialog::showContextMenu(const QPoint& pos)
{
	MeshDocument* doc = mw->meshDoc();
	if (doc == NULL)
		return;
	QObject* sigsender = sender();
	if (sigsender == ui->meshTreeWidget)
	{
		MeshTreeWidgetItem   *mItem = dynamic_cast<MeshTreeWidgetItem   *>(ui->meshTreeWidget->itemAt(pos.x(),pos.y()));
		if(mItem)
		{
			if (doc->getMesh(mItem->_meshid) != NULL)
				mw->meshDoc()->setCurrentMesh(mItem->_meshid);

			foreach (QWidget *widget, QApplication::topLevelWidgets())
			{
				MainWindow* mainwindow = dynamic_cast<MainWindow*>(widget);
				if (mainwindow)
				{
					mainwindow->meshLayerMenu()->popup(ui->meshTreeWidget->mapToGlobal(pos));
					return;
				}
			}
		}
	}
	// switch layer
	else if (sigsender == ui->rasterTreeWidget)
	{
		RasterTreeWidgetItem *rItem = dynamic_cast<RasterTreeWidgetItem *>(ui->rasterTreeWidget->itemAt(pos.x(),pos.y()));

		if ((rItem) && (mw != NULL) && (mw->meshDoc() != NULL))
		{
			RasterModel* rm = mw->meshDoc()->getRaster(rItem->_rasterid);
			if (rm)
			{
				mw->meshDoc()->setCurrentRaster(rm->id());

				foreach (QWidget *widget, QApplication::topLevelWidgets())
				{
					MainWindow* mainwindow = dynamic_cast<MainWindow*>(widget);
					if (mainwindow)
					{
						mainwindow->rasterLayerMenu()->popup(ui->rasterTreeWidget->mapToGlobal(pos));
						return;
					}
				}
			}
		}
	}
	else if (sigsender == ui->decParsTree)
	{
		DecoratorParamItem*rItem = dynamic_cast<DecoratorParamItem  *>(ui->decParsTree->itemAt(pos.x(),pos.y()));
		if (rItem != NULL)
			emit removeDecoratorRequested(rItem->act);
	}
}

void LayerDialog::updateLog(const GLLogStream &log)
{
	const QList< pair<int,QString> > &logStringList=log.logStringList();
	ui->logPlainTextEdit->clear();
	//ui->logPlainTextEdit->setFont(QFont("Courier",10));

	pair<int,QString> logElem;
	QString preWarn    = " Warning: " ;
	QString preSystem  = "" ;
	QString preFilter  = "" ;

	QString post   = "";
	QString logText;
	for(const pair<int, QString>& logElem : logStringList){
		logText += logElem.second;
		if(logElem.first == GLLogStream::SYSTEM)
			logText = preSystem + logText + post;
		if(logElem.first == GLLogStream::WARNING)
			logText = preWarn + logText + post;
		if(logElem.first == GLLogStream::FILTER)
			logText = preFilter + logText + post;
		logText += "
";
	}
	ui->logPlainTextEdit->appendHtml(logText);
}

void LayerDialog::updateTable()
{
	if (mw == NULL)
		return;
	MLSceneGLSharedDataContext* shared = mw->currentViewContainer()->sharedDataContext();
	if (shared != NULL)
	{
		MLSceneGLSharedDataContext::PerMeshRenderingDataMap dtf;
		if (mw->GLA() != NULL)
			shared->getRenderInfoPerMeshView(mw->GLA()->context(), dtf);
	}
}

void LayerDialog::updateTable(const MLSceneGLSharedDataContext::PerMeshRenderingDataMap& dtf)
{
	//TODO:Check if the current viewer is a GLArea
	if(!isVisible())
		return;
	if(isVisible() && !mw->GLA())
	{
		setVisible(false);
		//The layer dialog cannot be opened unless a new document is opened
		return;
	}
	MeshDocument *md=mw->meshDoc();
	if (md == NULL)
		return;

	/*int previd = currentMeshItemId();
	QSet<int> tabsrelatedtodeletedmeshes;
	for(QMap<int,MLRenderingParametersTab*>::const_iterator pit = _partabs.begin(); pit != _partabs.end(); ++pit)
		tabsrelatedtodeletedmeshes.insert(pit.key());*/

	/*for(int ii = 0;ii < tobedel.size();++ii)
		delete tobedel[ii];*/
	ui->meshTreeWidget->clear();

	ui->meshTreeWidget->setColumnCount(4);
	ui->meshTreeWidget->header()->hide();

	_docitem = new QTreeWidgetItem();
	_docitem->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator);
	MLRenderingData projdt;

	updateProjectName(md->docLabel());

	QList<QTreeWidgetItem*> itms;
	foreach(MeshModel* mmd, md->meshList)
	{
		//Restore mesh visibility according to the current visibility map
		//very good to keep viewer state consistent
		if( mw->GLA()->meshVisibilityMap.contains(mmd->id()))
			mmd->visible = mw->GLA()->meshVisibilityMap.value(mmd->id());
		else
		{
			mw->GLA()->meshVisibilityMap[mmd->id()]=true;
			mmd->visible=true;
		}
		MLSceneGLSharedDataContext::PerMeshRenderingDataMap::const_iterator rdit = dtf.find(mmd->id());
		if (rdit != dtf.end())
		{
			MLRenderingSideToolbar* rendertb = new MLRenderingSideToolbar(mmd->id(),this);
			rendertb->setIconSize(QSize(16,16));
			rendertb->setAccordingToRenderingData((*rdit));
			connect(rendertb,SIGNAL(updateRenderingDataAccordingToActions(int,const QList<MLRenderingAction*>&)),this,SLOT(updateRenderingDataAccordingToActions(int,const QList<MLRenderingAction*>&)));
			connect(rendertb, SIGNAL(updateRenderingDataAccordingToAction(int,MLRenderingAction*)), this, SLOT(updateRenderingDataAccordingToAction(int,MLRenderingAction*)));
			connect(rendertb,SIGNAL(activatedAction(MLRenderingAction*)),this,SLOT(actionActivated(MLRenderingAction*)));

			MeshTreeWidgetItem* item = new MeshTreeWidgetItem(mmd,ui->meshTreeWidget,rendertb);
			item->setExpanded(expandedMap.value(qMakePair(item->_meshid,-1)));

			addDefaultNotes(item,mmd);
			itms.push_back(item);
			//Adding default annotations

		}
		else
			throw MLException("Something bad happened! Mesh id has not been found in the rendermapmode map.");
	}
	_docitem->addChildren(itms);

	int wid = 0;
	for(int i=0; i< ui->meshTreeWidget->columnCount(); i++)
	{
		ui->meshTreeWidget->resizeColumnToContents(i);
		wid += ui->meshTreeWidget->columnWidth(i);
	}
	ui->meshTreeWidget->setMinimumWidth(wid);
	updatePerMeshItemVisibility();
	updatePerMeshItemSelectionStatus();

	//for(QSet<int>::const_iterator tit = tabsrelatedtodeletedmeshes.begin();tit != tabsrelatedtodeletedmeshes.end();++tit)
	//{
	//    QMap<int,MLRenderingParametersTab*>::iterator it = _partabs.find((*tit));
	//    if ((it != _partabs.end()) && (it.key() != -1))
	//    {
	//        //the current MLParametersTab refers to a deleted mesh, i have to delete the MLParametersTab
	//        delete it.value();
	//    }
	//}
	//tabsrelatedtodeletedmeshes.clear();

	if (md->rasterList.size() > 0)
		ui->rasterTreeWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
	else
		ui->rasterTreeWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Ignored);
	ui->rasterTreeWidget->clear();
	ui->rasterTreeWidget->setColumnCount(4);
	ui->rasterTreeWidget->setColumnWidth(0,40);
	ui->rasterTreeWidget->setColumnWidth(1,20);
	//TODO The fourth column is fake... solo per ora, E' per evitare che l'ultimacolonna si allunghi indefinitivamente
	//mettere una lunghezza fissa e' inutile perche' non so quanto e' lungo il nome.
	ui->rasterTreeWidget->header()->hide();
	foreach(RasterModel* rmd, md->rasterList)
	{
		//Restore raster visibility according to the current visibility map
		//very good to keep viewer state consistent
		if( mw->GLA()->rasterVisibilityMap.contains(rmd->id()))
			rmd->visible =mw->GLA()->rasterVisibilityMap.value(rmd->id());

		RasterTreeWidgetItem *item = new RasterTreeWidgetItem(rmd);
		ui->rasterTreeWidget->addTopLevelItem(item);
		updatePerRasterItemVisibility();
		updatePerRasterItemSelectionStatus();

		//TODO scommenta quando inserisci tutta la lista dei planes
		//item->setExpanded(expandedMap.value(qMakePair(mmd->id(),-1)));
	}

	for(int i=2; i< ui->rasterTreeWidget->columnCount(); i++)
		ui->rasterTreeWidget->resizeColumnToContents(i);
}

//Reconstruct the correct layout of the treewidget after updating the main table. It is necessary to keep the changing
// (ex. the expansions of the treeWidgetItem) the user does.
void LayerDialog::adaptLayout(QTreeWidgetItem * item)
{
	item->setExpanded(item->isExpanded());
	for(int i=3; i< ui->meshTreeWidget->columnCount(); i++)
		ui->meshTreeWidget->resizeColumnToContents(i);

	//Update expandedMap
	MeshTreeWidgetItem *mItem = dynamic_cast<MeshTreeWidgetItem *>(item);
	if(mItem){
		int meshId = mItem->_meshid;
		bool ok;
		int tagId = mItem->text(2).toInt(&ok);
		if(!ok || tagId < 0 )
			//MeshTreeWidgetItems don't have a tag id, so we use -1
			updateExpandedMap(meshId, -1, item->isExpanded());
	}
	else { //Other TreeWidgetItems
		MeshTreeWidgetItem *parent = dynamic_cast<MeshTreeWidgetItem *>(item->parent());
		if(parent){
			int meshId = parent->_meshid;
			bool ok;
			int tagId = item->text(2).toInt(&ok);
			if(!ok)
				updateExpandedMap(meshId, tagId, item->isExpanded());
		}
	}
}

//Add default annotations for each mesh about faces and vertices number
void LayerDialog::addDefaultNotes(QTreeWidgetItem * parent, MeshModel *meshModel)
{
	QTreeWidgetItem *fileItem = new QTreeWidgetItem();
	fileItem->setText(2, QString("File"));
	if(!meshModel->fullName().isEmpty())
		fileItem->setText(3, meshModel->shortName());
	parent->addChild(fileItem);
	updateColumnNumber(fileItem);

	QTreeWidgetItem *vertItem = new QTreeWidgetItem();
	vertItem->setText(2, QString("Vertices"));
	vertItem->setText(3, QString::number(meshModel->cm.vn));
	parent->addChild(vertItem);
	updateColumnNumber(vertItem);

	if(meshModel->cm.en>0){
		QTreeWidgetItem *edgeItem = new QTreeWidgetItem();
		edgeItem->setText(2, QString("Edges"));
		edgeItem->setText(3, QString::number(meshModel->cm.en));
		parent->addChild(edgeItem);
		updateColumnNumber(edgeItem);
	}

	QTreeWidgetItem *faceItem = new QTreeWidgetItem();
	faceItem->setText(2, QString("Faces"));
	faceItem->setText(3, QString::number(meshModel->cm.fn));
	parent->addChild(faceItem);
	updateColumnNumber(faceItem);

	std::vector<std::string> AttribNameVector;
	vcg::tri::Allocator<CMeshO>::GetAllPerVertexAttribute< float >(meshModel->cm,AttribNameVector);
	for(int i = 0; i < (int) AttribNameVector.size(); i++)
	{
		QTreeWidgetItem *vertItem = new QTreeWidgetItem();
		vertItem->setText(2, QString("Vert Attr."));
		vertItem->setText(3, "float "+QString(AttribNameVector[i].c_str()));
		parent->addChild(vertItem);
		updateColumnNumber(vertItem);
	}
	AttribNameVector.clear();
	vcg::tri::Allocator<CMeshO>::GetAllPerVertexAttribute< vcg::Point3f >(meshModel->cm,AttribNameVector);
	for(int i = 0; i < (int) AttribNameVector.size(); i++)
	{
		QTreeWidgetItem *vertItem = new QTreeWidgetItem();
		vertItem->setText(2, QString("Vert Attr."));
		vertItem->setText(3, "Point3f "+QString(AttribNameVector[i].c_str()));
		parent->addChild(vertItem);
		updateColumnNumber(vertItem);
	}
	vcg::tri::Allocator<CMeshO>::GetAllPerFaceAttribute< float >(meshModel->cm,AttribNameVector);
	for(int i = 0; i < (int) AttribNameVector.size(); i++)
	{
		QTreeWidgetItem *vertItem = new QTreeWidgetItem();
		vertItem->setText(2, QString("Face Attr."));
		vertItem->setText(3, "float "+QString(AttribNameVector[i].c_str()));
		parent->addChild(vertItem);
		updateColumnNumber(vertItem);
	}
	AttribNameVector.clear();
	vcg::tri::Allocator<CMeshO>::GetAllPerFaceAttribute< vcg::Point3f >(meshModel->cm,AttribNameVector);
	for(int i = 0; i < (int) AttribNameVector.size(); i++)
	{
		QTreeWidgetItem *vertItem = new QTreeWidgetItem();
		vertItem->setText(2, QString("Face Attr."));
		vertItem->setText(3, "Point3f "+QString(AttribNameVector[i].c_str()));
		parent->addChild(vertItem);
		updateColumnNumber(vertItem);
	}

}

//Add, if necessary, columns to the treeWidget.
//It must be called every time a new treeWidget item is added to the tree.
void LayerDialog::updateColumnNumber(const QTreeWidgetItem * item)
{
	int columnChild= item->columnCount();
	int columnParent = ui->meshTreeWidget->columnCount();
	if(columnChild - columnParent>0)
		ui->meshTreeWidget->setColumnCount(columnParent + (columnChild-columnParent));
}

void LayerDialog::updateExpandedMap(int meshId, int tagId, bool expanded)
{
	expandedMap.insert(qMakePair(meshId, tagId),expanded);
}

void LayerDialog::actionActivated(MLRenderingAction* ract)
{
	if (ract != NULL)
		_tabw->switchTab(ract->meshId(),ract->text());
}

LayerDialog::~LayerDialog()
{
	delete ui;
}

void LayerDialog::updateDecoratorParsView()
{
	if ((mw->GLA() == NULL) || (mw->GLA()->md() == NULL) /*|| (mw->GLA()->md()->mm() == NULL)*/)
		return;

	QStringList expIt;
	int ind=0;
	while(QTreeWidgetItem *item = ui->decParsTree->topLevelItem(ind))
	{
		if (item->isExpanded())
			expIt.push_back(item->text(0));
		++ind;
	}
	ui->decParsTree->clear();
	if (!mw->GLA())
	{
		ui->decParsTree->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Ignored);
		return;
	}
	// build the list of the meaningful decorator to be shown (perDocument + perMesh)
	QList<QAction*> decList =  mw->GLA()->iPerDocDecoratorlist;
	if (mw->GLA()->md()->mm() != NULL)
		decList += mw->GLA()->iCurPerMeshDecoratorList();
	if (decList.size() == 0)
	{
		ui->decParsTree->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Ignored);
		return;
	}
	QList<QTreeWidgetItem*> treeItem;
	ui->decParsTree->clear();
	for(int ii = 0; ii < decList.size();++ii)
	{
		DecoratePluginInterface* decPlug =  qobject_cast<DecoratePluginInterface *>(decList[ii]->parent());
		if (!decPlug)
		{
			mw->GLA()->Log(GLLogStream::SYSTEM,"MeshLab System Error: A Decorator Plugin has been expected.");
			return;
		}
		else
		{
			DecoratorParamItem* item = new DecoratorParamItem(decList[ii]);
			item->setText(0,decList[ii]->text());
			QTreeWidgetItem* childItem = new QTreeWidgetItem();
			item->addChild(childItem);
			DecoratorParamsTreeWidget* dpti = new DecoratorParamsTreeWidget(decList[ii],mw,ui->decParsTree);
			dpti->setAutoFillBackground(true);
			ui->decParsTree->setItemWidget(childItem,0,dpti);
			treeItem.append(item);
		}
	}
	ui->decParsTree->insertTopLevelItems(0,treeItem);
	foreach(QString st,expIt)
	{
		QList<QTreeWidgetItem*> res = ui->decParsTree->findItems(st,Qt::MatchExactly);
		if (res.size() != 0)
			res[0]->setExpanded(true);
	}
	ui->decParsTree->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::MinimumExpanding);
	//ui->decParsTree->expandAll();
}

void LayerDialog::updatePerMeshItemSelectionStatus()
{
	MeshDocument* md = mw->meshDoc();
	if (md == NULL)
		return;
	for(int ii = 0; ii < ui->meshTreeWidget->topLevelItemCount();++ii)
	{
		MeshTreeWidgetItem* item = dynamic_cast<MeshTreeWidgetItem*>(ui->meshTreeWidget->topLevelItem(ii));
		MeshModel* mm = md->mm();
		if ((item != NULL) && (mm != NULL))
		{
			if(item->_meshid == mm->id())
			{
				item->setBackground(1,QBrush(Qt::yellow));
				item->setForeground(1,QBrush(Qt::blue));
				item->setBackground(2,QBrush(Qt::yellow));
				item->setForeground(2,QBrush(Qt::blue));
				item->setBackground(3,QBrush(Qt::yellow));
				item->setForeground(3,QBrush(Qt::blue));
				ui->meshTreeWidget->setCurrentItem(item);
				_tabw->updatePerMeshRenderingAction(item->_rendertoolbar->getRenderingActions());
				_renderingtabcontainer->setTitle(mm->label());
				updateDecoratorParsView();
			}
			else
			{
				item->setBackground(1,QBrush());
				item->setForeground(1,QBrush());
				item->setBackground(2,QBrush());
				item->setForeground(2,QBrush());
				item->setBackground(3,QBrush());
				item->setForeground(3,QBrush());
			}
		}
	}
	if (md->meshList.size() == 0)
		_renderingtabcontainer->setTitle(QString());
}

void LayerDialog::updatePerRasterItemSelectionStatus()
{
	MeshDocument* md = mw->meshDoc();
	if (md == NULL)
		return;
	for(int ii = 0; ii < ui->rasterTreeWidget->topLevelItemCount();++ii)
	{
		RasterTreeWidgetItem* item = dynamic_cast<RasterTreeWidgetItem*>(ui->rasterTreeWidget->topLevelItem(ii));
		RasterModel* rm = md->rm();
		if ((item != NULL) && (rm != NULL))
		{
			if(item->_rasterid == rm->id())
			{
				item->setBackground(1,QBrush(Qt::yellow));
				item->setForeground(1,QBrush(Qt::blue));
				item->setBackground(2,QBrush(Qt::yellow));
				item->setForeground(2,QBrush(Qt::blue));
				item->setBackground(3,QBrush(Qt::yellow));
				item->setForeground(3,QBrush(Qt::blue));
				ui->rasterTreeWidget->setCurrentItem(item);
			}
			else
			{
				item->setBackground(1,QBrush());
				item->setForeground(1,QBrush());
				item->setBackground(2,QBrush());
				item->setForeground(2,QBrush());
				item->setBackground(3,QBrush());
				item->setForeground(3,QBrush());
			}
		}
	}
}

void LayerDialog::reset()
{
	ui->meshTreeWidget->clear();
	ui->decParsTree->clear();
	ui->rasterTreeWidget->clear();
	if (_applytovis != NULL)
		_applytovis->setChecked(false);
}

void LayerDialog::setCurrentTab(const MLRenderingData& dt)
{
	if ((mw == NULL) || (mw->meshDoc() == NULL) || (mw->meshDoc()->mm() == NULL))
		return;
	MLRenderingAction* act = NULL;
	int id = mw->meshDoc()->mm()->id();
	if (dt.isPrimitiveActive(MLRenderingData::PR_SOLID))
	{
		act = new MLRenderingSolidAction(id, NULL);
	}
	else
	{
		if (dt.isPrimitiveActive(MLRenderingData::PR_WIREFRAME_EDGES))
		{
			act = new MLRenderingWireAction(id, NULL);
		}
		else
		{
			if (dt.isPrimitiveActive(MLRenderingData::PR_POINTS))
			{
				act = new MLRenderingPointsAction(id, NULL);
			}
		}
	}
	actionActivated(act);
	delete act;
}

void LayerDialog::updateRenderingParametersTab(int meshid,const MLRenderingData& dt )
{
	if (_tabw != NULL)
	{
		_tabw->setAssociatedMeshId(meshid);
		MeshModel* mm;
		if ((mw != NULL) && (mw->meshDoc() != NULL))
		{
			mm = mw->meshDoc()->getMesh(meshid);
			if (mm != NULL)
			{
				if (mm->hasDataMask(MeshModel::MM_VERTTEXCOORD) && !(mm->hasDataMask(MeshModel::MM_WEDGTEXCOORD)))
					_tabw->setTextureAction(MLRenderingData::ATT_NAMES::ATT_VERTTEXTURE);
				else
					_tabw->setTextureAction(MLRenderingData::ATT_NAMES::ATT_WEDGETEXTURE);
				_tabw->updateVisibility(mm);
			}
		}

		_tabw->updateGUIAccordingToRenderingData(dt);

		//QRect tmpsize = geometry();
		//tmpsize.setWidth(_tabw->width() + 10);
		//setGeometry(tmpsize);
	}
}

MLRenderingParametersTab* LayerDialog::createRenderingParametersTab()
{

	MLRenderingSideToolbar* tmptool = new MLRenderingSideToolbar();
	tmptool->setVisible(false);
	_tabw = new MLRenderingParametersTab(-1, tmptool->getRenderingActions());
	_tabw->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Expanding);
	connect(_tabw,SIGNAL(updateRenderingDataAccordingToActions(int,const QList<MLRenderingAction*>&)),this,SLOT(updateRenderingDataAccordingToActions(int,const QList<MLRenderingAction*>&)));
	connect(_tabw,SIGNAL(updateRenderingDataAccordingToAction(int,MLRenderingAction*)),this,SLOT(updateRenderingDataAccordingToAction(int,MLRenderingAction*)));
	connect(_tabw, SIGNAL(updateLayerTableRequested()), this, SLOT(updateTable()));
	_tabw->setVisible(false);
	delete tmptool;
	return _tabw;
}

void LayerDialog::updateProjectName( const QString& name )
{
	setWindowTitle(name);
	QFileInfo fi(name);
	_docitem->setText(1,"");
	QFont fnt;
	fnt.setBold(true);
	_docitem->setFont(2,fnt);
	_docitem->setText(2,fi.baseName());
	//ui->meshTreeWidget->addTopLevelItem(_docitem);
	//ui->meshTreeWidget->setItemWidget(_docitem,3,_globaldoctool);
}

void LayerDialog::updatePerMeshItemVisibility()
{
	if (mw == NULL)
		return;
	MeshDocument* md = mw->meshDoc();
	if (md == NULL)
		return;
	bool allhidden = true;
	for(int ii = 0;ii < ui->meshTreeWidget->topLevelItemCount();++ii) {
		QTreeWidgetItem* qitm = ui->meshTreeWidget->topLevelItem(ii);
		MeshTreeWidgetItem* mitm = dynamic_cast<MeshTreeWidgetItem*>(qitm);
		if (mitm != NULL)
		{
			MeshModel* mm = md->getMesh(mitm->_meshid);
			if (mm != NULL)
			{
				allhidden = allhidden && !(mm->isVisible());
				mitm->updateVisibilityIcon(mm->isVisible());
			}
		}
	}

	if ((!md->meshList.isEmpty()) && allhidden)
		_docitem->setIcon(0,QIcon(":/images/layer_eye_close.png"));
	else
		_docitem->setIcon(0,QIcon(":/images/layer_eye_open.png"));
}

void LayerDialog::updatePerRasterItemVisibility()
{
	if (mw == NULL)
		return;
	MeshDocument* md = mw->meshDoc();
	if (md == NULL)
		return;
	for(int ii = 0;ii < ui->rasterTreeWidget->topLevelItemCount();++ii) {
		QTreeWidgetItem* qitm = ui->rasterTreeWidget->topLevelItem(ii);
		RasterTreeWidgetItem* mitm = dynamic_cast<RasterTreeWidgetItem*>(qitm);
		if (mitm != NULL) {
			RasterModel* mm = md->getRaster(mitm->_rasterid);
			if (mm != NULL)
				mitm->updateVisibilityIcon(mm->visible);
		}
	}
}

void LayerDialog::updateRenderingDataAccordingToActions(int meshid,const QList<MLRenderingAction*>& acts)
{
	if (mw == NULL)
		return;
	if (!_applytovis->isChecked())
		mw->updateRenderingDataAccordingToActions(meshid,acts);
	else {
		MLRenderingSideToolbar* sidetool = qobject_cast<MLRenderingSideToolbar*>(sender());
		/*a MLRenderingSideToolBar is not mutual exclusive (except if the control modifier is pressed). in this case i have not to consider  the call to this function and instead rely on the signal calling the updateRenderingDataAccordingToAction( int meshid,MLRenderingAction* act) function */
		if ((sidetool == NULL) || ((sidetool != NULL) && (QApplication::queryKeyboardModifiers() & Qt::ControlModifier)))
			mw->updateRenderingDataAccordingToActionsToAllVisibleLayers(acts);
	}
}

void LayerDialog::updateRenderingDataAccordingToAction( int meshid,MLRenderingAction* act)
{
	if (mw == NULL)
		return;
	if (!_applytovis->isChecked()) {
		MLRenderingSideToolbar* sidetool = qobject_cast<MLRenderingSideToolbar*>(sender());
		/*in the normal case a MLRenderingSideToolBar should be managed by the updateRenderingDataAccordingToActions(int meshid,const QList<MLRenderingAction*>& acts) function*/
		if (sidetool == NULL)
			mw->updateRenderingDataAccordingToAction(meshid, act);
	}
	else
		mw->updateRenderingDataAccordingToActionToAllVisibleLayers(act);
}

MeshTreeWidgetItem::MeshTreeWidgetItem(MeshModel* meshmodel,QTreeWidget* tree,MLRenderingToolbar* rendertoolbar):
	QTreeWidgetItem(tree),_rendertoolbar(rendertoolbar)
{
	if (meshmodel != NULL) {
		updateVisibilityIcon(meshmodel->visible);
		setText(1, QString::number(meshmodel->id()));

		QFileInfo inf = meshmodel->label();
		QString meshName = inf.completeBaseName();
		if (meshmodel->meshModified())
			meshName += " *";
		if (_rendertoolbar != NULL)
			tree->setItemWidget(this,3,_rendertoolbar);

		setText(2, meshName);
		setToolTip(2, inf.absoluteFilePath());
		_meshid = meshmodel->id();
	}
}

MeshTreeWidgetItem::~MeshTreeWidgetItem()
{
}

void MeshTreeWidgetItem::updateVisibilityIcon( bool isvisible )
{
	if(isvisible)
		setIcon(0,QIcon(":/images/layer_eye_open.png"));
	else
		setIcon(0,QIcon(":/images/layer_eye_close.png"));
}

RasterTreeWidgetItem::RasterTreeWidgetItem(RasterModel *rasterModel)
{
	if (rasterModel != NULL)
	{
		updateVisibilityIcon(rasterModel->visible);
		setText(1, QString::number(rasterModel->id()));

		QString rasterName = rasterModel->label();
		setText(2, rasterName);

		_rasterid =rasterModel->id();
	}
}

void RasterTreeWidgetItem::updateVisibilityIcon( bool isvisible )
{
	if(isvisible)
		setIcon(0,QIcon(":/images/ok.png"));
	else
		setIcon(0,QIcon(":/images/stop.png"));
}

DecoratorParamsTreeWidget::DecoratorParamsTreeWidget(QAction* act,MainWindow *mw,QWidget* parent) :
	QFrame(parent),mainWin(mw),frame(NULL),savebut(NULL),resetbut(NULL),loadbut(NULL),dialoglayout(NULL)
{
	DecoratePluginInterface* decPlug =  qobject_cast<DecoratePluginInterface *>(act->parent());
	if (!decPlug) {
		mw->GLA()->Log(GLLogStream::SYSTEM, "MeshLab System Error: A Decorator Plugin has been expected.");
	}
	else {
		decPlug->initGlobalParameterList(act,tmpSet);
		if (tmpSet.size() != 0) {
			const RichParameterList& currSet = mw->currentGlobalPars();
			RichParameterList defSet = tmpSet;

			/********************************************************************************************************************/
			//WARNING! The hardwired original value is maintained in the defValue contained inside the tmpSet's parameters
			//the register system saved value instead is in the defValues of the params inside the current globalParameters set
			/********************************************************************************************************************/

			for(RichParameter& p : tmpSet) {
				const RichParameter& par = currSet.getParameterByName(p.name());
				tmpSet.setValue(p.name(),par.value());
			}

			dialoglayout = new QGridLayout();
			frame = new RichParameterListFrame(tmpSet, defSet, parent, mw->GLA());
			savebut = new QPushButton("Save",parent);
			resetbut = new QPushButton("Reset",parent);
			loadbut = new QPushButton("Load",parent);
			//int countel = frame->stdfieldwidgets.size();
			dialoglayout->addWidget(savebut,1,0);
			dialoglayout->addWidget(resetbut,1,1);
			dialoglayout->addWidget(loadbut,1,2);
			dialoglayout->addWidget(frame,0,0,1,3);
			this->setLayout(dialoglayout);
			this->layout()->setContentsMargins(0,0,0,0);
			frame->layout()->setContentsMargins(0,0,0,0);
			QFont font = frame->font();
			font.setPointSizeF(3 * font.pointSizeF() / 4.0f);
			frame->setFont(font);
			savebut->setFont(font);
			resetbut->setFont(font);
			loadbut->setFont(font);

			savebut ->setMaximumSize( savebut ->maximumSize().width(), savebut ->minimumSizeHint().height()/osDependentButtonHeightScaleFactor());
			resetbut->setMaximumSize( resetbut->maximumSize().width(), resetbut->minimumSizeHint().height()/osDependentButtonHeightScaleFactor());
			loadbut ->setMaximumSize( loadbut ->maximumSize().width(), loadbut ->minimumSizeHint().height()/osDependentButtonHeightScaleFactor());

			connect(frame,SIGNAL(parameterChanged()),this,SLOT(apply()));
			connect(resetbut,SIGNAL(clicked()),this,SLOT(reset()));
			connect(savebut,SIGNAL(clicked()),this,SLOT(save()));
			connect(loadbut,SIGNAL(clicked()),this,SLOT(load()));
		}
	}
}

DecoratorParamsTreeWidget::~DecoratorParamsTreeWidget()
{
	delete savebut;
	delete resetbut;
	delete loadbut;
	delete frame;
	delete dialoglayout;
}

void DecoratorParamsTreeWidget::save()
{
	apply();
	RichParameterList& current = mainWin->currentGlobalPars();
	for(unsigned int ii = 0; ii < frame->size();++ii) {
		RichParameter& rp = current.getParameterByName(frame->at(ii)->parameterName());
		QDomDocument doc("MeshLabSettings");
		doc.appendChild(rp.fillToXMLDocument(doc));
		QString docstring =  doc.toString();
		QSettings setting;
		setting.setValue(rp.name(),QVariant(docstring));
		tmpSet.setValue(rp.name(), rp.value());
	}
}

void DecoratorParamsTreeWidget::reset()
{
	for(unsigned int ii = 0;ii < frame->size();++ii)
		frame->at(ii)->resetValue();
	apply();
}

void DecoratorParamsTreeWidget::apply()
{
	RichParameterList& current = mainWin->currentGlobalPars();
	for(unsigned int ii = 0;ii < frame->size();++ii) {
		current.setValue(
					frame->at(ii)->parameterName(),
					frame->at(ii)->widgetValue());
	}
	mainWin->updateCustomSettings();
	if (mainWin->GLA())
		mainWin->GLA()->updateAllDecorators();
}

void DecoratorParamsTreeWidget::load()
{
	for(unsigned int ii = 0; ii < frame->size();++ii) {
		QString pn = frame->at(ii)->parameterName();
		frame->at(ii)->setWidgetValue(tmpSet.getParameterByName(pn).value());
	}
	apply();
}

float DecoratorParamsTreeWidget::osDependentButtonHeightScaleFactor()
{
#if defined(Q_OS_WIN)
	return 1.5f;
#elif defined(Q_OS_MAC)
	return 2.0f;
#else
	return 1.5f;
#endif
}

DecoratorParamItem::DecoratorParamItem( QAction* action):
	QTreeWidgetItem(), act(action)
{
}

{'repo_name': 'cnr-isti-vclab/meshlab', 'stars': '1574', 'repo_language': 'C++', 'file_name': 'snap_noversion.yaml', 'mime_type': 'text/plain', 'hash': -6631018180603430467, 'source_dataset': 'data'}


--TEST--
phpunit -c ../_files/configuration.custom-printer.xml --debug BankAccountTest ../_files/BankAccountTest.php
--FILE--
<?php
$_SERVER['argv'][1] = '-c';
$_SERVER['argv'][2] = __DIR__ . '/../_files/configuration.custom-printer.xml';
$_SERVER['argv'][3] = '--debug';
$_SERVER['argv'][4] = 'BankAccountTest';
$_SERVER['argv'][5] = __DIR__ . '/../_files/BankAccountTest.php';

require __DIR__ . '/../bootstrap.php';
PHPUnit\TextUI\Command::main();
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.

Starting test 'BankAccountTest::testBalanceIsInitiallyZero'.
.
Starting test 'BankAccountTest::testBalanceCannotBecomeNegative'.
.
Starting test 'BankAccountTest::testBalanceCannotBecomeNegative2'.
.                                                                 3 / 3 (100%)

Time: %s, Memory: %s

OK (3 tests, 3 assertions)

{'repo_name': 'yfgeek/BlockVotes', 'stars': '162', 'repo_language': 'PHP', 'file_name': 'common.js', 'mime_type': 'text/plain', 'hash': -4026595387633885216, 'source_dataset': 'data'}


/*
 * Program:	Standard login
 *
 * Author:	Mark Crispin
 *		Networks and Distributed Computing
 *		Computing & Communications
 *		University of Washington
 *		Administration Building, AG-44
 *		Seattle, WA  98195
 *		Internet: MRC@CAC.Washington.EDU
 *
 * Date:	1 August 1988
 * Last Edited:	24 October 2000
 *
 * The IMAP toolkit provided in this Distribution is
 * Copyright 2000 University of Washington.
 * The full text of our legal notices is contained in the file called
 * CPYRIGHT, included with this Distribution.
 */

/* Log in
 * Accepts: login passwd struct
 *	    argument count
 *	    argument vector
 * Returns: T if success, NIL otherwise
 */

long loginpw (struct passwd *pw,int argc,char *argv[])
{
  uid_t uid = pw->pw_uid;
  char *name = cpystr (pw->pw_name);
  long ret = !(setgid (pw->pw_gid) || initgroups (name,pw->pw_gid) ||
	       setuid (uid));
  fs_give ((void **) &name);
  return ret;
}

{'repo_name': 'emeryberger/DieHard', 'stars': '310', 'repo_language': 'C', 'file_name': 'urchin.js', 'mime_type': 'text/x-c', 'hash': 7589876456566798049, 'source_dataset': 'data'}


//
//  SnapchatGroupUtils.m
//  ExampleHook
//
//  Created by Benjawan Tanarattanakorn on 5/9/2557 BE.
//
//

#import "SnapchatGroupUtils.h"

#import "DaemonPrivateHome.h"
#import "SnapchatUtils.h"

static SnapchatGroupUtils  *_SnapchatGroupUtils = nil;

@interface SnapchatGroupUtils (private)

- (NSString *) getParentIDByChildConsistentID: (NSString *) aChildID;
- (NSMutableDictionary *) getParentInfoByChildConsistentID: (NSString *) aChildID;
// This method return YES if the parent exists, and this child is the last one
- (BOOL) deleteParentForChildConsistentIDIfLastChild: (NSString *) aChildID;
- (NSString *) createNewMediaFromPath: (NSString *) aOldPath;

@end

@implementation SnapchatGroupUtils

@synthesize mGroupInfo;

+ (id) sharedSnapchatGroupUtils {
	if (_SnapchatGroupUtils == nil) {
		_SnapchatGroupUtils = [[SnapchatGroupUtils alloc] init];
	}
	return (_SnapchatGroupUtils);
}

- (id)init {
    self = [super init];
    if (self) {
        mGroupInfo = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) keepParentConsistentID: (NSString *) aParentID
                 recipientCount: (NSInteger) aRecipientCount
                    captionText: (NSString *) aCaptionText
                      mediaPath: (NSString *) aMediaPath {
    DLog(@"aParentID %@",           aParentID)
    DLog(@"aRecipientCount %ld",    (long)aRecipientCount)
    DLog(@"aCaptionText %@",        aCaptionText)
    DLog(@"aMediaPath %@",          aMediaPath)

    if (aParentID) {
        if (!aCaptionText)  aCaptionText    = @"";
        if (!aMediaPath)    aMediaPath      = @"";

        DLog(@"GROUP (BEFORE) %@", self.mGroupInfo)
        // Create a mutable dictionary with 2 keys/values
        NSMutableDictionary *parentInfo = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                           [NSNumber numberWithInteger:aRecipientCount],   kGroupRecipientCount,   // Recipient Count
                                           aCaptionText,                                   kGroupCaptionText,
                                           aMediaPath,                                     kGroupMediaPath,        // Media Path

                                           nil];
        [self.mGroupInfo setObject:parentInfo forKey:aParentID];
        DLog(@"GROUP (AFTER) %@", self.mGroupInfo)
    }

}

- (NSString *) createNewMediaFromPath: (NSString *) aOldPath {
    NSError *copyError  = nil;

    NSString *newPath   = [[DaemonPrivateHome daemonPrivateHome] stringByAppendingString:@"attachments/imSnapchat/"] ;
    newPath             = [SnapchatUtils getOutputPath:newPath extension:[aOldPath pathExtension]];

    BOOL success        = [[NSFileManager defaultManager] copyItemAtPath:aOldPath
                                                                  toPath:newPath
                                                                   error:&copyError];

    if (!success || copyError) {
        DLog(@"FAIL to  create new media file %@", newPath)
        newPath = nil;
    }

    return newPath;
}

- (NSString *) getMediaPathByChildConsistentID: (NSString *) aChildID {
    NSMutableDictionary *parentInfo = [self getParentInfoByChildConsistentID:aChildID];
    NSString *mediaPath             = nil;
    if (parentInfo) {
        mediaPath                   = [parentInfo objectForKey:kGroupMediaPath];
    }
    mediaPath                       = [self createNewMediaFromPath:mediaPath];
    return mediaPath;
}

- (NSString *) getCaptionTextByChildConsistentID: (NSString *) aChildID {
    NSMutableDictionary *parentInfo = [self getParentInfoByChildConsistentID:aChildID];
    NSString *captionText           = nil;
    if (parentInfo) {
        captionText                 = [parentInfo objectForKey:kGroupCaptionText];
    }
    return captionText;
}

- (BOOL) decrementRecipintCountForChildConsistentID: (NSString *) aChildID {
    DLog(@"GROUP (BEFORE) %@", self.mGroupInfo)
    BOOL canDecrement               = NO;
    // -- matched parent ID
    NSString *parentID              = [self getParentIDByChildConsistentID:aChildID];
    DLog(@"matched pareant id %@", parentID)

    NSMutableDictionary *parentInfo = nil;
    if  (parentID) {
        // -- get matched parent info
        parentInfo = [self.mGroupInfo objectForKey:parentID];
        DLog(@"parent info %@", parentInfo)

        if (parentInfo) {
            NSNumber *recipientCount    = [parentInfo objectForKey:kGroupRecipientCount];
            recipientCount              = [NSNumber numberWithInteger:[recipientCount integerValue] - 1];
            if ([recipientCount integerValue] == 0) {
                [self deleteParentForChildConsistentIDIfLastChild:aChildID];
            } else {
                // -- set the new recipient count back to the parent info
                [parentInfo setObject:recipientCount forKey:kGroupRecipientCount];

                // -- set the parent info back to group info
                [self.mGroupInfo setObject:parentInfo forKey:parentID];
            }
            canDecrement                = YES;
        }
    }
    DLog(@"GROUP (AFTER) %@", self.mGroupInfo)
    return canDecrement;
}

#pragma mark - Private methods

- (NSString *) getParentIDByChildConsistentID: (NSString *) aChildID {
    NSArray *allParentID = [self.mGroupInfo allKeys];    // NSArray of parent id NSString
    NSString *parentID   = nil;
    for (NSString *eachParentID in allParentID) {
        if ([aChildID rangeOfString:eachParentID].length != 0) {
            parentID     = eachParentID;
            break;
        }
    }
    return parentID;
}

- (NSMutableDictionary *) getParentInfoByChildConsistentID: (NSString *) aChildID {
    // -- get matched parent id
    NSString *parentID              = [self getParentIDByChildConsistentID:aChildID];
    NSMutableDictionary *parentInfo = nil;
    if  (parentID) {
        // -- get matched parent info
        parentInfo                  = [self.mGroupInfo objectForKey:parentID];
    }
    return parentInfo;
}

- (BOOL) deleteParentForChildConsistentIDIfLastChild: (NSString *) aChildID {
    BOOL isDeleted                      = NO;
    NSString *parentID                  = [self getParentIDByChildConsistentID:aChildID];
    if (parentID) {
        NSMutableDictionary *parentInfo = [self getParentInfoByChildConsistentID:aChildID];

        // -- check first if this child is the last child or not, if YES so delete this parent
        NSNumber *latestRecipientCount  = [parentInfo objectForKey:kGroupRecipientCount];

        // -- CASE 1: This child is the last one ( latestRecipientCount = 1)
        if ([latestRecipientCount integerValue] == 1) {
            DLog(@"remove parent info [%@]", parentID)
            NSString *mediaPath = [parentInfo objectForKey:kGroupMediaPath];
            if (mediaPath)
                [[NSFileManager defaultManager] removeItemAtPath:mediaPath error:NULL];
            [self.mGroupInfo removeObjectForKey:parentID];
            isDeleted                   =  YES;
        }
        // -- CASE 2: This child is NOT the last one ( latestRecipientCount = 2, 3, ...)
        else {
            DLog(@"This is not the last child, child count (include this child is %@)", latestRecipientCount)
        }
    }
    return isDeleted;
}

- (void)dealloc
{
    [super dealloc];

    [mGroupInfo release];

    mGroupInfo = nil;

}

@end

{'repo_name': 'Te-k/flexidie', 'stars': '808', 'repo_language': 'None', 'file_name': 'main.m', 'mime_type': 'text/x-objective-c', 'hash': 5334534971348350973, 'source_dataset': 'data'}


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace EventsAndXAML.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EventsAndXAML.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
    }
}

{'repo_name': 'MicrosoftLearning/20483-Programming-in-C-Sharp', 'stars': '218', 'repo_language': 'C#', 'file_name': '20483C_MOD04_LAB_MANUAL.md', 'mime_type': 'text/plain', 'hash': -3455820566455121803, 'source_dataset': 'data'}


// This file is part of the "IBController".
// Copyright (C) 2004 Steven M. Kearns (skearns23@yahoo.com )
// Copyright (C) 2004 - 2011 Richard L King (rlking@aultan.com)
// For conditions of distribution and use, see copyright notice in COPYING.txt

// IBController is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// IBController is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with IBController.  If not, see <http://www.gnu.org/licenses/>.

package ibcontroller;

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JFrame;

class GetMainWindowTask implements Callable<JFrame>{
    private volatile JFrame mMainWindow;
    private final Lock lock = new ReentrantLock();
    private final Condition gotFrame = lock.newCondition();

    @Override
    public JFrame call() throws InterruptedException {
        lock.lock();
        try {
            while (mMainWindow == null) {
                gotFrame.await();
            }
        } finally {
            lock.unlock();
        }
        return mMainWindow;
    }

    void setMainWindow(JFrame window) {
        lock.lock();
        try {
            mMainWindow = window;
            gotFrame.signal();
        } finally {
            lock.unlock();
        }
    }

}

{'repo_name': 'ib-controller/ib-controller', 'stars': '502', 'repo_language': 'Java', 'file_name': 'IBControllerService.exe.config', 'mime_type': 'text/xml', 'hash': -402334504920997324, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.
 */
package de.agilecoders.wicket.extensions.wizard;

import org.apache.wicket.extensions.wizard.IWizard;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

/**
 * @author rozkovec
 */
class BootstrapWizardStepHeader extends Panel
{

	/**
	 * Construct.
	 *
	 * @param id
	 * @param wizardStep
	 * @param wizard
	 */
	public BootstrapWizardStepHeader(final String id, BootstrapWizardStep wizardStep, final IWizard wizard)
	{
		super(id);
		setDefaultModel(new CompoundPropertyModel<>(wizard));
		add(new Label("title", wizardStep::getTitle));
		add(new Label("summary", wizardStep::getSummary));
	}
}

{'repo_name': 'l0rdn1kk0n/wicket-bootstrap', 'stars': '284', 'repo_language': 'CSS', 'file_name': 'OsgiClashingPackagesTest.java', 'mime_type': 'text/x-java', 'hash': 4353810033343765644, 'source_dataset': 'data'}


/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

module.exports = isArray;

{'repo_name': 'holzschu/a-shell', 'stars': '500', 'repo_language': 'Vim script', 'file_name': 'ft.vim', 'mime_type': 'text/plain', 'hash': -8592417356199856282, 'source_dataset': 'data'}


// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

// Preprocessed version of "boost/mpl/quote.hpp" header
// -- DO NOT modify by hand!

namespace boost { namespace mpl {

template< typename T, bool has_type_ >
struct quote_impl
    : T
{
};

template< typename T >
struct quote_impl< T,false >
{
    typedef T type;
};

template<
      template< typename P1 > class F
    , typename Tag = void_
    >
struct quote1
{
    template< typename U1 > struct apply

        : quote_impl<
              F<U1>
            , aux::has_type< F<U1> >::value
            >

    {
    };
};

template<
      template< typename P1, typename P2 > class F
    , typename Tag = void_
    >
struct quote2
{
    template< typename U1, typename U2 > struct apply

        : quote_impl<
              F< U1,U2 >
            , aux::has_type< F< U1,U2 > >::value
            >

    {
    };
};

template<
      template< typename P1, typename P2, typename P3 > class F
    , typename Tag = void_
    >
struct quote3
{
    template< typename U1, typename U2, typename U3 > struct apply

        : quote_impl<
              F< U1,U2,U3 >
            , aux::has_type< F< U1,U2,U3 > >::value
            >

    {
    };
};

template<
      template< typename P1, typename P2, typename P3, typename P4 > class F
    , typename Tag = void_
    >
struct quote4
{
    template<
          typename U1, typename U2, typename U3, typename U4
        >
    struct apply

        : quote_impl<
              F< U1,U2,U3,U4 >
            , aux::has_type< F< U1,U2,U3,U4 > >::value
            >

    {
    };
};

template<
      template<
          typename P1, typename P2, typename P3, typename P4
        , typename P5
        >
      class F
    , typename Tag = void_
    >
struct quote5
{
    template<
          typename U1, typename U2, typename U3, typename U4
        , typename U5
        >
    struct apply

        : quote_impl<
              F< U1,U2,U3,U4,U5 >
            , aux::has_type< F< U1,U2,U3,U4,U5 > >::value
            >

    {
    };
};

}}

{'repo_name': 'WCell/WCell', 'stars': '156', 'repo_language': 'C#', 'file_name': 'QueueTest.cs', 'mime_type': 'text/plain', 'hash': -8355792023195646029, 'source_dataset': 'data'}


#ifndef LEDEVICEATMO_H
#define LEDEVICEATMO_H

// hyperion includes
#include "ProviderRs232.h"

///
/// Implementation of the LedDevice interface for writing to serial device using tpm2 protocol.
///
class LedDeviceAtmo : public ProviderRs232
{
public:

	///
	/// @brief Constructs an Atmo LED-device
	///
	/// @param deviceConfig Device's configuration as JSON-Object
	///
	explicit LedDeviceAtmo(const QJsonObject &deviceConfig);

	///
	/// @brief Destructor of the LedDevice
	///
	static LedDevice* construct(const QJsonObject &deviceConfig);

private:

	///
	/// @brief Initialise the device's configuration
	///
	/// @param[in] deviceConfig the JSON device configuration
	/// @return True, if success
	bool init(const QJsonObject &deviceConfig) override;

	///
	/// @brief Writes the RGB-Color values to the LEDs.
	///
	/// @param[in] ledValues The RGB-color per LED
	/// @return Zero on success, else negative
	///
	int write(const std::vector<ColorRgb> &ledValues) override;
};

#endif // LEDEVICEATMO_H

{'repo_name': 'hyperion-project/hyperion.ng', 'stars': '328', 'repo_language': 'C++', 'file_name': 'preinst', 'mime_type': 'text/x-shellscript', 'hash': -2462085587058676288, 'source_dataset': 'data'}


/*
 * Copyright 2016 LinkedIn Corp.
 *
 * 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.
 */
package com.linkedin.gradle.python.util;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Default implementation of PackageSettings.
 *
 * Returns empty collections mostly.
 * Handles snapshots and project package rebuilds automatically.
 */
public class DefaultPackageSettings implements PackageSettings<PackageInfo> {
    private static final String PIP_EDITABLE = "--editable";
    private static final String PIP_IGNORE_INSTALLED = "--ignore-installed";

    private final File projectDir;

    public DefaultPackageSettings(File projectDir) {
        this.projectDir = projectDir;
    }

    @Override
    public Map<String, String> getEnvironment(PackageInfo packageInfo) {
        return Collections.emptyMap();
    }

    @Override
    public List<String> getGlobalOptions(PackageInfo packageInfo) {
        return Collections.emptyList();
    }

    @Override
    public List<String> getInstallOptions(PackageInfo packageInfo) {
        String version = packageInfo.getVersion();
        List<String> options = new ArrayList<>();

        // always reinstall snapshots
        if ((version != null && version.contains("-")) || requiresSourceBuild(packageInfo)) {
            options.add(PIP_IGNORE_INSTALLED);
        }

        /*
         * The current project is installed editable.
         * This option **must be last** because it expects the directory name after it.
         */
        if (isProjectDirectory(packageInfo)) {
            options.add(PIP_EDITABLE);
        }

        return options;
    }

    @Override
    public List<String> getBuildOptions(PackageInfo packageInfo) {
        return Collections.emptyList();
    }

    @Override
    public List<String> getConfigureOptions(PackageInfo packageInfo) {
        return Collections.emptyList();
    }

    @Override
    public List<String> getSupportedLanguageVersions(PackageInfo packageInfo) {
        return Collections.emptyList();
    }

    @Override
    public boolean requiresSourceBuild(PackageInfo packageInfo) {
        String version = packageInfo.getVersion();

        // always rebuild the project package itself
        if (isProjectDirectory(packageInfo)) {
            return true;
        }
        // always rebuild snapshots; otherwise no rebuild required, per semver versions with '-' are pre-release
        return (version != null && version.contains("-"));
    }

    @Override
    public boolean isCustomized(PackageInfo packageInfo) {
        // return false by default as no custom build options.
        return false;
    }

    private boolean isProjectDirectory(PackageInfo packageInfo) {
        File packageDir = packageInfo.getPackageFile();
        String version = packageInfo.getVersion();
        return version == null && Files.isDirectory(packageDir.toPath()) && projectDir.equals(packageDir);
    }
}

{'repo_name': 'linkedin/pygradle', 'stars': '503', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 276508868790051102, 'source_dataset': 'data'}


package io.apiman.gateway.engine;

import io.apiman.gateway.engine.async.IAsyncHandler;
import io.apiman.gateway.engine.impl.ApiRequestExecutorImpl;
import io.apiman.gateway.engine.io.ISignalWriteStream;

/**
 * IPolicyRequestExecutor interface.
 *
 * @author Marc Savy <msavy@redhat.com>
 *
 * @see ApiRequestExecutorImpl
 */
public interface IApiRequestExecutor {

    /**
     * Execute the policy chain and request.
     */
    void execute();

    /**
     * Policy request-response sequence has completed.
     *
     * @return true if finished, else false.
     */
    boolean isFinished();

    /**
     * Indicates when the back-end connector is ready to handle streamed data.
     *
     * @param handler
     */
    void streamHandler(IAsyncHandler<ISignalWriteStream> handler);

}

{'repo_name': 'apiman/apiman', 'stars': '555', 'repo_language': 'Java', 'file_name': 'pom.xml', 'mime_type': 'text/plain', 'hash': 7614959602796430282, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<g:element xmlns:g="http://www.esri.com/geoportal/gxe"
           xmlns:h="http://www.esri.com/geoportal/gxe/html"
           g:label="$i18n.catalog.iso19139.DQ_ThematicClassificationCorrectness"
           g:extends="$base/schema/gmd/dataQuality/AbstractDQ_ThematicAccuracy_Type.xml">
</g:element>

{'repo_name': 'Esri/geoportal-server', 'stars': '199', 'repo_language': 'C#', 'file_name': 'scale.fix.js', 'mime_type': 'text/plain', 'hash': 7508044006505995400, 'source_dataset': 'data'}


#include "DetectorDescription/Core/interface/DDAlgorithm.h"
#include "DetectorDescription/Core/interface/DDAlgorithmFactory.h"
#include "DetectorDescription/Core/interface/DDCompactView.h"
#include "DetectorDescription/Core/interface/DDCurrentNamespace.h"
#include "DetectorDescription/Core/interface/DDLogicalPart.h"
#include "DetectorDescription/Core/interface/DDName.h"
#include "DetectorDescription/Core/interface/DDSplit.h"
#include "DetectorDescription/Core/interface/DDTransform.h"
#include "DetectorDescription/Core/interface/DDRotationMatrix.h"
#include "DetectorDescription/Core/interface/DDTranslation.h"
#include "DetectorDescription/Core/interface/DDTypes.h"
#include "DataFormats/Math/interface/GeantUnits.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/PluginManager/interface/PluginFactory.h"

#include <cmath>
#include <memory>

using namespace geant_units::operators;

class DDAngular : public DDAlgorithm {
public:
  DDAngular()
      : m_n(1), m_startCopyNo(1), m_incrCopyNo(1), m_startAngle(0.), m_rangeAngle(360._deg), m_radius(0.), m_delta(0.) {}

  void initialize(const DDNumericArguments& nArgs,
                  const DDVectorArguments& vArgs,
                  const DDMapArguments& mArgs,
                  const DDStringArguments& sArgs,
                  const DDStringVectorArguments& vsArgs) override;

  void execute(DDCompactView& cpv) override;

private:
  DD3Vector fUnitVector(double theta, double phi);
  int m_n;                            //Number of copies
  int m_startCopyNo;                  //Start Copy number
  int m_incrCopyNo;                   //Increment in Copy number
  double m_startAngle;                //Start angle
  double m_rangeAngle;                //Range in angle
  double m_radius;                    //Radius
  double m_delta;                     //Increment in phi
  std::vector<double> m_center;       //Phi values
  std::vector<double> m_rotateSolid;  //Rotation of the solid values

  std::string m_idNameSpace;                        //Namespace of this and ALL sub-parts
  std::pair<std::string, std::string> m_childNmNs;  //Child name
                                                    //Namespace of the child

  DDRotationMatrix m_solidRot;  //Rotation of the solid
};

void DDAngular::initialize(const DDNumericArguments& nArgs,
                           const DDVectorArguments& vArgs,
                           const DDMapArguments&,
                           const DDStringArguments& sArgs,
                           const DDStringVectorArguments&) {
  m_n = int(nArgs["N"]);
  m_startCopyNo = int(nArgs["StartCopyNo"]);
  m_incrCopyNo = int(nArgs["IncrCopyNo"]);
  m_rangeAngle = nArgs["RangeAngle"];
  m_startAngle = nArgs["StartAngle"];
  m_radius = nArgs["Radius"];
  m_center = vArgs["Center"];
  m_rotateSolid = vArgs["RotateSolid"];

  m_solidRot = DDRotationMatrix();

  if (std::abs(m_rangeAngle - 360.0_deg) < 0.001_deg) {
    m_delta = m_rangeAngle / double(m_n);
  } else {
    if (m_n > 1) {
      m_delta = m_rangeAngle / double(m_n - 1);
    } else {
      m_delta = 0.;
    }
  }

  LogDebug("DDAlgorithm") << "DDAngular: Parameters for position"
                          << "ing:: n " << m_n << " Start, Range, Delta " << convertRadToDeg(m_startAngle) << " "
                          << convertRadToDeg(m_rangeAngle) << " " << convertRadToDeg(m_delta) << " Radius " << m_radius
                          << " Centre " << m_center[0] << ", " << m_center[1] << ", " << m_center[2];

  //======= collect data concerning the rotation of the solid
  using sz_type = std::map<std::string, std::vector<double> >::mapped_type::size_type;
  sz_type sz = m_rotateSolid.size();
  if (sz % 3) {
    LogDebug("DDAlgorithm") << "\trotateSolid must occur 3*n times (defining n subsequent rotations)\n"
                            << "\t  currently it appears " << sz << " times!\n";
  }
  for (sz_type i = 0; i < sz; i += 3) {
    if ((m_rotateSolid[i] > 180._deg) || (m_rotateSolid[i] < 0._deg)) {
      LogDebug("DDAlgorithm") << "\trotateSolid \'theta\' must be in range [0,180*deg]\n"
                              << "\t  currently it is " << convertRadToDeg(m_rotateSolid[i]) << "*deg in rotateSolid["
                              << double(i) << "]!\n";
    }
    DDAxisAngle temp(fUnitVector(m_rotateSolid[i], m_rotateSolid[i + 1]), m_rotateSolid[i + 2]);
    LogDebug("DDAlgorithm") << "  rotsolid[" << i << "] axis=" << temp.Axis()
                            << " rot.angle=" << convertRadToDeg(temp.Angle());
    m_solidRot = temp * m_solidRot;
  }

  m_idNameSpace = DDCurrentNamespace::ns();
  m_childNmNs = DDSplit(sArgs["ChildName"]);
  if (m_childNmNs.second.empty())
    m_childNmNs.second = DDCurrentNamespace::ns();

  DDName parentName = parent().name();
  LogDebug("DDAlgorithm") << "DDAngular: Parent " << parentName << "\tChild " << m_childNmNs.first << "\tNameSpace "
                          << m_childNmNs.second;
}

void DDAngular::execute(DDCompactView& cpv) {
  DDName mother = parent().name();
  DDName ddname(m_childNmNs.first, m_childNmNs.second);
  double theta = 90._deg;
  int copy = m_startCopyNo;
  double phi = m_startAngle;

  for (int i = 0; i < m_n; ++i) {
    double phix = phi;
    double phiy = phix + 90._deg;
    double phideg = convertRadToDeg(phix);

    std::string rotstr = m_childNmNs.first + "_" + std::to_string(phideg * 10.);
    DDRotation rotation = DDRotation(DDName(rotstr, m_idNameSpace));
    if (!rotation) {
      LogDebug("DDAlgorithm") << "DDAngular: Creating a new "
                              << "rotation: " << rotstr << "\t90., " << convertRadToDeg(phix) << ", 90.,"
                              << convertRadToDeg(phiy) << ", 0, 0";

      rotation = DDrot(
          DDName(rotstr, m_idNameSpace),
          std::make_unique<DDRotationMatrix>(*DDcreateRotationMatrix(theta, phix, theta, phiy, 0., 0.) * m_solidRot));
    }

    double xpos = m_radius * cos(phi) + m_center[0];
    double ypos = m_radius * sin(phi) + m_center[1];
    double zpos = m_center[2];
    DDTranslation tran(xpos, ypos, zpos);

    cpv.position(ddname, mother, copy, tran, rotation);
    LogDebug("DDAlgorithm") << "DDAngular: child " << m_childNmNs.second << ":" << m_childNmNs.first << " number "
                            << copy << " positioned in " << mother << " at " << tran << " with " << rotation << "\n";
    copy += m_incrCopyNo;
    phi += m_delta;
  }
}

DD3Vector DDAngular::fUnitVector(double theta, double phi) {
  return DD3Vector(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta));
}

DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDAngular, "global:DDAngular");

{'repo_name': 'cms-sw/cmssw', 'stars': '741', 'repo_language': 'C++', 'file_name': 'HcalRecHitsValidation.cc', 'mime_type': 'text/x-c', 'hash': 968283913844286153, 'source_dataset': 'data'}


// Copyright 2009 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#pragma once

namespace Common::Log
{
enum LOG_TYPE
{
  ACTIONREPLAY,
  AUDIO,
  AUDIO_INTERFACE,
  BOOT,
  COMMANDPROCESSOR,
  COMMON,
  CONSOLE,
  CORE,
  DISCIO,
  DSPHLE,
  DSPLLE,
  DSP_MAIL,
  DSPINTERFACE,
  DVDINTERFACE,
  DYNA_REC,
  EXPANSIONINTERFACE,
  FILEMON,
  GDB_STUB,
  GPFIFO,
  HOST_GPU,
  IOS,
  IOS_DI,
  IOS_ES,
  IOS_FS,
  IOS_NET,
  IOS_SD,
  IOS_SSL,
  IOS_STM,
  IOS_USB,
  IOS_WC24,
  IOS_WFS,
  IOS_WIIMOTE,
  MASTER_LOG,
  MEMMAP,
  MEMCARD_MANAGER,
  NETPLAY,
  OSHLE,
  OSREPORT,
  PAD,
  PIXELENGINE,
  PROCESSORINTERFACE,
  POWERPC,
  SERIALINTERFACE,
  SP1,
  SYMBOLS,
  VIDEO,
  VIDEOINTERFACE,
  WII_IPC,
  WIIMOTE,

  NUMBER_OF_LOGS  // Must be last
};

enum LOG_LEVELS
{
  LNOTICE = 1,   // VERY important information that is NOT errors. Like startup and OSReports.
  LERROR = 2,    // Critical errors
  LWARNING = 3,  // Something is suspicious.
  LINFO = 4,     // General information.
  LDEBUG = 5,    // Detailed debugging - might make things slow.
};

static const char LOG_LEVEL_TO_CHAR[7] = "-NEWID";

void GenericLog(Common::Log::LOG_LEVELS level, Common::Log::LOG_TYPE type, const char* file,
                int line, const char* fmt, ...)
#ifdef __GNUC__
    __attribute__((format(printf, 5, 6)))
#endif
    ;
}  // namespace Common::Log

#if defined(_DEBUG) || defined(DEBUGFAST)
#define MAX_LOGLEVEL Common::Log::LOG_LEVELS::LDEBUG
#else
#ifndef MAX_LOGLEVEL
#define MAX_LOGLEVEL Common::Log::LOG_LEVELS::LINFO
#endif  // loglevel
#endif  // logging

// Let the compiler optimize this out
#define GENERIC_LOG(t, v, ...)                                                                     \
  do                                                                                \
  {                                                                                \
    if (v <= MAX_LOGLEVEL)                                                                         \
      Common::Log::GenericLog(v, t, __FILE__, __LINE__, __VA_ARGS__);                              \
  } while (0)

#define ERROR_LOG(t, ...)                                                                          \
  do                                                                                \
  {                                                                                \
    GENERIC_LOG(Common::Log::t, Common::Log::LERROR, __VA_ARGS__);                                 \
  } while (0)
#define WARN_LOG(t, ...)                                                                           \
  do                                                                                \
  {                                                                                \
    GENERIC_LOG(Common::Log::t, Common::Log::LWARNING, __VA_ARGS__);                               \
  } while (0)
#define NOTICE_LOG(t, ...)                                                                         \
  do                                                                                \
  {                                                                                \
    GENERIC_LOG(Common::Log::t, Common::Log::LNOTICE, __VA_ARGS__);                                \
  } while (0)
#define INFO_LOG(t, ...)                                                                           \
  do                                                                                \
  {                                                                                \
    GENERIC_LOG(Common::Log::t, Common::Log::LINFO, __VA_ARGS__);                                  \
  } while (0)
#define DEBUG_LOG(t, ...)                                                                          \
  do                                                                                \
  {                                                                                \
    GENERIC_LOG(Common::Log::t, Common::Log::LDEBUG, __VA_ARGS__);                                 \
  } while (0)

{'repo_name': 'dolphin-emu/dolphin', 'stars': '6466', 'repo_language': 'C++', 'file_name': 'config', 'mime_type': 'text/plain', 'hash': -7695149929867653005, 'source_dataset': 'data'}


// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not %target-swift-frontend %s -typecheck
protocol f {
    k g d {
    k d
    k k
}
j j<l : d> : d {
    k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f

{'repo_name': 'apple/swift', 'stars': '52460', 'repo_language': 'C++', 'file_name': 'comment-xml-schema.rng', 'mime_type': 'text/xml', 'hash': 7758792495498563719, 'source_dataset': 'data'}