Beispiel #1
0
bool  MainWindow::Initialize(int argc,const char** argv)
{
    backend = new SimTestBackend(&world);
    if(!backend->LoadAndInitSim(argc,argv)) {
      printf("ERROR LOADING FROM COMMAND LINE");
      return false;
    }
    else
      printf("BACKEND LOADED\n");

    gui=new QSimTestGUI(ui->displaywidget,backend);
    gui->ini=ini;
    ui->displaywidget->gui = gui;

    //set the system calls for encoding video
    ui->displaywidget->moviefile = toStdString(ini->value("video_record_file","klampt_record.mp4").toString());
    ui->displaywidget->SetVideoEncoding(toStdString(ini->value("video_encoding_command","ffmpeg -y -f image2 -i image%04d.ppm").toString()));

    ui->displaywidget->installEventFilter(this);
    ui->displaywidget->setFocusPolicy(Qt::WheelFocus);

    backend->Start();
    DoFreeMode();
    return true;
}
Beispiel #2
0
  void BuildModel::exportAsBIF(ProjectItem* item, QList<QPair<QString, QString>> &result) 
  {
    auto path = __project->dir().absoluteFilePath(item->path());
    gum::prm::o3prm::O3prmReader<double> reader;
    reader.addClassPath( __project->dir().absolutePath().toStdString() );
    auto package = __retrievePackage( item );
    reader.readFile(path.toStdString(), package.toStdString());
    auto prm = reader.prm();

    reader.showElegantErrorsAndWarnings();

    for ( auto sys: prm->systems() ) {
      gum::BayesNet<double> bn;
      gum::BayesNetFactory<double> bn_fact(&bn);
      sys->groundedBN(bn_fact);

      gum::BIFWriter<double> writer;
      std::stringstream str;

      writer.write(str, bn);

      auto name = QString::fromStdString(sys->name());
      auto ground = QString::fromStdString( str.str() );
      auto pair = qMakePair(name, ground);

      result.push_back(pair);
    }

    delete prm;
  }
void PreprocessHandler::writeTargetFile(QString sourceFile, QString targetFile, QString currentDir) {

    QFileInfo sourceInfo(sourceFile);
    QDir::setCurrent(sourceInfo.absolutePath());

    std::string result;
    result.reserve(20 * 1024);  // 20K

    result += "# 1 \"builtins\"\n";
    result += "# 1 \"";
    result += toStdString(sourceFile);
    result += "\"\n";

    qDebug() << "Processing source" << sourceInfo.absolutePath() << sourceInfo.fileName();
    preprocess.file(toStdString(sourceInfo.fileName()),
                    rpp::pp_output_iterator<std::string> (result));

    QDir::setCurrent(currentDir);

    QFile f(targetFile);
    if (!f.open(QIODevice::Append | QIODevice::Text)) {
        std::fprintf(stderr, "Failed to write preprocessed file: %s\n", qPrintable(targetFile));
    }
    f.write(result.c_str(), result.length());
}
Beispiel #4
0
void
MainWindow::handleOpenFile()
{
    auto name = QFileDialog::getOpenFileName( this
                                              , tr( "Open QtPlatz publisher xml" )
                                              , recentFile( "RecentFiles", "Files" )
                                              , tr( "QtPlatz publisher xml(*.xml);;HTML(*.html)" ) );
    if ( !name.isEmpty() ) {
        boost::filesystem::path path( name.toStdWString() );
        if ( path.extension() == ".xml" ) {

            addRecentFiles( "RecentFiles", "Files", name );

            auto doc = std::make_shared< adpublisher::document>();

            if ( doc->load_file( name.toStdString().c_str() ) ) {

                setWindowTitle( name );
                xmlpath_ = name.toStdString();

                ui->actionApply->setEnabled( true );
                processed_.clear();

                docEditor_->setDocument( doc );
            }
        }
        else if ( path.extension() == ".html" ) {
            docEditor_->setOutput( QUrl( QString( "file:///%1" ).arg( path.string().c_str() ) ) );
        }
    }
}
Beispiel #5
0
void MainWindow::ChangeEncoderCommand(){
    QString preset = ini->value("video_encoding_command","ffmpeg -y -f image2 -i image%04d.ppm").toString();
    QString value = QInputDialog::getText(this,"Record Command","enter the system command for the encoder using input files *.ppm",
                          QLineEdit::Normal,preset);
    string tmp = toStdString(value);
    const char* cstr = tmp.c_str();
    ui->displaywidget->SetVideoEncoding(toStdString(value));
    ini->setValue("video_encoding_command",value);
}
Beispiel #6
0
std::vector<Transaction *> CreateEdit::transactions() const {
    auto text = this->text();
    if(text.isEmpty())
        return std::vector<Transaction *>();
    if(QFileInfo(text).exists()) {
        auto is = std::ifstream(text.toStdString());
        return this->read_transactions(&is);
    } else {
        auto is = std::istringstream(text.toStdString());
        return this->read_transactions(&is);
    }
}
void DiscretePeriodicWavelet::makeInverseTransform()
{
    if (m_thresholdedSignal.empty()) {
        if (m_transformedSignal.empty()) {
            return;
        }
        idwt(m_transformedSignal, m_flag, toStdString(m_waveletFunction), m_outputSignal, m_length);
        return;
    }

    idwt(m_thresholdedSignal, m_flag, toStdString(m_waveletFunction), m_outputSignal, m_length);
}
Beispiel #8
0
		virtual std::string getSDFilePath(const std::string& robotName, unsigned fileNumber) const override
		{
			auto fileName(QString("%1/%2/%3/U%4.DAT")
				.arg(QDesktopServices::storageLocation(QDesktopServices::DataLocation))
				.arg(qHash(QDir(sceneFileName).canonicalPath()), 8, 16, QChar('0'))
				.arg(QString::fromStdString(robotName))
				.arg(fileNumber)
			);
			QDir().mkpath(QFileInfo(fileName).absolutePath());
			// dump
			std::cerr << fileName.toStdString() << std::endl;
			return fileName.toStdString();
		}
Beispiel #9
0
		virtual std::string getSDFilePath(const std::string& robotName, unsigned fileNumber) const override
		{
			auto paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
			auto fileName(QString("%1/%2/%3/U%4.DAT")
				.arg(paths.empty() ? "" : paths.first())
				.arg(qHash(QDir(sceneFileName).canonicalPath()), 8, 16, QChar('0'))
				.arg(QString::fromStdString(robotName))
				.arg(fileNumber)
			);
			QDir().mkpath(QFileInfo(fileName).absolutePath());
			// dump
			std::cerr << fileName.toStdString() << std::endl;
			return fileName.toStdString();
		}
Beispiel #10
0
/***********************************************************************
 * color utils functions
 **********************************************************************/
QColor typeStrToColor(const QString &typeStr_)
{
    auto typeStr = typeStr_;
    if (typeStr.isEmpty()) return Qt::white; //not specified

    //try to pass it through DType to get a "nice" name
    try
    {
        Pothos::DType dtype(typeStr.toStdString());
        //use a darker color for multiple dimensions of primitive types
        if (dtype.dimension() > 1)
        {
            const auto name1d = Pothos::DType::fromDType(dtype, 1).toMarkup();
            return typeStrToColor(QString::fromStdString(name1d)).darker(120);
        }
        typeStr = QString::fromStdString(dtype.toMarkup());
    }
    catch (const Pothos::DTypeUnknownError &){}

    //check the cache
    {
        QReadLocker lock(getLookupMutex());
        auto it = getColorMap()->find(typeStr);
        if (it != getColorMap()->end()) return it->second;
    }

    //create a new entry
    const auto color = __typeStrToColor(typeStr);
    QWriteLocker lock(getLookupMutex());
    return getColorMap()->emplace(typeStr, color).first->second;
}
Beispiel #11
0
AffinityZoneEditor *AffinityZonesDock::createZoneFromName(const QString &zoneName)
{
    auto editor = new AffinityZoneEditor(this);
    _editorsTabs->addTab(editor, zoneName);
    if (zoneName == getSettings().value("AffinityZones/currentZone").toString()) _editorsTabs->setCurrentWidget(editor);

    //restore the settings from save -- even if this is a new panel with the same name as a previous one
    auto json = getSettings().value("AffinityZones/zones/"+zoneName).toString();
    if (not json.isEmpty()) try
    {
        Poco::JSON::Parser p; p.parse(json.toStdString());
        auto dataObj = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>();
        editor->loadFromConfig(dataObj);
    }
    catch (const Poco::JSON::JSONException &ex)
    {
        poco_error_f2(Poco::Logger::get("PothosGui.AffinityZonesDock"), "Failed to load editor for zone '%s' -- %s", zoneName.toStdString(), ex.displayText());
    }

    //now connect the changed signal after initialization+restore changes
    connect(editor, SIGNAL(settingsChanged(void)), this, SLOT(handleZoneEditorChanged(void)));
    connect(editor, SIGNAL(settingsChanged(void)), _mapper, SLOT(map(void)));
    _mapper->setMapping(editor, zoneName);

    //when to update colors
    connect(editor, SIGNAL(settingsChanged(void)), this, SLOT(updateTabColors(void)));
    this->updateTabColors();

    return editor;
}
bool PreprocessHandler::handler() {
    QFile file(ppconfig);
    if (!file.open(QFile::ReadOnly)) {
        std::fprintf(stderr, "Preprocessor configuration file not found '%s'\n", ppconfig);
        return false;
    }

    QByteArray ba = file.readAll();
    file.close();

// FIXME: Dump empty at start
// FIXME: If any debug mode, enable showing DEFINE/UNDEF/INCLUDE(summary/verbose)
// FIXME: If nothing set on cmdline enable #define Q_OS_OS2
// PROCESS string of "#define name value"
// FIXME: Replace "null_out" with stdout
    preprocess.operator()(ba.constData(), ba.constData() + ba.size(), null_out);
// FIXME: Dump defines set
// FIXME: Restore normal debug mode, showing DEFINE/UNDEF/INCLUDE(summary/verbose)
    QStringList includes = setIncludes();

    foreach(QString include, includes)
        preprocess.push_include_path(toStdString(QDir::toNativeSeparators(include)));
// FIXME: Dump defines set

    QString currentDir = QDir::current().absolutePath();

    writeTargetFile(sourceFile, targetFile, currentDir);

    return true;
}
Beispiel #13
0
octave_scalar_map makeKeyEventStruct (QKeyEvent* event)
{
  octave_scalar_map retval;

  retval.setfield ("Key", KeyMap::qKeyToKeyString (event->key ()));
  retval.setfield ("Character", toStdString (event->text ()));

  std::list<std::string> modList;
  Qt::KeyboardModifiers mods = event->modifiers ();

  if (mods & Qt::ShiftModifier)
    modList.push_back ("shift");
  if (mods & Qt::ControlModifier)
#ifdef Q_OS_MAC
    modList.push_back ("command");
#else
    modList.push_back ("control");
#endif
  if (mods & Qt::AltModifier)
    modList.push_back ("alt");
#ifdef Q_OS_MAC
  if (mods & Qt::MetaModifier)
    modList.push_back ("control");
#endif

  retval.setfield ("Modifier", Cell (modList));

  return retval;
}
Beispiel #14
0
//-----------------------------------------------------------------------------------
void Editor::on_action_LOAD_triggered()
{
    QFileDialog dialog {this};
    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.setViewMode(QFileDialog::List);
    dialog.setOption(QFileDialog::DontUseCustomDirectoryIcons);
    dialog.setNameFilter("Text (*.mu *.txt)");
    dialog.exec();
    auto files = dialog.selectedFiles();
    if (files.isEmpty())
        return;

    auto fileName = files[0];

    std::ifstream reader (fileName.toStdString(), std::ios_base::binary);

    if (!reader.good()) {
        QMessageBox::warning(this, "IO Error", "Could not load the file specified", QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    std::string data;
    do {
        char buffer[4096];
        reader.read(buffer, 4096);
        data.append(buffer, reader.gcount());
    } while (reader.gcount() == 4096);

    qDebug() << QString::fromStdString(data);
    builder_.loadMarkup(data);
    builder_.generateUiElements(ui->viewPort->layout());
}
Beispiel #15
0
void MainWindow::LogCommandedPath(bool status){
  string file;
  stringstream ss;
  if(status) file = toStdString(ini->value("log_commanded_path_file","simtest_commanded_path_log.csv").toString());
  ss<<"0 "<<file;//multiple robots what do we do?
  gui->SendCommand("log_commanded_path",ss.str());
}
Beispiel #16
0
/*!
  */
void CuiRendererManager::backupSceneFiles(const QJsonObject& scene_value,
                                          const SettingNodeBase& scene_settings,
                                          const QString& output_dir,
                                          QString* error_message) const noexcept
{
  QString dummy_message;
  QString* err_message = (error_message != nullptr) ? error_message : &dummy_message;

  // Backup scene settings
  {
    const auto backup_path = output_dir + "/" + keyword::sceneBackupFileName;
    if (!SceneDocument::saveDocument(backup_path, scene_value, *err_message))
      return;
  }

  // Backup scene binary
  if (isSavingSceneBinaryEnabled()) {
    const auto backup_path = output_dir + "/" + keyword::sceneBinaryFileName;
    std::ofstream scene_binary{backup_path.toStdString(), std::ios::binary};
    if (!scene_binary.is_open()) {
      *err_message = "making scene binary failed.";
      return;
    }
    scene_settings.writeData(&scene_binary);
  }
}
Beispiel #17
0
bool JackServer::setValue(jackctl_parameter_t *parameter, const QVariant &value)
{
    jackctl_parameter_value_t jvalue = {};

    switch (this->jackctl_parameter_get_type(parameter)) {
    case JackParamInt:
        jvalue.i = value.value<decltype(jvalue.i)>();

        break;
    case JackParamUInt:
        jvalue.ui = value.value<decltype(jvalue.ui)>();

        break;
    case JackParamChar:
        jvalue.c = value.value<decltype(jvalue.c)>();

        break;
    case JackParamString: {
        auto str = value.toString();
        memcpy(jvalue.str,
               str.toStdString().c_str(),
               size_t(std::min(str.size(), JACK_PARAM_STRING_MAX)));

        break;
    }
    case JackParamBool:
        jvalue.b = value.toBool();

        break;
    }

    return this->jackctl_parameter_set_value(parameter, &jvalue);
}
Beispiel #18
0
static std::string qUrlQueryToPostData(const QUrlQuery & query) {
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	return toStdString(query.encodedQuery());
#else
	return toUTF8(query.query(QUrl::FullyEncoded));
#endif
}
TString PlatformString::toString() {
#ifdef _UNICODE
    return toUnicodeString();
#else
    return toStdString();
#endif //_UNICODE
}
Beispiel #20
0
void ComponentDock::actAdd(QAction *Action) {
	auto ent = eman->getEntity(currEntity);
	// logic components need a unique name
	if (Action->text() == "Logic") {
		auto text = getAvailName(ent);
		if (text.isEmpty()) {
			return;
		}

		ent->addComponent(Kite::CTypes::Logic, text.toStdString());
		// fixed components
	} else {
		// available name
		auto isExist = ent->hasComponentType((Kite::CTypes)Action->data().toUInt());
		if (isExist) {
			QMessageBox msg;
			msg.setWindowTitle("Message");
			msg.setText("this component is already exist!");
			msg.exec();
			return;
		}
		ent->addComponent((Kite::CTypes)Action->data().toUInt(), Action->text().toStdString());
	}

}
Beispiel #21
0
void SceneSet::initPoperty()
{
	resize(200, 300);
	mPreview = NULL;
	mSkyBoxName = "";
	QFile skyConfig("resource/setting/sky.config");
	QDomDocument dom;
	QDomElement  root;
	QDomElement  child;
	if( skyConfig.open(QFile::ReadOnly) )
	{
		if( !dom.setContent(&skyConfig, true) )
		{
			return;
		}
		root = dom.documentElement();
		mStrPixPath = root.attribute("path");
		child = root.firstChildElement("skybox");
		QString chs;
		QString material;
		QString name;
		while( !child.isNull() )
		{
			chs = child.attribute("chs");
			material = child.attribute("mat");
			name = child.attribute("name");
			mMapName[chs] = toStdString(material);
			mMapPixmapName[chs] = name;
			mComScene->addItem( chs );
			child = child.nextSiblingElement("skybox");
		}
	}
}
void ArraySetDlg::setCurType(int curType)
{
	LogMessage("cur Type is :"+toStdString(curType));
	ui.mListArrayType->setCurrentRow( curType );
	this->on_mListArrayType_currentRowChanged( curType );
	ui.mLabCurType->setText(toChs("当前正在使用:") + 
		ui.mListArrayType->item(curType)->text());
}
Beispiel #23
0
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) {
    auto logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message);

    if (!logMessage.isEmpty()) {
        Lock lock(logBufferMutex);
        logBuffer.append(logMessage.toStdString() + '\n');
    }
}
Beispiel #24
0
void ComponentDock::actAddDef() {
	auto ent = eman->getEntity(currEntity);
	auto text = getAvailName(ent);
	if (text.isEmpty()) {
		return;
	}

	ent->addComponent(Kite::CTypes::Logic, text.toStdString());
}
Beispiel #25
0
Option<Error> jsToJson(QJSValue value, JsonValue::Builder builder) {
    if (value.isArray()) {
        std::vector<QJSValue> arr;
        QJSValueIterator iter(value);
        while (iter.hasNext()) {
            iter.next();
            // dafuq!? why is this required
            if (!iter.hasNext()) {
                break;
            }
            arr.push_back(iter.value());
        }
        auto lst = builder.initArray(static_cast<unsigned int>(arr.size()));
        for (auto k = 0; k < arr.size(); ++k) {
            auto subvalue = lst[k];
            auto opt_err = jsToJson(arr[k], subvalue);
            if (opt_err.has()) {
                return opt_err;
            }
        }
        return Option<Error>();
    } if (value.isObject()) {
        std::vector<std::tuple<QString, QJSValue>> arr;
        QJSValueIterator iter(value);
        while (iter.hasNext()) {
            iter.next();
            arr.push_back(std::make_tuple(iter.name(), iter.value()));
        }
        auto lst = builder.initObject(static_cast<unsigned int>(arr.size()));
        for (auto k = 0; k < arr.size(); ++k) {
            auto value_builder = lst[k].initValue();
            const char *name = std::get<0>(arr[k]).toUtf8().constData();
            lst[k].setName(name);
            auto opt_err = jsToJson(std::get<1>(arr[k]), value_builder);
            if (opt_err.has()) {
                return opt_err;
            }
        }
        return Option<Error>();
    } if (value.isBool()) {
        builder.setBoolean(value.toBool());
        return Option<Error>();
    } if (value.isNumber()) {
        builder.setNumber(value.toNumber());
        return Option<Error>();
    } if (value.isString()) {
        const char *str = value.toString().toUtf8().constData();
        builder.setString(str);
        return Option<Error>();
    } if (value.isNull()) {
        builder.setNone();
        return Option<Error>();
    }
    auto tpname = toStdString(value.toVariant().typeName());
    Error err(Error::Kind::ClientSideError, "Invalid type: " + tpname);
    return err;
}
/**
Load settings
@param options : map of user options to load into
*/
void QDataProcessorWidget::loadSettings(
    std::map<std::string, QVariant> &options) {
  QSettings settings;
  settings.beginGroup(DataProcessorSettingsGroup);
  QStringList keys = settings.childKeys();
  for (auto it = keys.begin(); it != keys.end(); ++it)
    options[it->toStdString()] = settings.value(*it);
  settings.endGroup();
}
Beispiel #27
0
bool Server::attachFile(int issue_id, const QString & filePath,
                        const QString & fileDescription, const QString & comment) {
	
	QFile file(filePath, this);
	if(!file.open(QIODevice::ReadOnly)) {
		return false;
	}
	
	if(file.size() > 20 * 1024 * 1024) {
		return false;
	}
	
	QString uuid = QUuid::createUuid().toString();
	QByteArray boundaryRegular = ("--" + uuid.mid(1, uuid.length() - 2)).toUtf8();
	QByteArray boundary = "\r\n--" + boundaryRegular + "\r\n";
	QByteArray boundaryLast = "\r\n--" + boundaryRegular + "--\r\n";

	QByteArray data;
	data.append("--" + boundaryRegular + "\r\n");
	data.append("Content-Disposition: form-data; name=\"uploader_file\"; filename=\""
	            + QFileInfo(file).fileName().toUtf8() + "\"\r\n");
	data.append("Content-Type: application/octet-stream\r\n\r\n");
	data.append(file.readAll());
	data.append(boundary);
	data.append("Content-Disposition: form-data; name=\"uploader_file_description\"\r\n\r\n");
	data.append(fileDescription.toUtf8());
	data.append(boundary);
	data.append("Content-Disposition: form-data; name=\"comment\"\r\n\r\n");
	data.append(comment.toUtf8());
	data.append(boundaryLast);
	
	QByteArray contentType = "multipart/form-data; boundary=\"" + boundaryRegular + "\"";

	QString url = "/upload/to/issue/" + QString::number(issue_id);
	
	http::POSTRequest request(toUTF8(m_serverPrefix + url));
	request.setData(toStdString(data));
	request.setContentType(toStdString(contentType));
	request.setFollowRedirects(false);
	
	boost::scoped_ptr<http::Response> response(post(request));
	
	return response->ok();
}
Beispiel #28
0
void MainWindow::ChangeRecordFile(){
    QString filter="MPG Video (*.mpg)";
    QString recordPath = ini->value("video_record_file",QDir::home().absolutePath()).toString();
    QString recordfilename = QFileDialog::getSaveFileName(this,"Recording Output",recordPath,filter,&filter);
    if(!recordfilename.isNull()) {
      ini->setValue("video_record_file",QFileInfo(recordfilename).absoluteFilePath());
      string str = toStdString(recordfilename);
      ui->displaywidget->moviefile = str;
    }
}
Beispiel #29
0
  gum::prm::o3prmr::O3prmrInterpreter* BuildModel::build(ProjectItem* item)
  {
    auto interpreter = new gum::prm::o3prmr::O3prmrInterpreter();

    interpreter->addPath(__project->dir().absolutePath().toStdString() + '/');
    auto path = __project->dir().absoluteFilePath(item->path());
    interpreter->interpretFile(path.toStdString());

    return interpreter;
  }
void AudioSourceManager::parsePackage(juce::var package)
{
    std::cout<<"HEADER:"<<std::endl<<std::endl;
    var id = package[Identifier("id")];
    std::cout<<"Package ID: "<<id.toString()<<std::endl;
    
    AudioSourcePackage audioSourcePackage(id.toString().toStdString());
    
    var type = package[Identifier("type")];
    std::cout<<"Package Type: "<<type.toString()<<std::endl;
    var groups = package[Identifier("groups")];
    
    std::cout<<"Number of Groups: "<<groups.size()<<std::endl<<std::endl;
    
    for(auto group = 0; group < groups.size(); group++)
    {
        auto currentGroup = groups[group];
        auto groupName = currentGroup[Identifier("name")].toString();
        std::cout<<"Group: "<<groupName<<std::endl;
        auto layer = currentGroup[Identifier("layer")];
        std::cout<<"Layer: "<<layer[0].toString()<<" - "<<layer[1].toString()<<std::endl<<std::endl;
        
        std::cout<<"    SOURCES:"<<std::endl;
        auto samples = currentGroup[Identifier("samples")];
        
        for(auto sample = 0; sample < samples.size(); sample++)
        {
            auto currentSampleObject = samples[sample];
            auto currentSample = currentSampleObject[Identifier("sample")];
            auto currentSampleName = currentSample[Identifier("name")].toString();
            std::cout<<"    Sample: "<<currentSampleName<<std::endl;
            AudioSourceDescription description;
            description.ID = "Fileplayer";
            description.info = currentSampleName.toStdString();
            description.velocity.setMinValue(layer[0]);
            description.velocity.setMaxValue(layer[1]);
            
            var zone = currentSample[Identifier("zone")];
            
            description.note.setMinValue(zone[0]);
            description.note.setMaxValue(zone[0]);
            
            description.channel.setMinValue(0);
            description.channel.setMaxValue(16);
            description.channel.setValue(0);
            
            audioSourcePackage.addSource(description);
        }
        std::cout<<std::endl;
    }
    std::cout<<std::endl;
    
    packages.emplace_back(audioSourcePackage);
}