void SyntaxHighlighter::TextFormat::loadFromJson(const QJsonObject& o) {
		namespace Highlight = JEnt::Highlight;
		// Italicフラグ: デフォルト値=false
		auto itr = o.find(Highlight::italic);
		bool b = false;
		if(itr != o.end())
			b = itr.value().toBool(false);
		setFontItalic(b);
		// Boldフラグ: デフォルト値=QFont::Normal
		int w = QFont::Normal;
		itr = o.find(Highlight::bold);
		if(itr != o.end())
			w = itr.value().toBool(false) ? QFont::Bold : QFont::Normal;
		setFontWeight(w);
		// Underlineフラグ: デフォルト値=false
		b = false;
		itr = o.find(Highlight::underline);
		if(itr != o.end())
			b = itr.value().toBool(false);
		setFontUnderline(b);
		// Color RGB: デフォルト値=(128,128,128)
		QColor col(128,128,128);
		itr = o.find(Highlight::color);
		if(itr != o.end()) {
			QJsonArray ar = itr.value().toArray();
			if(ar.size() == 3)
				col.setRgb(ar[0].toInt(), ar[1].toInt(), ar[2].toInt());
		}
		setForeground(col);
	}
Example #2
0
void AnimationToJson::fromJsonObject(KeyFrame &keyFrame, const QJsonObject &object, const QString &fileName)
{
    keyFrame.setFileName(QFileInfo(fileName).dir().absolutePath() + "/" + object.find("fileName").value().toString());
    keyFrame.setOffset(pointFromJsonObject(object.find("offset").value().toObject()));
    keyFrame.setRect(rectFromJsonObject(object.find("rect").value().toObject()));

    QJsonObject customPropertiesObject = object.find("customProperties").value().toObject();
//    qDebug() << customPropertiesObject;
    for (auto it = customPropertiesObject.begin(); it != customPropertiesObject.end(); ++it) {
        keyFrame.setCustomProperty(it.key(), it.value().toDouble());
    }
//    for (const auto &value : customPropertiesObject) {
//        value.
//        qDebug() << value;
//        for (auto it = value.begin(); it != value.end(); ++it) {
//            keyFrame.setCustomProperty(it.key(), it.value().toDouble());
//        }
//    }

    for (const QJsonValue &value : object.find("hitBoxes").value().toArray()) {
        auto hitBox = new HitBox();
        fromJsonObject(*hitBox, value.toObject());
        keyFrame.insertHitBox(keyFrame.hitBoxes().count(), hitBox);
    }
}
Example #3
0
void NetWork::dealGetListInfo(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray listObj = resultObj.find("tracks").value().toArray();

	QList<QStringList> rev_list;
	for (int i = 0; i < listObj.size(); i++)
	{
		QJsonObject mp3Obj = listObj.at(i).toObject();
		QString url = mp3Obj.find("mp3Url").value().toString();
		QString name = mp3Obj.find("name").value().toString();
		QJsonArray artistsList = mp3Obj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
		{
			QJsonObject artistsObjName = artistsList.at(j).toObject();
			artists.append(artistsObjName.find("name").value().toString() + " ");
		}
		QJsonObject albumObj = mp3Obj.find("album").value().toObject();
		QString album = albumObj.find("name").value().toString();
		int songId = mp3Obj.find("id").value().toInt();
		QStringList list;
		list << name << artists << album << url << QString::number(songId);
		rev_list.insert(i, list);
	}
	emit musicInfo(rev_list);
}
	void SyntaxHighlighter::Keywords::loadFromJson(const QJsonObject& o) {
		namespace Keyword = JEnt::Keyword;
		_strV.clear();
		_regV.clear();
		// AutoSpacingフラグ: デフォルト値=false
		bool b = false;
		auto itr = o.find(Keyword::auto_spacing);
		if(itr != o.end())
			b = itr.value().toBool(false);
		_bAutoSpacing = b;
		// CaseSensitiveフラグ: デフォルト値=false
		b = false;
		itr = o.find(Keyword::case_sensitive);
		if(itr != o.end())
			b = itr.value().toBool(false);
		_bCaseSensitive = b;
		// String or RegEx: デフォルト値=string
		QString strType = o.value(Keyword::type).toString(Keyword::string);
		bool bIsRegex = strType == Keyword::regex;

		QJsonArray ar = o.value(Keyword::words).toArray();
		for(const auto& w : ar) {
			QString word = w.toString();
			if(!word.isEmpty()) {
				if(bIsRegex) {
					// 正規表現によるキーワード指定
					_regV.emplace_back(word,
									   _bCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
				} else {
					// 文字列によるキーワード指定
					_strV.emplace_back(word);
				}
			}
		}
	}
Example #5
0
void NetWork::dealLyric(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject lrcObj = obj.find("lrc").value().toObject();
	QString strLyric = lrcObj.find("lyric").value().toString();
	if (strLyric == "")
		strLyric = "当前歌曲没有歌词";
	emit lyric(strLyric);
}
Example #6
0
// ------------ TwqUser::P_Name ------------
void TwqUser::P_Name::receiveInfo(const QJsonObject& jobj) {
	// from Search
	if(jobj.contains(JSONKWD::TWEET::FromUserName)) {
		_v.name = jobj.find(JSONKWD::TWEET::FromUserName).value().toString();		// 表示名
		_v.scrName = jobj.find(JSONKWD::TWEET::FromUser).value().toString();		// アカ名
		haveF |= Flag;
	} else if(jobj.contains(JSONKWD::USER::Name)) {
		// from Home
		_v.name = jobj.find(JSONKWD::USER::Name).value().toString();
		_v.scrName = jobj.find(JSONKWD::USER::Screen_name).value().toString();
		haveF |= Flag;
	}
}
Example #7
0
// ------------ TwqUser::P_Follow ------------
void TwqUser::P_Follow::receiveInfo(const QJsonObject& jobj) {
	auto itr = jobj.find(JSONKWD::USER::Following);
	if(itr != jobj.end()) {
		_v.bFollowing = itr.value().toBool();
		haveF |= Flag;
	}
	itr = jobj.find("connections");
	if(itr != jobj.end()) {
		// friendships/lookup タイプ
		_v.bFollowing = itr.value().toObject().contains("following");
		haveF |= Flag;
	}
}
Example #8
0
QJsonObject Plugin14C::checkValuesCompatibility(const QJsonObject& values){
    QJsonObject result = values;

    if(result.find(DATE_14C_DELTA_R_STR) == result.end())
        result[DATE_14C_DELTA_R_STR] = 0;
    
    if(result.find(DATE_14C_DELTA_R_ERROR_STR) == result.end())
        result[DATE_14C_DELTA_R_ERROR_STR] = 0;
    
    // Force curve name to lower case :
    result[DATE_14C_REF_CURVE_STR] = result[DATE_14C_REF_CURVE_STR].toString().toLower();
    
    return result;
}
Example #9
0
static bool checkProtocol(const QJsonObject& in, SceneDeserializer::Info* info)
{
    if (in.find("protocol") == in.end())
    {
        if (info)
            info->error_message = "Could not detect protocol";
        return false;
    }
    else
    {
        auto protocol_version = in["protocol"].toDouble();
        if (protocol_version < 6)
        {
            if (info)
                info->error_message = "File was saved with a older protocol "
                                      "and can no longer be read.";
            return false;
        }
        else if (protocol_version > 6)
        {
            if (info)
                info->error_message = "File was saved with a newer protocol "
                                      "and cannot yet be read.";
            return false;
        }
    }
    return true;
}
Example #10
0
void GetRequest::exec(AbstractWeiboApi *apiRequest)
{
  QByteArray responseStr;
  if (apiRequest->isHttpGet())
    responseStr = manager->getMethod(apiRequest->getUrl());
  else {
    QHttpMultiPart multiPart(QHttpMultiPart::FormDataType);
    QList<QHttpPart> partList = apiRequest->setPostMultiPart();
    for (int i = 0; i < partList.size(); i++)
      multiPart.append(partList.at(i));

    responseStr = manager->postMethod(apiRequest->getUrl(), multiPart);
  }
  QString error;
  JsonParser parser(responseStr);

  QJsonObject responseMap = parser.getJsonObject();

  if (responseMap.isEmpty())
    error = responseStr;
  else
    error = apiRequest->parse(responseMap);

  if (responseMap.find("error") != responseMap.end())
    error = responseStr;

  emit sendLog(apiRequest->getUrl().toString(), QDateTime::currentDateTime(),
               responseMap, error);
}
Example #11
0
void DbModel::insert(QString key, QJSValue callbackFunction)
{
    if(m_name.isEmpty() || key.isEmpty() ||  m_jsonDocument.isNull())
    {
        DEBUG << "cannot insert. name is empty or json document is null";
        if(callbackFunction.isCallable())
        {
            callbackFunction.call(QJSValueList() << 1);
        }
        return;
    }
    QJsonObject root = m_jsonDocument.object();
    QJsonValueRef _arrayRef = root.find(m_name).value();
    QJsonArray _arrayMain = _arrayRef.toArray();
    QVariantMap _obj;
    _obj.insert("name", key);
    _arrayMain.append(QJsonValue::fromVariant(_obj));
    root.insert(m_name, _arrayMain);
    m_jsonDocument.setObject(root);
    qDebug() << m_jsonDocument.toJson();
    saveDatabase();
    if(callbackFunction.isCallable())
    {
        callbackFunction.call(QJSValueList() << 0);
    }
    beginInsertRows(QModelIndex(), _arrayMain.count() - 1, _arrayMain.count() - 1);
    endInsertRows();
}
Example #12
0
// ------------ TwqUser::P_Followed ------------
void TwqUser::P_Followed::receiveInfo(const QJsonObject& jobj) {
	auto itr = jobj.find("connections");
	if(itr != jobj.end()) {
		_v.bFollowed = itr.value().toObject().contains("followed_by");
		haveF |= Flag;
	}
}
JsonCoinInfoParser::JsonCoinInfoParser( const QJsonObject& apiResult )
    : QJsonObject( apiResult )
{
    qDebug() << "JsonCoinInfoParser: " << apiResult.begin().key();
    if ( apiResult.find( "Result" ).value().isObject() )
    {
        if ( apiResult.find( "Result" ).value().toObject().find( "CoinInfo" ).value().isObject() )
        {
            coinInfoObject = apiResult.find( "Result" ).value().toObject().find( "CoinInfo" ).value().toObject();
        }
        else
        {
            qDebug()<<"JsonCoinInfoParser first key: " << apiResult.find( "Result" ).value().toObject().begin().key();
        }
    }
}
Example #14
0
// ------------ TwqUser::P_PictureURL ------------
void TwqUser::P_PictureURL::receiveInfo(const QJsonObject& jobj) {
	// profile_url項があればOK
	auto itr = jobj.find(JSONKWD::USER::Profile_url);
	if(itr != jobj.end()) {
		_v.profURL = itr.value().toString();
		haveF |= Flag;
	}
}
Example #15
0
int DbModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    QJsonObject root = m_jsonDocument.object();
    QJsonValueRef _arrayRef = root.find(m_name).value();
    QJsonArray _arrayMain = _arrayRef.toArray();
    DEBUG << _arrayMain.count();
    return _arrayMain.count();
}
Example #16
0
void TwqUser::P_Prop::receiveInfo(const QJsonObject& jobj) {
	// Descriptionを持っていればOK
	if(jobj.contains(JSONKWD::USER::Description)) {
		_v.description = jobj.find(JSONKWD::USER::Description).value().toString();
		_v.nTweet = JtoInt(jobj, JSONKWD::USER::Statuses_count);
		_v.nFollow = JtoInt(jobj, JSONKWD::USER::Friends_count);
		_v.nFollower = JtoInt(jobj, JSONKWD::USER::Followers_count);
		haveF |= Flag;
	}
}
Example #17
0
//! Gets a reference to an object.
ObjectFront* VaultFront::object(
	const QJsonValue& objectInfoValue  //!< Json object that identifies the object. This can be ObjVer or ObjectVersion.
)
{
	// First identiy which type of id we have and
	// then get new front for the object.
	QJsonObject objectInfo = objectInfoValue.toObject();
	ObjectFront* front = 0;
	if( objectInfo.find( QString( "Title" ) ) != objectInfo.end() )
	{
		// This is an ObjectVersion Json object.
		QJsonValue objverJson = objectInfo[ "ObjVer" ];
		MFiles::ObjVer objver( objverJson.toObject() );
		front = this->newFront( objver.objId() );
	}
	else if( objectInfo.find( QString( "Type" ) ) != objectInfo.end() &&
			 objectInfo.find( QString( "Version" ) ) == objectInfo.end() )
	{
		// This is ObjID Json object.
		MFiles::ObjID objid( objectInfo );
		front = this->newFront( objid );
	}
	else if( objectInfo.find( QString( "Type" ) ) != objectInfo.end() &&
			 objectInfo.find( QString( "Version" ) ) != objectInfo.end() )
	{
		// This is ObjVer Json object.
		MFiles::ObjVer objver( objectInfo );
		front = this->newFront( objver.objId() );
	}
	else
	{
		// TODO: Error handling.
		front = 0;
	}

	// Set the ownership to JavaScript.
	if( front )
		QQmlEngine::setObjectOwnership( front, QQmlEngine::JavaScriptOwnership );

	// Return the front.
	return front;
}
Example #18
0
void DlgUser::showUser(UserID id) {
	_id = id;
	sgUser.getInfo<TwqUser::P_Picture, TwqUser::P_Prop>(id, _spVoid, [this,id](const TwqUser::P_Picture& p, const TwqUser::P_Prop& pp) {
		// ダイアログに色々設定する
		_ui->lbIcon->setPixmap(*p.profileIcon());
		_ui->lbName->setText(p.name());
		_ui->lbScName->setText(p.screenName());
		_ui->lbDescription->setText(pp.description());
		_ui->lbNTweets->setText(QString("%1").arg(pp.nTweet()));
		_ui->lbNFollow->setText(QString("%1").arg(pp.nFollow()));
		_ui->lbNFollower->setText(QString("%1").arg(pp.nFollower()));

		// ユーザのTLを読み込み
		_ui->tabTweet->showTL(id);
		_ui->tabTweet->refreshPage();

		// 対象ユーザと自分の関係を読み取る
		ParamMap pm;
		pm[TWAPIKWD::FR_SHOW::SourceId] = QString("%1").arg(sgNet.getMyID());
		pm[TWAPIKWD::FR_SHOW::TargetId] = QString("%1").arg(id);
		if(sgNet.getMyID() == id) {
		} else {
			sgNet.restAPI([id, this](QJsonDocument& jdoc) {
				QJsonObject jobj = jdoc.object();
				jobj = jobj.find("relationship").value().toObject();
				jobj = jobj.find("source").value().toObject();
				bool bF = jobj.find("following").value().toBool(),
					bFD = jobj.find("followed_by").value().toBool();

				_ui->btnBlock->setEnabled(bFD);
				_ui->btnFollow->setEnabled(!bF);
				_ui->btnUnfollow->setEnabled(bF);

				connect(_ui->btnFollow, SIGNAL(clicked()), this, SLOT(_makeFollow()));
				connect(_ui->btnUnfollow, SIGNAL(clicked()), this, SLOT(_makeUnFollow()));
				connect(_ui->btnBlock, SIGNAL(clicked()), this, SLOT(_makeBlock()));
			}, TWAPI::FR_SHOW, pm);
		}
		connect(_ui->tabTweet, SIGNAL(userOp(USEROP,QVariant)), this, SIGNAL(userOp(USEROP,QVariant)));
	});
}
	void SyntaxHighlighter::loadUserFormat(const QString& path) {
		QJsonDocument doc = _LoadJson(path);
		_formatMap.clear();
		QJsonObject root = doc.object();
		auto itr = root.find(JEnt::Highlight::highlights);
		if(itr != root.end()) {
			QJsonObject ent = itr.value().toObject();
			for(auto itr2 = ent.begin() ; itr2 != ent.end() ; itr2++)
				_formatMap.emplace(itr2.key().toStdString(), TextFormat(itr2.value().toObject()));
		}
		_refreshPairV();
	}
Example #20
0
void NetWork::dealLogIn(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	int code = obj.find("code").value().toInt();
	if (code != 200)
	{
		emit logInStatus(code, "");
		return;
	}
	QJsonObject::const_iterator it = obj.find("profile");
	if (it != obj.constEnd())
	{
		QJsonObject profileObj = it.value().toObject();
		m_userId = profileObj.find("userId").value().toInt();
		m_nickName = profileObj.find("nickname").value().toString();
		//	头像....
		logInStatus(code, m_nickName);
	}
}
Example #21
0
void NetWork::dealSeach(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray objList = resultObj.find("songs").value().toArray();

	m_list.clear();
	m_songIds.clear();
	for (int i = 0; i < objList.count(); i++)
	{
		QJsonObject songObj = objList.at(i).toObject();
		int songId = songObj.find("id").value().toInt();
		QString name = songObj.find("name").value().toString();
		QJsonArray artistsList = songObj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
			artists.append(artistsList.at(j).toObject().find("name").value().toString());
		QString album = songObj.find("album").value().toObject().find("name").value().toString();

		m_songIds.insert(songId, i);
		QStringList list;
		list << name << artists << album << "" << QString::number(songId);
		m_list.insert(i, list);
	}
}
Example #22
0
void NetWork::dealSongId(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonArray songObj = obj.find("songs").value().toArray();
	QString url = songObj.at(0).toObject().find("mp3Url").value().toString();
	int id = songObj.at(0).toObject().find("id").value().toInt();
	m_list[m_songIds.value(id)][3] = url;
	m_musicCount++;
	if (m_musicCount == m_songIds.count())
		emit musicInfo(m_list);
}
Example #23
0
static bool checkType(const QJsonObject& in, SceneDeserializer::Info* info)
{
    // Check that the "type" field is "sb"
    if (in.find("type") == in.end() || in["type"].toString() != "sb")
    {
        if (info)
            info->error_message = "Could not recognize file.<br><br>"
                                  "If this file was saved in Antimony 0.7.7 or earlier, "
                                  "open it in Antimony 0.7.8 and re-save to upgrade to "
                                  "the current file format.";
        return false;
    }
    return true;
}
Example #24
0
void NetWork::dealGetMusicList(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QStringList list;
	QVector<int> vector;
	//		获取歌单...
	QJsonObject::const_iterator it = obj.find("playlist");
	if (it != obj.constEnd())
	{
		QJsonArray array = it.value().toArray();
		for (int j = 0; j < array.count(); j++)
		{
			QJsonObject mObj = array.at(j).toObject();
			QString name = mObj.find("name").value().toString();
			int id = mObj.find("id").value().toInt();

			list.append(name);
			vector.append(id);
		}
	}
	emit musicList(list, vector);
}
Example #25
0
Signal ReadGraph(const QJsonObject& obj)
{
	Signal signal{};

	auto it = obj.find("name");
	if (it != obj.end())
	{
		const auto sigName = it->toString();
		signal.name = std::move(sigName);

		it = obj.find("color");
		if (it != obj.end())
			signal.graphic.color = it->toString();
		
		it = obj.find("visible");
		if (it != obj.end())
			signal.graphic.visible = it->toBool();
		
		it = obj.find("range");
		if (it != obj.end())
		{
			auto vec = ToVector(it->toArray());
			signal.graphic.rangeLower = vec.front();
			signal.graphic.rangeUpper = vec.back();
		}
		
		it = obj.find("values");
		if (it != obj.end() && it->isArray())
		{
			signal.y = ToVector(it->toArray());
		}
		
		it = obj.find("ticks");
		if (it != obj.end() && it->isArray())
		{
			signal.graphic.ticks = ToVector(it->toArray());
		}

		it = obj.find("tickLabels");
		if (it != obj.end() && it->isArray())
		{
			signal.graphic.tickLabels = ToStrVector(it->toArray());
		}
	}

	return signal;
}
Example #26
0
bool SceneDeserializer::run(QJsonObject in, Graph* graph, Info* info)
{
    if (!checkType(in, info))
        return false;

    if (!checkProtocol(in, info))
        return false;

    // Make sure there's a "nodes" array
    if (in.find("nodes") == in.end() || !in["nodes"].isArray())
    {
        if (info)
            info->error_message = "File does not contain any nodes.";
        return false;
    }

    deserializeGraph(in["nodes"].toArray(), graph, info);
    return true;
}
Example #27
0
void AnimationToJson::fromJsonObject(Animation &animation, const QJsonObject &object, const QString &fileName)
{
    animation.setFrameCount(object.find("frameCount").value().toInt());
    animation.setFps(object.find("fps").value().toInt());
    animation.setOrigin(pointFromJsonObject(object.find("origin").value().toObject()));

    QJsonArray keyFramesArray = object.find("keyFrames").value().toArray();
    for(auto keyFrameValue : keyFramesArray) {
        QJsonObject keyFrameObject = keyFrameValue.toObject();
        int frame = keyFrameObject.find("frame").value().toInt();

        auto keyFrame = new KeyFrame;
        fromJsonObject(*keyFrame, keyFrameObject.find("data").value().toObject(), fileName);
        animation.insertKeyFrame(frame, keyFrame);
    }
}
Example #28
0
QVariant DbModel::data(const QModelIndex &index, int role) const
{
    DEBUG << "index=" << index.row();
    if(index.isValid())
    {
        QHash<int, QByteArray> _roles = this->roleNames();
        QString _key = _roles.value(role);
        //        if((index.row() <= m_modelData.count() - 1) && index.row() >= 0)
        //        {
        //            QMap<QString, QString > _dataMap = m_modelData.at(index.row());
        //            return QVariant(_dataMap.value(_key));
        //        }
        QJsonObject root = m_jsonDocument.object();
        QJsonValueRef _arrayRef = root.find(m_name).value();
        QJsonArray _arrayMain = _arrayRef.toArray();
        QJsonValue val = _arrayMain.at(index.row());
        QVariantMap vm = val.toVariant().toMap();
        DEBUG << vm.value(_key);
        return QVariant(vm.value(_key));
    }
    return QVariant();
}
Example #29
0
void Ledger::historySuccess(QNetworkReply& reply) {
    // here we send a historyResult with some extra stuff in it
    // Namely, the styled text we'd like to show.  The issue is the
    // QML cannot do that easily since it doesn't know what the wallet
    // public key(s) are.  Let's keep it that way
    QByteArray response = reply.readAll();
    QJsonObject data = QJsonDocument::fromJson(response).object();
    qInfo(commerce) << "history" << "response" << QJsonDocument(data).toJson(QJsonDocument::Compact);

    // we will need the array of public keys from the wallet
    auto wallet = DependencyManager::get<Wallet>();
    auto keys = wallet->listPublicKeys();

    // now we need to loop through the transactions and add fancy text...
    auto historyArray = data.find("data").value().toObject().find("history").value().toArray();
    QJsonArray newHistoryArray;

    // TODO: do this with 0 copies if possible
    for (auto it = historyArray.begin(); it != historyArray.end(); it++) {
        // We have 2 text fields to synthesize, the one on the left is a listing
        // of the HFC in/out of your wallet.  The one on the right contains an explaination
        // of the transaction.  That could be just the memo (if it is a regular purchase), or
        // more text (plus the optional memo) if an hfc transfer
        auto valueObject = (*it).toObject();
        valueObject["hfc_text"] = hfcString(valueObject["sent_money"], valueObject["received_money"]);
        valueObject["transaction_text"] = transactionString(valueObject);
        newHistoryArray.push_back(valueObject);
    }
    // now copy the rest of the json -- this is inefficient
    // TODO: try to do this without making copies
    QJsonObject newData;
    newData["status"] = "success";
    QJsonObject newDataData;
    newDataData["history"] = newHistoryArray;
    newData["data"] = newDataData;
    newData["current_page"] = data["current_page"].toInt();
    emit historyResult(newData);
}
Example #30
0
bool ObjectContainer::verifyData(QJsonObject& object)
{
	// Verify mandatory keys for all types (name, type):
	auto nameIt = object.find("name");
	if (nameIt == object.end())
	{
		StaticLogger::logit("WARNING: Found no name for object in project file!");
		return false;
	}
	const QString& name = nameIt->toString();

	// Check if "type" key exists:
	auto typeIt = object.find("type");
	if (typeIt == object.end())
	{
		StaticLogger::logit("WARNING: Found no type for object '" + name + "' in project file!");
		return false;
	}

	ObjectType type = stringToObjectType(typeIt->toString().toStdString());

	// Insert all non-existent keys for all types with default values,
	if (!object.contains("id"))
	{
		object.insert("id", s_id);
		m_ids.insert(s_id++);
	}
	if (!object.contains("enabled"))
		object["enabled"] = true;

	if (type == ObjectType::Mesh)
	{
		// Verify mandatory keys for meshes
		if (!object.contains("obj-file"))
		{
			StaticLogger::logit("WARNING: Found no obj-file for Mesh '" + name + "' in project file!");
			return false;
		}

		// Insert all non-existent keys for meshes with default values
		if (!object.contains("position"))
			object["position"] = QJsonObject{ { "x", 0.0 }, { "y", 0.0 }, { "z", 0.0 } };
		if (!object.contains("scaling"))
			object["scaling"] = QJsonObject{ { "x", 1.0 }, { "y", 1.0 }, { "z", 1.0 } };
		if (!object.contains("rotation"))
			object["rotation"] = QJsonObject{ { "ax", 0.0 }, { "ay", 1.0 }, { "az", 0.0 }, { "angle", 0.0 } };
		if (!object.contains("shading"))
			object["shading"] = "Flat";
		if (!object.contains("color"))
			object["color"] = QJsonObject{ { "r", conf.mesh.dc.r }, { "g", conf.mesh.dc.g }, { "b", conf.mesh.dc.b } };
		if (!object.contains("voxelize"))
			object["voxelize"] = true;
		if (!object.contains("dynamics"))
			object["dynamics"] = true;
		if (!object.contains("density"))
			object["density"] = 2712.0; // Density of aluminium, Iron: 7850, Steel: 7850, Brass 60/40: 8520
		if (!object.contains("localRotAxis"))
			object["localRotAxis"] = QJsonObject{ { "enabled", false }, { "x", 0.0f }, { "y", 0.0f }, { "z", 0.0f } };
		if (!object.contains("showAccelArrow"))
			object["showAccelArrow"] = false;
	}
	if (type == ObjectType::VoxelGrid)
	{
		// Verify mandatory keys for voxel grids
		if (!object.contains("resolution"))
		{
			StaticLogger::logit("WARNING: Found no resolution for Voxel Grid '" + name + "' in project file!");
			return false;
		}
		if (!object.contains("gridSize"))
		{
			StaticLogger::logit("WARNING: Found no grid size for Voxel Grid '" + name + "' in project file!");
			return false;
		}

		// Insert all non-existent keys for voxel grids with default values
		if (!object.contains("position"))
			object["position"] = QJsonObject{ { "x", 0.0 }, { "y", 0.0 }, { "z", 0.0 } };
		if (!object.contains("scaling"))
			object["saling"] = QJsonObject{ { "x", 1.0 }, { "y", 1.0 }, { "z", 1.0 } };
		if (!object.contains("rotation"))
			object["rotation"] = QJsonObject{ { "ax", 0.0 }, { "ay", 1.0 }, { "az", 0.0 }, { "angle", 0.0 } };
		if (!object.contains("voxel"))
			object["voxel"] = VoxelGrid::getVoxelSettingsDefault();
		if (!object.contains("glyphs"))
		{
			QJsonObject res = object["resolution"].toObject();
			object["glyphs"] = VoxelGrid::getGlyphSettingsDefault(DirectX::XMUINT3(res["x"].toInt(), res["y"].toInt(), res["z"].toInt()));
		}
		if (!object.contains("volume"))
		{
			QJsonObject functions;
			for (const auto& metric : Metric::names)
				functions[metric] = TransferFunction().toJson();
			object["volume"] = QJsonObject{ { "enabled", false }, { "stepSize", 0.5 }, { "metric", Metric::toString(Metric::Magnitude)}, { "transferFunctions", functions } };
		}
		if (!object.contains("windTunnelSettings"))
			object["windTunnelSettings"] = ""; // Simulation uses default values
		if (!object.contains("runSimulation"))
			object["runSimulation"] = false;
		if (!object.contains("smoke"))
		{
			object["smoke"] = Simulator::getSmokeSettingsDefault();
		}
		if (!object.contains("lines"))
			object["lines"] = Simulator::getLineSettingsDefault();
	}

	return true;
}