Example #1
0
void VoteView::on_pushButtonCreateRevealVote_clicked()
{
    extern json_spirit::Value createrevealvote(const json_spirit::Array &revealVoteParams, bool fHelp);

    // Grab the branch if it exists
    std::string branchID = "0f894a25c5e0318ee148fe54600ebbf50782f0a1df1eb2aab06321a8ccec270d";
    uint256 uBranch;
    uBranch.SetHex(branchID);
    marketBranch *branch = pmarkettree->GetBranch(uBranch);
    if (!branch) {
        emit displayMessage("Error creating Revealed Vote", "Invalid Branch ID, branch does not exist!");
        return;
    }

    // Get the voter's address
    CHivemindAddress voterAddress;
    voterAddress.is_votecoin = 1;
    voterAddress.SetString(ui->lineEditVotecoinAddress->text().toStdString());

    if (!voterAddress.IsValid()) {
        emit displayMessage("Error creating Reveald Vote", "Invalid Votecoin address!");
        return;
    }

    // Try to get the sealed vote
    uint256 uVote;
    uVote.SetHex(ui->lineEditSealedVoteID->text().toStdString());

    marketSealedVote *sealedVote = pmarkettree->GetSealedVote(uVote);
    if (!sealedVote) {
        emit displayMessage("Error creating Revealed Vote", "Vote does not exist!");
        return;
    }

    // Create spirit array of sealed vote params
    json_spirit::Array revealVoteParams;
    revealVoteParams.push_back(voterAddress.ToString());
    revealVoteParams.push_back(branch->GetHash().GetHex());
    int height = sealedVote->height;
    revealVoteParams.push_back(height);
    revealVoteParams.push_back(sealedVote->GetHash().GetHex());
    revealVoteParams.push_back(2016);
    QString decisionVote = ui->lineEditDecisionID->text();
    decisionVote.append(",");
    decisionVote.append(ui->comboBoxVote->currentIndex());
    revealVoteParams.push_back(decisionVote.toStdString());

    // Try to create the revealvote
    json_spirit::Value revealVoteResult;
    try {
        revealVoteResult = createrevealvote(revealVoteParams, false);
    } catch (const std::runtime_error &error) {
        QString errorText = QString::fromStdString(error.what());
        emit displayMessage("Error creating Revealed Vote", errorText);
        return;
    } catch (const std::exception &exception) {
        QString exceptionText = QString::fromStdString(exception.what());
        emit displayMessage("Error creating Revealed Vote", exceptionText);
        return;
    } catch (const json_spirit::Object &object) {
        revealVoteResult = object;
    }

    // Check the reveal vote result
    try {
        // Get reveal vote result pairs
        json_spirit::Object revealVoteResultObject = revealVoteResult.get_obj();
        json_spirit::Pair codePair = revealVoteResultObject[0];
        json_spirit::Pair messagePair = revealVoteResultObject[1];

        // If error, get error code and message
        if (codePair.name_ == "code") {
            int code = codePair.value_.get_int();
            if (code < 0) {
                QString errorText = QString::fromStdString(messagePair.value_.get_str());
                emit displayMessage("Error creating Revealed Vote", errorText);
                return;

            }
        }

        // If the reveal vote was created, display the txid and vote id
        QString resultMessage;
        resultMessage.append("Revealed vote has been submitted!\n");
        resultMessage.append(QString::fromStdString(codePair.name_));
        resultMessage.append(":\n");
        resultMessage.append(QString::fromStdString(codePair.value_.get_str()));
        resultMessage.append("\n\n");
        resultMessage.append(QString::fromStdString(messagePair.name_));
        resultMessage.append(":\n");
        resultMessage.append(QString::fromStdString(messagePair.value_.get_str()));
        emit displayMessage("Revealed Vote Submitted!", resultMessage);

    } catch (const std::runtime_error &error) {
        emit displayMessage("Error creating Revealed Vote!", QString::fromStdString(error.what()));

    } catch (const std::exception &exception) {
        emit displayMessage("Error creating Revealed Vote!", QString::fromStdString(exception.what()));
    }
}
QVector3D RobotVisualization::getTranslation(QString source_frame, QString target_frame){
    osg::Matrixd tr = getRelativeTransform(target_frame.toStdString(), source_frame.toStdString());
    osg::Vec3d t = tr.getTrans();
    return QVector3D(t.x(),t.y(),t.z());
}
void RobotVisualization::showSegmentText(QString link_name, QString text){
    OSGSegment* seg = getSegment(link_name.toStdString());
    seg->attachTextLabel(text.toStdString());
}
Example #4
0
	/*!
	Initializes the new camera information.
	\param sceneMgr     Camera's SceneManager
	\param name         Camera's name
	\param pos          Camera's position
	\param target       Camera's target
	*/
	void Camera::init( Ogre::SceneManager *sceneMgr,
					   const QString& name,
					   QVector3D &pos,
					   QVector3D &target)
	{
		_cameraNode	= NULL;
		_targetNode	= NULL;
		_camera		= NULL;

		// Basic member references setup
		//_name = name;

		if(sceneMgr->hasSceneNode(name.toStdString()))
		{
			_cameraNode = sceneMgr->getSceneNode( name.toStdString() );
			_camera = sceneMgr->getCamera( name.toStdString() );
			if(sceneMgr->hasSceneNode(name.toStdString() + ".Target"))
			{
				_targetNode = sceneMgr->getSceneNode( name.toStdString() + ".Target" );
			}
			else
			{
				_targetNode = sceneMgr->getRootSceneNode()->createChildSceneNode( name.toStdString() + ".Target" );
			}
		}
		else
		{
			//create camera
			_camera = sceneMgr->createCamera( name.toStdString() );

			//default camera
			_camera->setNearClipDistance( 5.0f );
			_camera->setPosition( 0, 0, 0 );	// Camera position is set by node
			_camera->lookAt( 0, 0, 0 );			// Target position is set by node
			_camera->setFarClipDistance( 1500.0f );

			// Create the camera's node
			_cameraNode = sceneMgr->getRootSceneNode()->createChildSceneNode( name.toStdString() );
			_cameraNode->attachObject( _camera );
			_cameraNode->setPosition(UtilFunctions::qVector3dToOgreVector3(pos));
			// Create the camera's target node
			_targetNode = sceneMgr->getRootSceneNode()->createChildSceneNode( name.toStdString() + ".Target" );
			_targetNode->setPosition(UtilFunctions::qVector3dToOgreVector3(target));
		}

		_cameraNode->setAutoTracking( true, _targetNode ); // The camera will always look at the camera target
		_cameraNode->setFixedYawAxis( true );		// Needed because of auto tracking

		_defaultPosition = UtilFunctions::ogreVector3ToQVector3d(_cameraNode->getPosition());
		_position = _defaultPosition;
		_defaultTargetPosition = UtilFunctions::ogreVector3ToQVector3d(_targetNode->getPosition());
		_targetPosition = _defaultTargetPosition;

		// movement
		_animation = new QPropertyAnimation(this, "position");
		_targetAnimation = new QPropertyAnimation(this, "targetPosition");
		connect(_animation, SIGNAL(finished()), this, SLOT(stopMovingTasks()));

		// Zoom
		_hasZoomApplied = false;
		_zoomOffTimerId = 0;
		_zoomTime       = 0;
	}
Example #5
0
void HelpMessageBox::printToConsole()
{
    // On other operating systems, the expected action is to print the message to the console.
    QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
    fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void MainWindow::on_object_id_textChanged(const QString &arg1)
{
    // show all faces allready taged with the id of the object_id field
    QString id = ui->object_id->text();

    std::vector<QPixmap> listCrops;

    QString dir_name = Manager::exemplar()->selectedDirectory;//"/home/daniel/BaoDataBase/myDataBase";
    // collect all FaceObjects and imagees with the given id
    DIR *dir;
    struct dirent *ent;
    struct stat info;
    const char *c_str2 = dir_name.toLocal8Bit().data();
    if ((dir = opendir (c_str2)) != NULL) {
      /* print all the files and directories within directory */
      while ((ent = readdir (dir)) != NULL) {
          stat(ent->d_name, &info);
          //if(!S_ISDIR (info.st_mode)) {
            //qDebug() << ent->d_name;
            std::vector<FaceObject> list = readObjectFile(dir_name.toStdString() + "/.metaface/" + ent->d_name + ".txt");
            if(list.size() > 0) {
                for(std::vector<FaceObject>::iterator it = list.begin(); it != list.end(); ++it) {
                    FaceObject fo = *it;
                    if(fo.objectID == id.toStdString()) {
                        qDebug() << "found a face in:" << ent->d_name;
                        QPixmap * img = new QPixmap();
                        QString fileName = QString::fromStdString(ent->d_name);
                        img->load(dir_name + "/" + fileName);
                        //QPixmap::copy(int x, int y, int width, int height )
                        QPixmap imgCroped = img->copy(fo.x, fo.y, fo.width, fo.height);
                        qDebug() << "image crop x:" << fo.x << "y:" << fo.y << "width" << fo.width << "height:" << fo.height;
                        listCrops.push_back(imgCroped);
                    }

                }
            }
      }
      closedir (dir);
    }

    // check how many croped faces are stored in the list
    qDebug() << "there are " << listCrops.size() << " store in the vector";



    //QString imgPath = "/home/daniel/facetag/datasettools2/datasettools80.png";
    //QImage *img = new QImage();
    //bool loaded = img->load(imgPath);
    //if (loaded)
    //{
        /*QTableWidgetItem *thumbnail = new QTableWidgetItem;
        thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));

        //thumbnailsWidget->setColumnCount(3);
        //thumbnailsWidget->setRowCount(3);
        ui->tableIamges->setItem(0, 0, thumbnail);*/

        //w.setCentralWidget(thumbnailsWidget);
    //} else {
        //qDebug()<<"Image "<<imgPath<<" was not opened!";
   // }
        int row = 0;
        int column = 0;
        int cell = 0;
        for(std::vector<QPixmap>::iterator it = listCrops.begin(); it != listCrops.end(); ++it) {
            QPixmap pm = *it;
            pm = pm.scaledToHeight(80,Qt::SmoothTransformation);
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            thumbnail->setData(Qt::DecorationRole, pm);
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }

        int maxCells = ui->tableIamges->rowCount() * ui->tableIamges->columnCount();
        while(cell < 9) {
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }
}
Example #7
0
Void ModulesHandle::applyAllModuleIf( PlaYUVerAppModuleIf *pcCurrModuleIf )
{
    if( pcCurrModuleIf )
    {
        if( !pcCurrModuleIf->m_pcModuleStream )
        {
            UInt Width = 0, Height = 0, FrameRate = 30;
            Int BitsPixel, InputFormat = -1;

            QString supported = tr( "Supported Files (" );
            QStringList formatsList;

            std::vector<PlaYUVerSupportedFormat> supportedFmts = PlaYUVerStream::supportedWriteFormats();
            for( UInt i = 0; i < supportedFmts.size(); i++ )
            {
                QString currFmt;
                supported.append( " *." );
                supported.append( QString::fromStdString( supportedFmts[i].formatExt ) );
                currFmt.append( QString::fromStdString( supportedFmts[i].formatName ) );
                currFmt.append( " (*." );
                currFmt.append( QString::fromStdString( supportedFmts[i].formatExt ) );
                currFmt.append( ")" );
                formatsList << currFmt;
            }
            supported.append( " )" );

            QStringList filter;
            filter << supported
                   << formatsList
                   << tr( "All Files (*)" );

            QString fileName = QFileDialog::getSaveFileName( m_pcParent, tr( "Open File" ), QString(), filter.join( ";;" ) );

            Width = pcCurrModuleIf->m_pcProcessedFrame->getWidth();
            Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight();
            InputFormat = pcCurrModuleIf->m_pcProcessedFrame->getPelFormat();
            BitsPixel = pcCurrModuleIf->m_pcProcessedFrame->getBitsPel();
            FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate();

            pcCurrModuleIf->m_pcModuleStream = new PlaYUVerStream;
            if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel, PLAYUVER_LITTLE_ENDIAN, FrameRate, false ) )
            {
                delete pcCurrModuleIf->m_pcModuleStream;
                pcCurrModuleIf->m_pcModuleStream = NULL;
                return;
            }
        }
    }
    if( pcCurrModuleIf->m_pcModuleStream )
    {
        UInt numberOfWindows = pcCurrModuleIf->m_pcModule->m_uiNumberOfFrames;
        UInt64 currFrames = 0;
        UInt64 numberOfFrames = INT_MAX;
        for( UInt i = 0; i < numberOfWindows; i++ )
        {
            currFrames = pcCurrModuleIf->m_pcSubWindow[i]->getInputStream()->getFrameNum();
            if( currFrames < numberOfFrames )
                numberOfFrames = currFrames;
            pcCurrModuleIf->m_pcSubWindow[i]->stop();
        }
        QApplication::setOverrideCursor( Qt::WaitCursor );
        for( UInt f = 1; f < numberOfFrames; f++ )
        {
            pcCurrModuleIf->apply( false, true );
            QCoreApplication::processEvents();
            pcCurrModuleIf->m_pcModuleStream->writeFrame( pcCurrModuleIf->m_pcProcessedFrame );
            for( UInt i = 0; i < numberOfWindows; i++ )
            {
                pcCurrModuleIf->m_pcSubWindow[i]->play();
                pcCurrModuleIf->m_pcSubWindow[i]->playEvent();
            }
        }
        for( UInt i = 0; i < numberOfWindows; i++ )
        {
            pcCurrModuleIf->m_pcSubWindow[i]->stop();
        }
        QApplication::restoreOverrideCursor();
    }
}
//****************************************************************************
// Save Segmentation Model
//****************************************************************************
void PatternAnalysisWizard::saveModel(void)
{
    //Selected Features
	std::vector<int> columnsToUse;
	QList<QAbstractButton *> buttons = featureGroup->buttons();
	for(int b = 0; b<buttons.size(); ++b)
    //for(int b = 0; b<10; ++b)
	{
		//buttons.at(b)->setCheckable(false);
		if( buttons.at(b)->isChecked() )
		{
			if(featureGroup->id(buttons.at(b)) != 0)
			{
				columnsToUse.push_back( featureGroup->id(buttons.at(b)) );
			}
			else
			{
				for(int col=0; col<(int)m_table->GetNumberOfColumns(); ++col)
				{
					std::string col_name = m_table->GetColumnName(col);
					if(col_name.find("Zern")!=std::string::npos)
					{
						columnsToUse.push_back(col);
					}
				}
			}
		}
	}	
	if(columnsToUse.size() <= 0)
		return;


	//Save Dialog
	QString filename = QFileDialog::getSaveFileName(this, tr("Save Training Model As..."),lastPath, tr("TEXT(*.txt)"));
	if(filename == "")
		return;
	lastPath = QFileInfo(filename).absolutePath();
	
	//Load the model into a new table 
    vtkSmartPointer<vtkTable> new_table = vtkSmartPointer<vtkTable>::New();
	new_table->Initialize();
   
	for(int c=0; c<(int)columnsToUse.size(); ++c)
	{
	    vtkSmartPointer<vtkDoubleArray> column = vtkSmartPointer<vtkDoubleArray>::New();
		column->SetName( m_table->GetColumnName(columnsToUse.at(c)) );
		new_table->AddColumn(column);
	}
	vtkSmartPointer<vtkDoubleArray> column1 = vtkSmartPointer<vtkDoubleArray>::New();
	column1->SetName( "Class" );
	new_table->AddColumn(column1);
	vtkSmartPointer<vtkDoubleArray> column2 = vtkSmartPointer<vtkDoubleArray>::New();
	column2->SetName( "ID" );
	new_table->AddColumn(column2);
   	for(int row = 0; row < (int)m_table->GetNumberOfRows(); ++row)
	{		
		vtkSmartPointer<vtkVariantArray> model_data1 = vtkSmartPointer<vtkVariantArray>::New();
		for(int c =0;c<(int)columnsToUse.size();++c)
			model_data1->InsertNextValue(m_table->GetValue(row,columnsToUse.at(c)));
		for(int col=((int)m_table->GetNumberOfColumns())-1; col>=0; --col)
		{	
			std::string current_column = m_table->GetColumnName(col);
			if(current_column.find("prediction") != std::string::npos )
			{
				model_data1->InsertNextValue(m_table->GetValue(row, col));
				break;
			}	
		}
		model_data1->InsertNextValue(m_table->GetValueByName(row, "ID"));
		new_table->InsertNextRow(model_data1);
	}
	//*********************************************************************
	//Save Model
	std::string Filename = filename.toStdString();
	
	//This function writes the features to a text file
	ofstream outFile; 
	outFile.open(Filename.c_str(), ios::out | ios::trunc );
	if ( !outFile.is_open() )
	{
		std::cerr << "Failed to Load Document: " << outFile << std::endl;
		return;
	}
	//Write the headers:
	for(int c=0; c<new_table->GetNumberOfColumns(); ++c)
	{
		outFile << new_table->GetColumnName(c) << "\t";
	}
	outFile << "\n";
	//Write out the features:
	std::string current_column;
	for(int row = 0; row < new_table->GetNumberOfRows(); ++row)
	{
		for(int c=0; c < new_table->GetNumberOfColumns(); ++c)
		{
			std::stringstream out;
			current_column = new_table->GetColumnName(c);
			if((current_column.compare("ID") == 0) || (current_column.compare("Class") == 0))
				out << std::fixed << new_table->GetValue(row,c).ToInt();
			else
	            out << std::setprecision(3) << std::fixed << new_table->GetValue(row,c).ToFloat();
	        outFile << out.str() << "\t";
		}
		outFile << "\n";
	}
	outFile.close();
    //******************************************************************************************
}
Example #9
0
void Etalonnage::run()
{
    ofstream fichier("/home/ludovic/Bureau/test.txt", ios::out | ios::trunc);
    QMessageBox box;
    bool stab;
    cout<<"dans les consignes"<<endl;
    for (int i=0; i<tabTemp.size();i++)//les consignes rentrées par l'opérateur
    {
        cout <<"TabTEMP :"<<tabTemp.size()<<endl;
        QString str;
        str.setNum(tabTemp.at(i));
        cout<<"CONSIGNE : "<<str.toStdString()<<endl;
        fr->definirTemp(str);//définie la temperature

        emit emSigCons(str.setNum(tabTemp.at(i)));
        float tmpTempo=sdInt->acquerirTemp().toFloat();

        //tant que temperature est suprérieur a la consigne +0,5° ou inférieur à la consigne -0.5°
        while(true)
        {
            if ((tmpTempo<(tabTemp.at(i)+0.5)) && (tmpTempo>(tabTemp.at(i)-0.5)) )
            {
//                QMessageBox box;
//                box.setText("CONSIGNE ATTEINTE ");
//                box.exec();
                break;

            }
            else
            {
                sleep(1);
                tmpTempo=sdInt->acquerirTemp().toFloat();
                cout<<"dans le while"<<endl;
            }
        }

        float tempIntTempo=sdInt->acquerirTemp().toFloat();
        float tempRefTempo=sdRef->acquerirTemp().toFloat();
        float newcons=tabTemp.at(i)+tempIntTempo-tempRefTempo;// calculer la nouvelle consigne
        fr->definirTemp(str.setNum(newcons));//définie la temperature
        cout<<"nouvelle consigne :"<<newcons<<endl;

        emit emSigCons(str.setNum(newcons));
        cout<<"temperatur envoyée :"<<str.toStdString()<<endl;
        stab = false;
        while(stab==false)
        {
            for(int j=0; j<5; j++)//récupére 1 valeur tout les 3 sec jusqu'a 240 valeurs
            {
                tabTempRecup.push_back(sdRef->acquerirTemp().toFloat());//récupére la temperature externe et la stock
                sleep(1);
                cout<<"DANS CONSIGNE : "<<sdRef->acquerirTemp().toFloat()<<endl;
            }
            stab = testStabilite(tabTempRecup, stabilite);
        }

        if((checkBox=="1")&&(idcam!=0))
        {
            cout<<"CHEESE"<<endl;
            emit emSigPrendPhoto();
            fichier<<"Reference : "<<endl;
            fichier<<i+1<<" : ";
            fichier<<sdRef->acquerirTemp().toFloat()<<endl;
        }
        else
        {
            cout<<"ON STOCK DANS LE FICHIER "<<endl;
            fichier<<"Reference : "<<endl;
            fichier<<i+1<<" : ";
            fichier<<sdRef->acquerirTemp().toFloat()<<endl;

            fichier<<"Interne : "<<endl;
            fichier<<i+1<<" : ";
            fichier<<sdInt->acquerirTemp().toFloat()<<endl;

            fichier.close();
        }
    }
}
Example #10
0
bool WalletModel::validateAddress(const QString &address)
{
    CBitcoinAddress addressParsed(address.toStdString());
    return addressParsed.IsValid();
}
//****************************************************************************
// Append Segmentation Model
//****************************************************************************
void PatternAnalysisWizard::appendModel(vtkSmartPointer<vtkTable> mod_table, QString filename)
{
	int r = mod_table->GetValue((int)mod_table->GetNumberOfRows()-1, (int)mod_table->GetNumberOfColumns()-1).ToInt();
   	for(int row = 0; row < (int)m_table->GetNumberOfRows(); ++row)
	{		
		vtkSmartPointer<vtkVariantArray> model_data1 = vtkSmartPointer<vtkVariantArray>::New();
		for(int c = 0;c<(int)mod_table->GetNumberOfColumns();++c)
		{
			 std::string mod_column = mod_table->GetColumnName(c);
			 if(mod_column.compare("Class") == 0)
			 {
				 for(int col=((int)m_table->GetNumberOfColumns())-1; col>=0; --col)
				{	
					std::string current_column = m_table->GetColumnName(col);
					if(current_column.find("prediction") != std::string::npos )
					{
						model_data1->InsertNextValue(m_table->GetValue(row, col));
						break;
					}	
				}
			 }

			 else
			 {
		        for(int d=0; d<(int)m_table->GetNumberOfColumns(); ++d)
		        {
			         std::string m_column = m_table->GetColumnName(d);
			         if( m_column.compare(mod_column) == 0)
				     {
					     if(mod_column.compare("ID") == 0)
						 {
							 int id = r + m_table->GetValue(row,d).ToInt();
							 model_data1->InsertNextValue(vtkVariant(id));
						 }
						 else
							 model_data1->InsertNextValue(m_table->GetValue(row,d));
				         break;
				     }
		         }
			 }
		}
		mod_table->InsertNextRow(model_data1);
	}
	//*********************************************************************
	//Save Model
	std::string Filename = filename.toStdString();
	
	//This function writes the features to a text file
	ofstream outFile; 
	outFile.open(Filename.c_str(), ios::out | ios::trunc );
	if ( !outFile.is_open() )
	{
		std::cerr << "Failed to Load Document: " << outFile << std::endl;
		return;
	}
	//Write the headers:
	for(int c=0; c<mod_table->GetNumberOfColumns(); ++c)
	{
		outFile << mod_table->GetColumnName(c) << "\t";
	}
	outFile << "\n";
	//Write out the features:
	std::string current_column;
	for(int row = 0; row < mod_table->GetNumberOfRows(); ++row)
	{
		for(int c=0; c < mod_table->GetNumberOfColumns(); ++c)
		{
			std::stringstream out;
			current_column = mod_table->GetColumnName(c);
			if((current_column.compare("ID") == 0) || (current_column.compare("Class") == 0))
				out << std::fixed << mod_table->GetValue(row,c).ToInt();
			else
	            out << std::setprecision(3) << std::fixed << mod_table->GetValue(row,c).ToFloat();
	        outFile << out.str() << "\t";
		}
		outFile << "\n";
	}
	outFile.close();
    //******************************************************************************************

}
Example #12
0
/**Provide access to the data through the defined QAbstractItemModel definition.
   The index parameter defines how to access the corresponded data while the role
   define the kind of information desired from RepoModel. This method will be queried
   from QView in order to populate the view.

   From the index.internalPointer the RepoModel will have access to the path,
   which uniquely define its entry on ScriptRepository.

   The RepoModel defines 4 columns:
    - Path
    - Status
    - AutoUpdate
    - Delete

   The path, provides the name of the file. The status, give information on the ScriptRepository
   entries. Currently, an entry may be found on the following states:
     - LOCAL_ONLY: The file only exists locally.
     - REMTOE_ONLY: The file has not been downloaded.
     - REMOTE_CHANGED: A new version of the file is available.
     - LOCAL_CHANGED: The file has been changed from the original one.
     - BOTH_CHANGED: Locally and remotelly changed.
     - UPDATED: The remote and local file are identical.

   The AutoUpdate allow to flag the entries to receive the updates automatically when new files
   are available at the central repository.

   The delete column will return a string "protected" or "deletable" that will be used to know if it
   can be deleted or not. For the current version, folders are protected, and files are deletable.

   The repomodel will react to the following roles:
     - DisplayRole: to provide the main information.
     - DecorationRole: to provide icons to make easier and fancier to identify the files and folders.
     - ToolTipRole: to provide user help to interact with this class.
 */
QVariant RepoModel::data(const QModelIndex &index, int role) const
{
    using namespace Mantid::API;
    if (!index.isValid())
        return QVariant();
    RepoItem *item = static_cast<RepoItem*>(index.internalPointer());
    try {
        QString path = item->path();
        Mantid::API::ScriptInfo inf ;
        Mantid::API::SCRIPTSTATUS status;
        // return the data for the display role
        if (role == Qt::DisplayRole) {
            switch(index.column()) {
            case 0: // return the label (the path of the file/folder)
                return item->label();
                break;
            case 1: // ask for the status
                if (isDownloading(index))
                    return downloadSt();
                if (isUploading(index))
                    return uploadSt();
                status = repo_ptr->fileStatus(path.toStdString());
                return fromStatus(status);
                break;
            case 2:// autoupdate option
                status = repo_ptr->fileStatus(path.toStdString());
                if (status == REMOTE_ONLY || status == LOCAL_ONLY)
                    return QVariant();
                inf = repo_ptr->fileInfo(path.toStdString());
                return inf.auto_update?QString("true"):QString("false");
                break;
            case 3:// delete action
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory)
                    return PROTECTEDENTRY;
                status = repo_ptr->fileStatus(path.toStdString());
                if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
                    return PROTECTEDENTRY;
                return DELETABLEENTRY;
                break;
            }
        }

        // return the data for the DecorationRole
        if (role == Qt::DecorationRole) {
            if (index.column() == 0) {
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory) {
                    status = repo_ptr->fileStatus(path.toStdString());
                    if (status == Mantid::API::REMOTE_ONLY)
                        return QIcon::fromTheme("folder-remote",QIcon(QPixmap(":/win/folder-remote")));
                    else
                        return QIcon::fromTheme("folder", QIcon(QPixmap(":/win/folder")));
                }
                else {
                    int pos = QString(path).lastIndexOf('.');
                    if (pos < 0)
                        return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
                    if (path.contains("readme",Qt::CaseInsensitive))
                        return QIcon::fromTheme("text-x-readme", QIcon(QPixmap(":/win/txt_file.png")));

                    QString extension = QString(path).remove(0,pos);
                    if (extension == ".cpp" || extension == ".CPP" || extension == ".c" || extension == ".C")
                        return QIcon::fromTheme("text-x-c++", QIcon(QPixmap(":/win/unknown")));
                    else if (extension == ".py" || extension == ".PY")
                        return QIcon::fromTheme("text-x-python", QIcon(QPixmap(":/win/text-x-python")));
                    else if (extension == ".ui")
                        return QIcon::fromTheme("document", QIcon(QPixmap(":/win/document")));
                    else if (extension == ".docx" || extension == ".doc" || extension == ".odf")
                        return QIcon::fromTheme("x-office-document", QIcon(QPixmap(":/win/office-document")));
                    else if (extension == ".pdf")
                        return QIcon::fromTheme("application-pdf", QIcon(QPixmap(":/win/file_pdf")));
                    else
                        return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
                }
            }
        }// end decorationRole

        // tool tip role
        if (role == Qt::ToolTipRole) {
            if (index.column() == 1) {
                if (isDownloading(index))
                    return "Downloading... Be patient.";
                if (isUploading(index))
                    return "Uploading... Be patient.";
                status = repo_ptr->fileStatus(path.toStdString());
                inf = repo_ptr->fileInfo(path.toStdString());
                switch(status) {

                case REMOTE_ONLY:
                    return (inf.directory)?"Click here to download this folder and all its files"
                           :"Click here to download this file";
                    break;
                case BOTH_UNCHANGED:
                    return (inf.directory)? "This folder is up-to-date" : "This file is up-to-date";
                    break;
                case LOCAL_CHANGED:
                    return "Click here to publish your changes";
                case REMOTE_CHANGED:
                case BOTH_CHANGED:
                    return (inf.directory)?
                           "There is a new version of the files inside this folder. Click here to install them.":
                           "There is a new version of this file available. Click here to install it.";
                    break;
                case LOCAL_ONLY:
                    return "Click here to share this file with the Mantid community!";

                }
            } else if (index.column() == 2) {
                return "Enable or disable this item to be downloaded automatically when new versions will be available";
            } else if (index.column() == 3) {
                if (isUploading(index))
                    return "Connection busy... Be patient.";
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory)
                    return QVariant();
                status = repo_ptr->fileStatus(path.toStdString());
                if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
                    return QVariant();
                return "Click here to delete this file from the Central Repository";
            }
        }// end tool tip
    } catch(Mantid::API::ScriptRepoException & ex) {
        handleExceptions(ex,"",false);
    }
    return QVariant();
}
Example #13
0
std::string ItemDomain::theme()
{
    QString theme = this->ptr()->as<Ilwis::IntervalDomain>()->theme();
    return theme.toStdString();
}
Example #14
0
/**
* Create the dynamic widgets for the concrete loader
*/
void LoadDialog::createDynamicLayout() {
  // Disable the layout so that a widget cannot be interacted with while it may
  // be being deleted
  m_form.propertyLayout->setEnabled(false);

  using namespace Mantid::API;
  using namespace Mantid::Kernel;

  if (!m_form.fileWidget->isValid())
    return;
  // First step is the get the specific loader that is responsible
  auto loadAlg = getAlgorithm();
  const QString filenames = m_form.fileWidget->getUserInput().toString();
  if (filenames == m_currentFiles)
    return;
  m_currentFiles = filenames;
  removeOldInputWidgets(m_form.propertyLayout); // The new file might be invalid
  try {
    loadAlg->setPropertyValue("Filename", filenames.toStdString());
  } catch (std::exception &exc) {
    m_form.fileWidget->setFileProblem(QString::fromStdString(exc.what()));
    m_form.propertyLayout->setEnabled(true);
    m_form.propertyLayout->activate();
    this->resize(this->width(), m_initialHeight + 15);

    // Reset the algorithm pointer so that the base class re-reads the
    // properties and drops links from
    // old widgets meaning they are safe to remove
    setAlgorithm(loadAlg);
    tieStaticWidgets(false); // The ties are cleared when resetting the
                             // algorithm

    return;
  }
  // Reset the algorithm pointer so that the base class re-reads the properties
  // and drops links from
  // old widgets meaning they are safe to remove
  setAlgorithm(loadAlg);
  tieStaticWidgets(false); // The ties are cleared when resetting the algorithm
  // Add the new ones
  const std::vector<Property *> &inputProps = loadAlg->getProperties();
  int dialogHeight = m_initialHeight;
  for (size_t i = 0; i < inputProps.size(); ++i) {
    const Property *prop = inputProps[i];
    const QString propName = QString::fromStdString(prop->name());
    if (propName == "OutputWorkspace" || propName == "Filename")
      continue;
    if (requiresUserInput(propName)) {
      dialogHeight += createWidgetsForProperty(prop, m_form.propertyLayout,
                                               m_form.scrollAreaWidgetContents);
    }
  }
  // Re-enable and recompute the size of the layout
  m_form.propertyLayout->setEnabled(true);
  m_form.propertyLayout->activate();

  const int screenHeight = QApplication::desktop()->height();
  // If the thing won't end up too big compared to the screen height,
  // resize the scroll area so we don't get a scroll bar
  if (dialogHeight < 0.8 * screenHeight)
    this->resize(this->width(), dialogHeight + 20);

  // Make sure the OutputWorkspace value has been stored so that the validator
  // is cleared appropriately
  QString wsName(m_form.workspaceEdit->text());
  if (!wsName.isEmpty())
    storePropertyValue("OutputWorkspace", wsName);
  setPropertyValues(QStringList("Filename"));
}
Project* AllneticImportHandler::parseProject(QXmlAttributes attrs) {
    Project* project = new Project();
    QString name = attrs.value(QString("name"));
    project->setName(new string(name.toStdString()));
    return project;
}
Example #16
0
int main(int argc, char *argv[])
{
    // set debug severity
    osg::setNotifyLevel(osg::ALWAYS);

    // add shaders to openscenegraph
    osg::ref_ptr<osg::Program> shProgram = new osg::Program;
    shProgram->setName("DefaultProgram");

    // vertex shader
    QString vShader = readFileAsQString("shaders/model_vert.glsl");
    shProgram->addShader(new osg::Shader(osg::Shader::VERTEX,vShader.toStdString()));

    // fragment shader
    QString fShader = readFileAsQString("shaders/model_frag.glsl");
    shProgram->addShader(new osg::Shader(osg::Shader::FRAGMENT,fShader.toStdString()));

    // [geometry]
    double polylineLength;
    std::vector<Vec3> vxArray,vxTriStrip;
    std::vector<Vec2> txTriStrip;
    GetStreetVx(8127449,vxArray);
    buildPolylineAsTriStrip(vxArray,120,vxTriStrip,txTriStrip,polylineLength);
//    buildPolylineAsLineStrip(vxArray,vxTriStrip,txTriStrip);

    for(size_t i=0; i < vxTriStrip.size(); i++)
    {
        printVector(vxTriStrip[i]);
    }

    osg::ref_ptr<osg::Vec3Array> listVx = new osg::Vec3Array(vxTriStrip.size());
    osg::ref_ptr<osg::Vec2Array> listTx = new osg::Vec2Array(txTriStrip.size());
    for(size_t i=0; i < listVx->size(); i++)   {
        listVx->at(i).x() = vxTriStrip[i].x - vxTriStrip[0].x;
        listVx->at(i).y() = vxTriStrip[i].y - vxTriStrip[0].y;
        listVx->at(i).z() = vxTriStrip[i].z - vxTriStrip[0].z;

        listTx->at(i).x() = txTriStrip[i].x;
        listTx->at(i).y() = txTriStrip[i].y;
    }

    osg::ref_ptr<osg::DrawElementsUInt> listIx = new osg::DrawElementsUInt(GL_LINE_STRIP);
    for(size_t i=0; i < listVx->size(); i++)   {
        listIx->push_back(i);
    }

    osg::ref_ptr<osg::Geometry> gmStreet = new osg::Geometry;
    gmStreet->setVertexArray(listVx);
    gmStreet->setNormalArray(listVx);
    gmStreet->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
    gmStreet->setTexCoordArray(1,listTx);
    gmStreet->addPrimitiveSet(listIx);

    // [geode]
    osg::ref_ptr<osg::Geode> gdStreet = new osg::Geode;
    osg::StateSet *ss = gdStreet->getOrCreateStateSet();
    ss->setAttributeAndModes(shProgram,osg::StateAttribute::ON);
    gdStreet->addDrawable(gmStreet);

    // [root]
    osg::ref_ptr<osg::Group> groupRoot = new osg::Group;
    ss = groupRoot->getOrCreateStateSet();
    ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    groupRoot->addChild(gdStreet);

    // viewer
    osgViewer::Viewer viewer;
    viewer.setThreadingModel(osgViewer::ViewerBase::SingleThreaded);
    viewer.setUpViewInWindow(100,100,800,480);
    viewer.setSceneData(groupRoot.get());
//    viewer.getCamera()->setClearColor(osg::Vec4(0,0,0,1));

    osgViewer::Viewer::Windows windows;
    viewer.getWindows(windows);
    for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
        itr != windows.end(); ++itr)   {
        (*itr)->getState()->setUseModelViewAndProjectionUniforms(true);
        (*itr)->getState()->setUseVertexAttributeAliasing(true);
    }

    return viewer.run();
}
Example #17
0
// -----------------------------------------------
bool DlgMarkets::LowLevelLoadOfferList(QString qstrServerID, QString qstrNymID, mapIDName & the_map, QString qstrMarketID)
{
    if (qstrServerID.isEmpty() || qstrNymID.isEmpty() || qstrMarketID.isEmpty())
        return false;
    // -----------------------------------
    QString qstrAssetID, qstrCurrencyID, qstrMarketScale;

    const bool bGotIDs = GetMarket_AssetCurrencyScale(qstrMarketID, qstrAssetID, qstrCurrencyID, qstrMarketScale);
    // -----------------------------------
    if (bGotIDs)
    {
        OTDB::OfferListNym * pOfferList = LoadOfferListForServer(qstrServerID.toStdString(), qstrNymID.toStdString());
        OTCleanup<OTDB::OfferListNym> theAngel(pOfferList);

        if (NULL != pOfferList)
        {
            size_t nOfferDataCount = pOfferList->GetOfferDataNymCount();

            for (size_t ii = 0; ii < nOfferDataCount; ++ii)
            {
                OTDB::OfferDataNym * pOfferData = pOfferList->GetOfferDataNym(ii);

                if (NULL == pOfferData) // Should never happen.
                    continue;
                // -----------------------------------------------------------------------
                QString qstrOfferAssetID    = QString::fromStdString(pOfferData->asset_type_id);
                QString qstrOfferCurrencyID = QString::fromStdString(pOfferData->currency_type_id);
                QString qstrOfferScale      = QString::fromStdString(pOfferData->scale);
                // -----------------------------------------------------------------------
                if ((qstrAssetID     != qstrOfferAssetID)    ||
                    (qstrCurrencyID  != qstrOfferCurrencyID) ||
                    (qstrMarketScale != qstrOfferScale))
                    continue;
                // -----------------------------------------------------------------------
                QString qstrTransactionID = QString::fromStdString(pOfferData->transaction_id);
                // -----------------------------------------------------------------------
                QString qstrCompositeID = QString("%1,%2").arg(qstrServerID).arg(qstrTransactionID);
                // -----------------------------------------------------------------------
                QString qstrBuySell = pOfferData->selling ? tr("Sell") : tr("Buy");

                const std::string str_asset_name = OTAPI_Wrap::GetAssetType_Name(pOfferData->asset_type_id);
                // --------------------------
                int64_t lTotalAssets   = OTAPI_Wrap::StringToLong(pOfferData->total_assets);
                int64_t lFinishedSoFar = OTAPI_Wrap::StringToLong(pOfferData->finished_so_far);
                // --------------------------
                const std::string str_total_assets    = OTAPI_Wrap::FormatAmount(pOfferData->asset_type_id, lTotalAssets);
                const std::string str_finished_so_far = OTAPI_Wrap::FormatAmount(pOfferData->asset_type_id, lFinishedSoFar);
                // --------------------------
                QString qstrAmounts;

                if (lFinishedSoFar > 0) // "300g (40g finished so far)"
                    qstrAmounts = QString("%1 (%2 %3)").
                            arg(QString::fromStdString(str_total_assets)).
                            arg(QString::fromStdString(str_finished_so_far)).
                            arg(tr("finished so far"));
                else // "300g"
                    qstrAmounts = QString("%1").
                            arg(QString::fromStdString(str_total_assets));
                // --------------------------
    //          "Buy Silver Grams: 300g (40g finished so far)";
                //
                QString qstrOfferName = QString("%1 %2: %3").
                        arg(qstrBuySell).
                        arg(QString::fromStdString(str_asset_name)).
                        arg(qstrAmounts);
                // ---------------------------
                the_map.insert(qstrCompositeID, qstrOfferName);
                // ---------------------------
                // NOTE that m_mapMarkets is a multimap, since there can be multiple markets with
                // the exact same ID and scale, across multiple servers. The single entry from MTMarketDetails::m_map
                // is then mapped to a group of entries in m_mapMarkets, or to a single entry by cross-referencing
                // the server ID.
                // Whereas in m_mapOffers, each Offer can be uniquely identified (regardless of server) by its unique key:
                // serverID,transactionID. Therefore MTOfferDetails::m_map and m_mapOffers are both maps (neither is a
                // multimap) and each offer is uniquely identified by that same key on both maps.
                // (That's why you see an insert() here instead of insertMulti.)
                //
                m_mapOffers.insert(qstrCompositeID, VPtr<OTDB::OfferDataNym>::asQVariant(pOfferData->clone()));
                // -----------------------------------------------------------------------
            } // for
        }
    }
    // -----------------------------------
    return true;
}
Example #18
0
QString ServerCommand::get(QString key){
    return QString(this->jsonObject.get(key.toStdString(),"").asString().c_str());
}
Example #19
0
    Json::Value users;

    foreach(AccountRecord *record, login_records_)
    {
        login_info["id"] = record->id_.toStdString();
        login_info["pwd"] = record->rem_pwd_ ? record->pwd_.toStdString() : "";
        login_info["login_status"] = (int)record->login_status_;
        login_info["rem_pwd"] = record->rem_pwd_;
        users.append(login_info);
    }

    root["users"] = users;

    std::ofstream os;
	QString path = QQGlobal::configDir() + "/users.json";
    os.open(path.toStdString().c_str(), std::ios::out);
    os<<writer.write(root);
    os.close();
}

void AccountManager::setCurrLoginAccount(const AccountRecord &account)
{
    curr_login_id_ = account.id_;

    AccountRecord *same_account = findAccountById(account.id_);
    if ( same_account )
    {
        login_records_.remove(login_records_.indexOf(same_account));
        login_records_.push_front(same_account);

        same_account->login_status_ = account.login_status_;
Example #20
0
void ServerCommand::set(QString key, QString value){
    this->jsonObject[key.toStdString().c_str()]=value.toStdString().c_str();
}
void CurvedSalsaDialog::slot_generateKey( const QString &key )
{
	uint8_t pubKey[32];
	generate_key( pubKey, key.toStdString()  );
	pubKeyLine->setText( b64encode(pubKey).c_str() );
}
void MyImageClass::SaveDICOMSeries(QString save_path, std::string subfolder)
{
    std::string output_directory = save_path.toStdString();
    output_directory +=subfolder;

    itksys::SystemTools::MakeDirectory( output_directory.c_str() );

    typedef signed short OutputPixelType;
    const unsigned int output_pixel_dimension = 2;

    typedef itk::Image < OutputPixelType, output_pixel_dimension > Image2Dtype;
    typedef itk::CastImageFilter<InternalImageType, ImageType> CastFilterType;

    typedef itk::ImageSeriesWriter < ImageType, Image2Dtype> SeriesWriterType;


    CastFilterType::Pointer caster = CastFilterType::New();
    SeriesWriterType::Pointer series_writer = SeriesWriterType::New();

    typedef itk::NumericSeriesFileNames NumericNamesGeneratorType;

    NumericNamesGeneratorType::Pointer namesGenerator = NumericNamesGeneratorType::New();

    itk::MetaDataDictionary &dict = gdcmIO_->GetMetaDataDictionary();
    std::string tagkey,value;
    tagkey = "0008|0060";
    value = "MR";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);
    tagkey = "0008|0008";
    value = "DERIVED\\SECONDARY";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);
    tagkey = "0008|0064";
    value = "DV";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);

    caster->SetInput(reader_->GetOutput());
    series_writer->SetInput( caster->GetOutput());
    series_writer->SetImageIO(gdcmIO_);

    ImageType::RegionType region = reader_->GetOutput()->GetLargestPossibleRegion();
    ImageType::IndexType start = region.GetIndex();
    ImageType::SizeType size = region.GetSize();

    std::string format = output_directory;
    format += "/image%03d.dcm";

    namesGenerator->SetSeriesFormat(format.c_str());

    namesGenerator->SetStartIndex(start[2]);
    namesGenerator->SetEndIndex(start[2]+size[2]-1);
    namesGenerator->SetIncrementIndex(1);

    series_writer->SetFileNames (namesGenerator->GetFileNames());

    series_writer->SetMetaDataDictionaryArray(reader_->GetMetaDataDictionaryArray());

    try
    {
        series_writer->Update();
    }
    catch( itk::ExceptionObject &excp)
    {
        msg_box_.setText(excp.GetDescription());
        msg_box_.exec();
    }

}
Example #23
0
 void SCNXViewerWidget::openSCNX() {
     QString fileName = QFileDialog::getOpenFileName(this, tr("Open .scnx..."), NULL );
     if (!fileName.isEmpty()) {
         m_scnxViewerWidget->setSCNXModel(fileName.toStdString());
     }
 }
void TaskPadParameters::apply()
{
    std::string name = PadView->getObject()->getNameInDocument();
    const char * cname = name.c_str();

    ui->lengthEdit->apply();

    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Reversed = %i",cname,getReversed()?1:0);
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Midplane = %i",cname,getMidplane()?1:0);

    ui->lengthEdit2->apply();

    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Type = %u",cname,getMode());
    std::string facename = getFaceName().data();
    PartDesign::Pad* pcPad = static_cast<PartDesign::Pad*>(PadView->getObject());
    Part::Feature* support = pcPad->getSupport();

    if (support != NULL && !facename.empty()) {
        QString buf = QString::fromUtf8("(App.ActiveDocument.%1,[\"%2\"])");
        buf = buf.arg(QString::fromUtf8(support->getNameInDocument()));
        buf = buf.arg(QString::fromStdString(facename));
        Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.UpToFace = %s", cname, buf.toStdString().c_str());
    } else
        Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.UpToFace = None", cname);
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");
    if (!PadView->getObject()->isValid())
        throw Base::Exception(PadView->getObject()->getStatusString());
    Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
    Gui::Command::commitCommand();
}
QQuaternion RobotVisualization::getRotation(QString source_frame, QString target_frame){
    osg::Matrixd tr = getRelativeTransform(target_frame.toStdString(), source_frame.toStdString());
    osg::Quat q = tr.getRotate();
    return QQuaternion(q.w(), q.x(), q.y(), q.z());
}
Example #26
0
void EmuThread::run()
{
	running = true;
	setCurrentThreadName("EmuThread");

	g_State.bEmuThreadStarted = true;

	host->UpdateUI();
	host->InitGL();

	glw->makeCurrent();

#ifndef USING_GLES2
	glewInit();
#endif
	NativeInitGraphics();

	INFO_LOG(BOOT, "Starting up hardware.");

	CoreParameter coreParameter;
	coreParameter.fileToStart = fileToStart.toStdString();
	coreParameter.enableSound = true;
	coreParameter.gpuCore = GPU_GLES;
	coreParameter.cpuCore = (CPUCore)g_Config.iCpuCore;
	coreParameter.enableDebugging = true;
	coreParameter.printfEmuLog = false;
	coreParameter.headLess = false;
	coreParameter.renderWidth = 480 * g_Config.iWindowZoom;
	coreParameter.renderHeight = 272 * g_Config.iWindowZoom;
	coreParameter.outputWidth = dp_xres;
	coreParameter.outputHeight = dp_yres;
	coreParameter.pixelWidth = pixel_xres;
	coreParameter.pixelHeight = pixel_yres;
	coreParameter.startPaused = !g_Config.bAutoRun;

	std::string error_string;
	if (!PSP_Init(coreParameter, &error_string))
	{
		ERROR_LOG(BOOT, "Error loading: %s", error_string.c_str());
		FinalShutdown();
		return;
	}

	LayoutGamepad(dp_xres, dp_yres);

	_dbg_update_();

	host->UpdateDisassembly();
	Core_EnableStepping(coreParameter.startPaused ? TRUE : FALSE);

	g_State.bBooted = true;
#ifdef _DEBUG
	host->UpdateMemView();
#endif
	host->BootDone();

	while(running) {
		//UpdateGamepad(*input_state);
		UpdateInputState(input_state);

		static const int mapping[12][2] = {
			{PAD_BUTTON_A, CTRL_CROSS},
			{PAD_BUTTON_B, CTRL_CIRCLE},
			{PAD_BUTTON_X, CTRL_SQUARE},
			{PAD_BUTTON_Y, CTRL_TRIANGLE},
			{PAD_BUTTON_UP, CTRL_UP},
			{PAD_BUTTON_DOWN, CTRL_DOWN},
			{PAD_BUTTON_LEFT, CTRL_LEFT},
			{PAD_BUTTON_RIGHT, CTRL_RIGHT},
			{PAD_BUTTON_LBUMPER, CTRL_LTRIGGER},
			{PAD_BUTTON_RBUMPER, CTRL_RTRIGGER},
			{PAD_BUTTON_START, CTRL_START},
			{PAD_BUTTON_SELECT, CTRL_SELECT},
		};

		for (int i = 0; i < 12; i++) {
            if (input_state->pad_buttons_down & mapping[i][0]) {
				__CtrlButtonDown(mapping[i][1]);
			}
            if (input_state->pad_buttons_up & mapping[i][0]) {
				__CtrlButtonUp(mapping[i][1]);
			}
		}
		__CtrlSetAnalog(input_state->pad_lstick_x, input_state->pad_lstick_y);

		EndInputState(input_state);

		glstate.Restore();
		glViewport(0, 0, pixel_xres, pixel_yres);
		Matrix4x4 ortho;
		ortho.setOrtho(0.0f, dp_xres, dp_yres, 0.0f, -1.0f, 1.0f);
		glsl_bind(UIShader_Get());
		glUniformMatrix4fv(UIShader_Get()->u_worldviewproj, 1, GL_FALSE, ortho.getReadPtr());


		ReapplyGfxState();

		Core_Run();

		// Hopefully coreState is now CORE_NEXTFRAME
		if (coreState == CORE_NEXTFRAME) {
			// set back to running for the next frame
			coreState = CORE_RUNNING;
		}

		fbo_unbind();

		UIShader_Prepare();

		uiTexture->Bind(0);

		glViewport(0, 0, pixel_xres, pixel_yres);

		ui_draw2d.Begin(DBMODE_NORMAL);

		//if (g_Config.bShowTouchControls)
		//	DrawGamepad(ui_draw2d);

		glsl_bind(UIShader_Get());
		ui_draw2d.End();
		ui_draw2d.Flush(UIShader_Get());


		// Tiled renderers like PowerVR should benefit greatly from this. However - seems I can't call it?
#if defined(USING_GLES2)
		bool hasDiscard = false;  // TODO
		if (hasDiscard) {
			//glDiscardFramebuffer(GL_COLOR_EXT | GL_DEPTH_EXT | GL_STENCIL_EXT);
		}
#endif

		glw->swapBuffers();
	}
	glw->doneCurrent();
}
void RobotVisualization::deHighlightSegment(QString link_name){
    bool highlighted = toggleHighlight(link_name.toStdString());
    if(highlighted)
        toggleHighlight(link_name.toStdString());
}
Example #28
0
int LDFEditor::OpenLDFFile(QString strLDFFilePath)
{
    if ( "" != strLDFFilePath )
    {
        CloseCurrentLDFFile();
        list<ParsingResults> ouErrors;
        list<ParsingResults> ouWarnings;
        QFile file(strLDFFilePath);

        if(file.exists() == false)
        {
            QMessageBox::critical(this, "Error", "File does not exists", QMessageBox::Ok);
            return -1;
        }
        ERRORCODE ecResult = LDFDatabaseManager::GetDatabaseManager()->GetLDFCluster()->LoadFromFile(strLDFFilePath.toStdString(), ouErrors, ouWarnings);

        m_pWarningTable->setRowCount(0);
        if ( ouErrors.size() > 0)
        {
            auto itr = ouErrors.begin();
            QString strErrorString;
            if ( ouErrors.end() != itr )
            {
                strErrorString.sprintf("Error While Parsing <br>(Error : %s)</br>", itr->m_strErrorDesc.c_str());
                QMessageBox::critical(this, "Error", strErrorString, QMessageBox::Ok);
            }
        }
        else if ( ouWarnings.size() > 0)
        {
            QList<QVariant> ouRow;
            int nRow = 0;
            m_pWarningTable->setRowCount(ouWarnings.size());
for ( auto itr : ouWarnings )
            {
                ouRow.clear();
                ouRow.push_back("Warning");
                ouRow.push_back(itr.m_strErrorDesc.c_str());
                ouRow.push_back(itr.m_strActionTaken.c_str());
                m_pWarningTable->InsertRow(nRow, ouRow);
                nRow++;
            }
            ui.dockPaneWarning->show();
        }
        else
        {
            ui.dockPaneWarning->hide();
        }
        if ( ecResult == EC_SUCCESS || ecResult == EC_WARNING_SUCCESS )
        {
            OnFileLoad(strLDFFilePath);
        }
    }
    return 0;
}
void RobotVisualization::hideSegmentText(QString link_name){
    OSGSegment* seg = getSegment(link_name.toStdString());
    seg->removeTextLabel();
}
void MainWindow::save_config_dialog() {
	QString sel = QFileDialog::getSaveFileName(this,"Save Configuration File","","Configuration Files (*.cfg)");
	if (!sel.isEmpty())
		save_config(sel.toStdString());
}