Пример #1
0
bool MeteorShowersMgr::loadCatalog(const QString& jsonPath)
{
	qDebug() << "MeteorShowersMgr: Loading catalog file:"
		 << QDir::toNativeSeparators(jsonPath);

	QFile jsonFile(jsonPath);
	if (!jsonFile.exists())
	{
		restoreDefaultCatalog(jsonPath);
	}

	if (!jsonFile.open(QIODevice::ReadOnly))
	{
		qWarning() << "MeteorShowersMgr: Cannot to open the catalog file!";
		return false;
	}

	QJsonObject json(QJsonDocument::fromJson(jsonFile.readAll()).object());
	jsonFile.close();

	if (json["shortName"].toString() != "meteor showers data"
		|| json["version"].toInt() != MS_CATALOG_VERSION)
	{
		qWarning()  << "MeteorShowersMgr: The current catalog is not compatible!";
		return false;
	}

	QVariantMap map = json["showers"].toObject().toVariantMap();
	m_meteorShowers->loadMeteorShowers(map);

	return true;
}
Пример #2
0
void ExtScript::readJsonFilters()
{
    QString fileName = QStandardPaths::locate(
        QStandardPaths::GenericDataLocation,
        QString(
            "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
    qCInfo(LOG_LIB) << "Filters file" << fileName;
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(LOG_LIB) << "Could not open" << fileName;
        return;
    }
    QString jsonText = jsonFile.readAll();
    jsonFile.close();

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonText.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError) {
        qCWarning(LOG_LIB) << "Parse error" << error.errorString();
        return;
    }
    jsonFilters = jsonDoc.toVariant().toMap();

    qCInfo(LOG_LIB) << "Filters" << jsonFilters;
}
Пример #3
0
void ModelBaker::exportScene() {
    auto fbxData = FBXWriter::encodeFBX(_rootNode);

    QString bakedModelURL = _bakedModelURL.toString();
    QFile bakedFile(bakedModelURL);

    if (!bakedFile.open(QIODevice::WriteOnly)) {
        handleError("Error opening " + bakedModelURL + " for writing");
        return;
    }

    bakedFile.write(fbxData);

    _outputFiles.push_back(bakedModelURL);

#ifdef HIFI_DUMP_FBX
    {
        FBXToJSON fbxToJSON;
        fbxToJSON << _rootNode;
        QFileInfo modelFile(_bakedModelURL.toString());
        QString outFilename(modelFile.dir().absolutePath() + "/" + modelFile.completeBaseName() + "_FBX.json");
        QFile jsonFile(outFilename);
        if (jsonFile.open(QIODevice::WriteOnly)) {
            jsonFile.write(fbxToJSON.str().c_str(), fbxToJSON.str().length());
            jsonFile.close();
        }
    }
#endif

    qCDebug(model_baking) << "Exported" << _modelURL << "with re-written paths to" << bakedModelURL;
}
    bool AEEditorPrefs::LoadPreferences(JSONValue& prefs)
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String path = GetPreferencesPath();

        if (!fileSystem->FileExists(path))
        {
            if (!CreateDefaultPreferences(path, prefs))
                return false;
        }
        else
        {
            SharedPtr<File> file(new File(context_, path, FILE_READ));
            SharedPtr<JSONFile> jsonFile(new JSONFile(context_));

            if (!jsonFile->BeginLoad(*file))
            {
                file->Close();
                if (!CreateDefaultPreferences(path, prefs))
                    return false;
            }
            else
            {
                prefs = jsonFile->GetRoot();
            }

            file->Close();
        }

        return true;
    }
Пример #5
0
/*

{
    "topFace" : "~/burp/faceZ/.png",
    "bottomFace" : "~/burp/faceZ-/.png",
    "leftFace" : "~/burp/faceY/.png",
    "rightFace" : "~/burp/faceY-/.png",
    "frontFace" : "~/burp/faceX/.png",
    "backFace" : "~/burp/faceX-/.png",
    "frameStart" : 1,
    "frameStop" : 499,
    "outputWidth" : 4094,
    "antialiasing" : 1,
    "aaPattern" : "grid",
    "frames": [
          {"cubemap": 1, "fov": 180, "pitch" : 0, "yaw" : 0, "roll" : 0, "zoom" : 0},
          {"cubemap": 1, "fov": 180, "pitch" : 1, "yaw" : 2, "roll" : 3, "zoom" : 4},
          {"cubemap": 1, "fov": 180, "pitch" : 2, "yaw" : 3, "roll" : 4, "zoom" : 1},
          {"cubemap": 1, "fov": 180, "pitch" : 3, "yaw" : 4, "roll" : 1, "zoom" : 2},
          {"cubemap": 1, "fov": 180, "pitch" : 4, "yaw" : 1, "roll" : 2, "zoom" : 3}
        ]
}

  */
void JSonIO::saveJSon(QString filePath){
    QFile jsonFile(filePath);
    if (!jsonFile.open(QIODevice::WriteOnly | QIODevice::Text)){
        parserState = 1;
        return;
    }

    QVariantMap root;
    root.insert("outputFile", getOutputFile());
    root.insert("topFace", getTopFace());
    root.insert("bottomFace", getBottomFace());
    root.insert("leftFace", getLeftFace());
    root.insert("rightFace", getRightFace());
    root.insert("frontFace", getFrontFace());
    root.insert("backFace", getBackFace());
    root.insert("frameStart", getFrameStart());
    root.insert("frameStop", getFrameStop());
    root.insert("outputWidth", getOutputWidth());
    root.insert("antialiasing", getAntialiasing());
    root.insert("aaPattern", getAaPattern());
    root.insert("frames", frames);

    QJson::Serializer serializer;
    QByteArray json = serializer.serialize(root);
    QTextStream out(&jsonFile);
    out.setCodec("UTF-8");
    out << json;
    jsonFile.close();
    qDebug() << "Saved to " << filePath;
}
bool ProjectBuildSettings::Load(const String& path)
{
    SharedPtr<File> file(new File(context_, path));
    if (!file->IsOpen())
        return false;

    SharedPtr<JSONFile> jsonFile(new JSONFile(context_));
    bool result = jsonFile->Load(*file);
    file->Close();

    if (!result)
        return false;

    JSONValue root = jsonFile->GetRoot();
    if (!root.IsObject())
        return false;

    macBuildSettings_->Read(root);
    windowsBuildSettings_->Read(root);
    webBuildSettings_->Read(root);
    androidBuildSettings_->Read(root);
    iosBuildSettings_->Read(root);

    return true;
}
Пример #7
0
void DTrash::extractJsonForItem(const QString &collPath, const QString &baseName, DTrashItemInfo &itemInfo)
{
    QString jsonFilePath = collPath + QLatin1Char('/') + TRASH_FOLDER +
                           QLatin1Char('/') + INFO_FOLDER + QLatin1Char('/') +
                           baseName + INFO_FILE_EXTENSION;

    QFile jsonFile(jsonFilePath);

    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QJsonDocument doc = QJsonDocument::fromJson(jsonFile.readAll());
    jsonFile.close();

    QJsonObject fileInfoObj = doc.object();

    itemInfo.jsonFilePath = jsonFilePath;

    itemInfo.collectionPath = fileInfoObj.value(PATH_JSON_KEY).toString();

    itemInfo.collectionRelativePath = fileInfoObj.value(PATH_JSON_KEY).toString()
                                      .replace(collPath, QLatin1String(""));

    itemInfo.deletionTimestamp = QDateTime::fromString(
                                 fileInfoObj.value(DELETIONTIMESTAMP_JSON_KEY).toString());
}
Пример #8
0
int main () {

    ifstream jsonFile("input.json");
    stringstream strStream;
    strStream << jsonFile.rdbuf();
    string jsonStr = strStream.str();
    string err;

    const Json json = Json::parse(jsonStr,err);
    if (!err.empty()) {
        printf ("Error in parsing input file: %s\n", err.c_str());
        return 0;
    }

    deom d(json["deom"]);

    const int inistate = json["proprho"]["inistate"].int_value();
    const int    nt = json["proprho"]["nt"].int_value();
    const double dt = json["proprho"]["dt"].number_value();
    const int    nk = json["proprho"]["nk"].int_value();

    cx_cube ddos = zeros<cx_cube>(size(d.ddos1));
    ddos(inistate,inistate,0) = 1;
    d.propagation (ddos, nt, dt, nk);

    return 0;
}
    bool AEEditorPrefs::CreateDefaultPreferences(String& path, JSONValue& prefs)
    {
        // Note there is some duplication here with the editor's
        // TypeScript preference code, this is due to the preferences for
        // the editor window needing to be available at window creation time
        // It could be better to split this all out to a native, scriptable
        // preferences object

        ATOMIC_LOGINFOF("Creating default Atomic Editor preferences: %s", path.CString());

        SharedPtr<JSONFile> jsonFile(new JSONFile(context_));

        JSONValue& root = jsonFile->GetRoot();

        root.Clear();
        root["recentProjects"] = JSONArray();

        JSONValue editorWindow;
        GetDefaultWindowPreferences(editorWindow, true);

        JSONValue playerWindow;
        GetDefaultWindowPreferences(playerWindow, false);

        root["editorWindow"] = editorWindow;
        root["playerWindow"] = playerWindow;

        prefs = root;

        SavePreferences(prefs);

        return true;
    }
Пример #10
0
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QString fileName;
    if (app.arguments().length() > 1) {
        fileName = app.arguments().at(1);
    } else {
        qWarning() << "Pass extracted json memory info dump as argument";
        return 0;
    }

    QtQuick2ApplicationViewer viewer;

    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open file:" << fileName;
        return 0;
    }

    viewer.setTitle(fileName);
    viewer.engine()->rootContext()->setContextProperty("jsonFile", QString(jsonFile.readAll()));
    viewer.setMainQmlFile(QStringLiteral("qml/memory-dump-reader.qml"));
    viewer.showExpanded();

    return app.exec();
}
Пример #11
0
void
FileStore::compressRide(RideFile*ride, QByteArray &data, QString name)
{
    // compress via a temporary file
    QTemporaryFile tempfile;
    tempfile.open();
    tempfile.close();

    // write as json
    QFile jsonFile(tempfile.fileName());
    if (RideFileFactory::instance().writeRideFile(NULL, ride, jsonFile, "json") == true) {

        // create a temp zip file
        QTemporaryFile zipFile;
        zipFile.open();
        zipFile.close();

        // add files using zip writer
        QString zipname = zipFile.fileName();
        ZipWriter writer(zipname);

        // read the ride file back and add to zip file
        jsonFile.open(QFile::ReadOnly);
        writer.addFile(name, jsonFile.readAll());
        jsonFile.close();
        writer.close();

        // now read in the zipfile
        QFile zip(zipname);
        zip.open(QFile::ReadOnly);
        data = zip.readAll();
        zip.close();
    }
}
Пример #12
0
bool AreaItemModel::loadJsonDocument(const char filename[]){
    QFile jsonFile(filename);
    if (! jsonFile.open(QIODevice::ReadOnly)){
        qWarning("Couldn't open area.json");

        return false;
    }
    else {
        QJsonParseError json_error;
        QByteArray dataArray = jsonFile.readAll();
        QJsonDocument jsonDoc(QJsonDocument::fromJson(dataArray, &json_error));
        if (json_error.error == QJsonParseError::NoError){
            if (jsonDoc.isArray()){
                QJsonArray jsonArray = jsonDoc.array();
                foreach(QJsonValue value, jsonArray){
                    if (value.isObject()){
                        QJsonObject jsonObj = value.toObject();
                        QString value = this->read(jsonObj, "label");
                        list << value;
                    }
                }

            }
        }
        jsonFile.close();
        return true;
    }
Пример #13
0
	void Serializer::serialize(QString file, Configuration* config)
	{
        Lemniscate* lemniscate = config->getLemniscate();
        QJsonObject lemniscateObj;
        lemniscate->write(lemniscateObj);
		QJsonObject jsonObject;
        jsonObject[KEY_LEMNISCATE] = lemniscateObj;

		QJsonObject panelObj;
		config->getPanel()->write(panelObj);
		jsonObject[KEY_PANEL] = panelObj;

		QJsonDocument jsonDocument(jsonObject);
		QFile jsonFile(file);
		if (!jsonFile.exists())
		{
			jsonFile.setFileName(file + ".json");
		}
		if (!jsonFile.open(QIODevice::WriteOnly))
		{
			throw ConfigSerializerException("error opening file for writing");
		}
		if (-1 == jsonFile.write(jsonDocument.toJson()))
		{
			throw ConfigSerializerException("error writing to file");
		}
	}
Пример #14
0
void BookmarksDialog::loadBookmarks()
{
	QVariantMap map;
	QFile jsonFile(bookmarksJsonPath);
	if (!jsonFile.open(QIODevice::ReadOnly))
		qWarning() << "[Bookmarks] cannot open" << QDir::toNativeSeparators(bookmarksJsonPath);
	else
	{
		try
		{
			map = StelJsonParser::parse(jsonFile.readAll()).toMap();
			jsonFile.close();

			bookmarksCollection.clear();
			QVariantMap bookmarksMap = map.value("bookmarks").toMap();
			int i = 0;
			for (auto bookmarkKey : bookmarksMap.keys())
			{
				QVariantMap bookmarkData = bookmarksMap.value(bookmarkKey).toMap();
				bookmark bm;

				QString JDs = "";

				bm.name = bookmarkData.value("name").toString();
				QString nameI18n = bookmarkData.value("nameI18n").toString();
				if (!nameI18n.isEmpty())
					bm.nameI18n = nameI18n;
				QString JD = bookmarkData.value("jd").toString();
				if (!JD.isEmpty())
				{
					bm.jd = JD;
					JDs = StelUtils::julianDayToISO8601String(JD.toDouble() + core->getUTCOffset(JD.toDouble())/24.).replace("T", " ");
				}
				QString Location = bookmarkData.value("location").toString();
				if (!Location.isEmpty())
					bm.location = Location;
				QString RA = bookmarkData.value("ra").toString();
				if (!RA.isEmpty())
					bm.ra = RA;
				QString Dec = bookmarkData.value("dec").toString();
				if (!Dec.isEmpty())
					bm.dec = Dec;

				bm.isVisibleMarker = bookmarkData.value("isVisibleMarker", false).toBool();
				double fov = bookmarkData.value("fov").toDouble();
				if (fov > 0.0)
					bm.fov = fov;

				bookmarksCollection.insert(bookmarkKey, bm);
				addModelRow(i, bookmarkKey, bm.name, bm.nameI18n, JDs, Location);
				i++;
			}
		}
		catch (std::runtime_error &e)
		{
			qDebug() << "[Bookmarks] File format is wrong! Error: " << e.what();
			return;
		}
	}
}
Пример #15
0
void Index::RebuildIndex() const
{
	std::ifstream file (m_name);

	std::ofstream ofile;
	char line[2048];
	IndexItem item;
	long itemCount = 0;
	if (file.is_open())
	{
		std::ofstream indexFile (m_indexName, std::ios::out | std::ios::binary | std::ios::trunc);
		std::ofstream jsonFile (m_jsonName, std::ios::out | std::ios::trunc);

		std::ifstream::pos_type first = file.tellg();
		int emptyLineCounter = 0;
		jsonFile << "[";
		while ( file.good() )
		{
			if(item.empty())
			{
				item.offset =  file.tellg().seekpos();
			}

			std::streamsize count = file.getline(line, sizeof(line)).gcount();
			if(count <= 1)
			{
				if(++emptyLineCounter == 2)
				{
					// сохраняем описатель документа.
					indexFile << static_cast<const Item&>(item);
					jsonFile << static_cast<const JsonItem&>(item) << ",";
					item.clear();
					emptyLineCounter = 0;
					itemCount++;
				}
			}
			else
			{
				item.length+=static_cast<short>(count);
				item.lineSizes.push_back(static_cast<short>(count-1));
			}
		}
		if(!item.empty())
		{
			indexFile << Item(item);
			jsonFile << JsonItem(item);
		}
		jsonFile << "]";

		file.close();
		indexFile.close();
		jsonFile.close();
	}
	else
	{
		throw std::runtime_error("Repository file not found.");
	}
}
void GetFaceResourceTest::testFaces(const QString& fileName) {
    QString base = testResources + QDir::separator() + fileName;
    QFile file(base + ".jpg");
    QJsonDocument current;
    int status = faceResource->getJSONFaces(&file, current);
    file.close();
    QCOMPARE(HttpHeaders::STATUS_SUCCESS, status);

    QFile jsonFile(base + ".json");

    QVERIFY(jsonFile.exists());

    jsonFile.open(QIODevice::ReadOnly | QIODevice::Text);
    QJsonDocument expected = QJsonDocument().fromJson(jsonFile.readAll());
    jsonFile.close();

    QJsonArray currentArray = current.array();
    QJsonArray expectedArray = expected.array();

    // Make sure we're not comparing zero to zero
    QVERIFY(expectedArray.size() > 0);
    QCOMPARE(currentArray.size(), expectedArray.size());

    for (int i=0; i<currentArray.size(); ++i) {
        QJsonObject cFaceParts = currentArray[i].toObject();
        QJsonObject eFaceParts = expectedArray[i].toObject();

        QJsonObject cFace = eFaceParts["face"].toObject();
        QJsonObject eFace = eFaceParts["face"].toObject();
        compareDoubles(cFace["x1"].toDouble(), eFace["x1"].toDouble(), 0.0001);
        compareDoubles(cFace["x2"].toDouble(), eFace["x2"].toDouble(), 0.0001);
        compareDoubles(cFace["y1"].toDouble(), eFace["y1"].toDouble(), 0.0001);
        compareDoubles(cFace["y2"].toDouble(), eFace["y2"].toDouble(), 0.0001);

        QCOMPARE(cFaceParts["pose"], eFaceParts["pose"]);
        QCOMPARE(cFaceParts["model"], eFaceParts["model"]);

        QJsonObject cParts = cFaceParts["parts"].toObject();
        QJsonObject eParts = eFaceParts["parts"].toObject();

        QCOMPARE(cParts.size(), eParts.size());

        for (QJsonObject::const_iterator cIter = cParts.constBegin(); cIter != cParts.constEnd(); ++cIter) {
            QJsonArray cSubpart = cIter.value().toArray();
            QJsonArray eSubpart = cParts[cIter.key()].toArray();

            QCOMPARE(cSubpart.size(), eSubpart.size());

            for (int i=0; i<cSubpart.size(); ++i) {
                QJsonObject cPart = cSubpart[i].toObject();
                QJsonObject ePart = eSubpart[i].toObject();
                compareDoubles(cPart["x"].toDouble(), ePart["x"].toDouble(), 0.0001);
                compareDoubles(cPart["y"].toDouble(), ePart["y"].toDouble(), 0.0001);
                QCOMPARE(cPart["num"], ePart["num"]);
            }
        }
    }
}
Пример #17
0
AudioLayer::AudioLayer(QQmlApplicationEngine *engine, QObject *parent):
    QObject(parent),
    m_engine(nullptr)
{
    this->m_inputState = AkElement::ElementStateNull;
    this->setQmlEngine(engine);
    this->m_pipeline = AkElement::create("Bin", "pipeline");

    if (this->m_pipeline) {
        QFile jsonFile(":/Webcamoid/share/audiopipeline.json");
        jsonFile.open(QFile::ReadOnly);
        QString description(jsonFile.readAll());
        jsonFile.close();

        this->m_pipeline->setProperty("description", description);

        QMetaObject::invokeMethod(this->m_pipeline.data(),
                                  "element",
                                  Q_RETURN_ARG(AkElementPtr, this->m_audioOut),
                                  Q_ARG(QString, "audioOut"));
        QMetaObject::invokeMethod(this->m_pipeline.data(),
                                  "element",
                                  Q_RETURN_ARG(AkElementPtr, this->m_audioIn),
                                  Q_ARG(QString, "audioIn"));
        QMetaObject::invokeMethod(this->m_pipeline.data(),
                                  "element",
                                  Q_RETURN_ARG(AkElementPtr, this->m_audioGenerator),
                                  Q_ARG(QString, "audioGenerator"));
        QMetaObject::invokeMethod(this->m_pipeline.data(),
                                  "element",
                                  Q_RETURN_ARG(AkElementPtr, this->m_audioSwitch),
                                  Q_ARG(QString, "audioSwitch"));
    }

    if (this->m_audioOut) {
        QString device = this->m_audioOut->property("defaultOutput").toString();
        this->m_audioOut->setProperty("device", device);
        this->m_outputDeviceCaps = this->m_audioOut->property("caps").value<AkCaps>();

        QObject::connect(this->m_audioOut.data(),
                         SIGNAL(deviceChanged(const QString &)),
                         this,
                         SIGNAL(audioOutputChanged(const QString &)));
        QObject::connect(this->m_audioOut.data(),
                         SIGNAL(capsChanged(const AkCaps &)),
                         this,
                         SLOT(setOutputDeviceCaps(const AkCaps &)));
        QObject::connect(this->m_audioOut.data(),
                         SIGNAL(outputsChanged(const QStringList &)),
                         this,
                         SIGNAL(outputsChanged(const QStringList &)));
        QObject::connect(this->m_audioOut.data(),
                         SIGNAL(stateChanged(AkElement::ElementState)),
                         this,
                         SIGNAL(outputStateChanged(AkElement::ElementState)));
    }
QJsonObject EntityMap::parseJSON(QString ref)
{
    QFile jsonFile(ref);
    if(!jsonFile.open(QFile::ReadOnly | QFile::Text)){
        qCritical() << "Unable to read File: "<< ref;
        qApp->exit(EXIT_FAILURE);
    }
    QByteArray data = jsonFile.readAll();
    QJsonDocument jsonData(QJsonDocument::fromJson(data));

    return jsonData.object();
}
Пример #19
0
void AEPreferences::Read()
{
    rapidjson::Document document;

    String filepath = GetPreferencesFullPath();

    File jsonFile(context_, filepath);

    if (!jsonFile.IsOpen())
        return;

    String json;
    jsonFile.ReadText(json);

    if (!json.Length())
        return;

    if (document.Parse<0>(json.CString()).HasParseError())
    {
        LOGERRORF("Could not parse JSON data from %s", filepath.CString());
        return;
    }

    Clear();

    const Value::Member* recent_files = document.FindMember("recent_files");
    if (recent_files && recent_files->value.IsArray())
    {
        for (Value::ConstValueIterator itr = recent_files->value.Begin(); itr != recent_files->value.End(); itr++)
        {
             if (!(*itr).IsString())
                 continue;

            String path(itr->GetString());
            recentProjects_.Push(path.CString());
        }
    }

    const Value::Member* android_sdk_path = document.FindMember("android_sdk_path");
    if (android_sdk_path && android_sdk_path->value.IsString())
        androidSDKPath_ = android_sdk_path->value.GetString();

    const Value::Member* jdk_root_path = document.FindMember("jdk_root_path");
    if (jdk_root_path && jdk_root_path->value.IsString())
        jdkRootPath_ = jdk_root_path->value.GetString();

    const Value::Member* ant_path = document.FindMember("ant_path");
    if (ant_path && ant_path->value.IsString())
        antPath_ = ant_path->value.GetString();

    UpdateRecentFiles(false);

}
Пример #20
0
bool JsonSnippetFile::load(const QString &fileName, SnippetCollection *collection)
{
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }

    QJsonDocument doc = QJsonDocument::fromJson(jsonFile.readAll());

    JsonSnippetTranslator translator;
    return translator.processDocument(doc, collection);
}
void ProjectBuildSettings::Save(const String& path)
{
    SharedPtr<JSONFile> jsonFile(new JSONFile(context_));

    jsonFile->CreateRoot();

    SharedPtr<File> file(new File(context_, path, FILE_WRITE));

    jsonFile->Save(*file, String("   "));

    file->Close();

}
Пример #22
0
void BookmarksDialog::saveBookmarks() const
{
	if (bookmarksJsonPath.isEmpty())
	{
		qWarning() << "[Bookmarks] Error saving bookmarks";
		return;
	}
	QFile jsonFile(bookmarksJsonPath);
	if(!jsonFile.open(QFile::WriteOnly|QFile::Text))
	{
		qWarning() << "[Bookmarks] bookmarks can not be saved. A file can not be open for writing:"
			   << QDir::toNativeSeparators(bookmarksJsonPath);
		return;
	}

	QVariantMap bookmarksDataList;
	QHashIterator<QString, bookmark> i(bookmarksCollection);
	while (i.hasNext())
	{
	    i.next();

	    bookmark sp = i.value();
	    QVariantMap bm;
	    bm.insert("name", sp.name);
	    if (!sp.nameI18n.isEmpty())
		    bm.insert("nameI18n", sp.nameI18n);
	    if (!sp.ra.isEmpty())
		    bm.insert("ra", sp.ra);
	    if (!sp.dec.isEmpty())
		    bm.insert("dec", sp.dec);
	    if (!sp.jd.isEmpty())
		    bm.insert("jd", sp.jd);
	    if (!sp.location.isEmpty())
		    bm.insert("location", sp.location);
	    if (sp.isVisibleMarker)
		    bm.insert("isVisibleMarker", sp.isVisibleMarker);
	    if (sp.fov > 0.0)
		    bm.insert("fov", sp.fov);

	    bookmarksDataList.insert(i.key(), bm);
	}

	QVariantMap bmList;
	bmList.insert("bookmarks", bookmarksDataList);

	//Convert the tree to JSON
	StelJsonParser::write(bmList, &jsonFile);
	jsonFile.flush();
	jsonFile.close();
}
void JsonViewerApplication::loadJson(QUrl jsonPath){
    QFile jsonFile(jsonPath.toLocalFile());
    jsonFile.open(QIODevice::ReadOnly);
    QByteArray data = jsonFile.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    GenAlgObject obj(doc.object());
    QImage temp(300,300,QImage::Format_ARGB32);
    obj.drawResult(&temp);
    imageProvider.image = temp;
    QVariant returnedValue;
    QMetaObject::invokeMethod(rootQML, "updateImage",
            Q_RETURN_ARG(QVariant, returnedValue));
    jsonFile.close();
}
Пример #24
0
bool JsonSnippetFile::save(const QString &fileName, SnippetCollection *collection)
{
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }

    JsonSnippetTranslator translator;
    QJsonDocument doc = translator.createDocument(collection);

    QTextStream out(&jsonFile);
    out << doc.toJson();

    return true;
}
Пример #25
0
bool JSONFileLoader::Save(const std::string& szFileName, json_spirit::mObject tData, const std::string& szSubDirectory, bool bOverwrite, bool bIsBinary)
{
	bool bSuccess = false;

	if (!szFileName.empty())
	{
		std::string szDirPath = APP_DATA_PATH + "\\";
		if (!szSubDirectory.empty())
		{
			szDirPath += szSubDirectory + "\\";
			boost::filesystem::path newDir(szDirPath);

			if (!boost::filesystem::exists(newDir))
			{
				if (!boost::filesystem::create_directory(newDir))
				{
					bSuccess = false;
				}
			}
		}

		if (!szDirPath.empty())
		{
			std::string szDirFile = szDirPath + szFileName;
			boost::filesystem::path dirFile(szDirFile);
			if ((!boost::filesystem::exists(dirFile)) || (bOverwrite && boost::filesystem::is_regular_file(dirFile)))
			{
				if (!bIsBinary)
				{
					std::ofstream jsonFile(szDirFile);
					json_spirit::write(tData, jsonFile, json_spirit::Output_options::pretty_print);
					jsonFile.close();
					
				}
				else
				{
					std::ofstream jsonBinaryFile(szDirFile, std::ios::binary);
					json_spirit::write(tData, jsonBinaryFile, json_spirit::Output_options::none);
					jsonBinaryFile.close();
				}

				bSuccess = true;
			}
		}
	}

	return bSuccess;
}
Пример #26
0
QJsonDocument TestHelper::readJsonFile(const QString &filename, QJsonParseError *error)
{
    QString filepath = filename;
    QFile jsonFile(filepath);
    if (!jsonFile.exists()) {
        if (error) {
            error->error = QJsonParseError::MissingObject;
            error->offset = 0;
        }
        return QJsonDocument();
    }
    jsonFile.open(QIODevice::ReadOnly);
    QByteArray json = jsonFile.readAll();
    QJsonDocument doc(QJsonDocument::fromJson(json, error));
    return doc;
}
void JsArchitecturalMetricsConfig::loadMetricsInfo()
{
    _ui->scriptsMetricsTable->setColumnWidth(1, 240);
    _ui->scriptsMetricsTable->setColumnWidth(2, 110);

    QFile jsonFile(_jsArchitecturalMetricsDir+"/"+ _jsonFileName);
    QString contentJsonFile;

    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning("Couldn't open json file.");
        return;
    }

    contentJsonFile = jsonFile.readAll();
    jsonFile.close();

    QJsonDocument jsonDocument = QJsonDocument::fromJson(contentJsonFile.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();

    QString scriptMetricDefault = jsonObject.value("MetricDefault").toString();

    QJsonArray scriptsList = jsonObject.value(QString("ScriptsFile")).toArray();

    for(int i = 0; i < scriptsList.size(); i++) {

        QString metricName;
        QString shortDescription;
        QString scriptFile;

        metricName = scriptsList.at(i).toObject().value("MetricName").toString();
        shortDescription = scriptsList.at(i).toObject().value("ShortDescription").toString();
        scriptFile = scriptsList.at(i).toObject().value("ScriptFile").toString();

        _ui->scriptsMetricsTable->insertRow(0);

        _ui->scriptsMetricsTable->setItem(0, 0, new QTableWidgetItem(metricName));
        _ui->scriptsMetricsTable->setItem(0, 1, new QTableWidgetItem(shortDescription));
        _ui->scriptsMetricsTable->setItem(0, 2, new QTableWidgetItem(scriptFile));

        _ui->metricDefaultComboBox->addItem(metricName,QVariant::fromValue(scriptFile));

        if(scriptFile == scriptMetricDefault){
            _ui->scriptsMetricsTable->selectRow(0);
            _ui->metricDefaultComboBox->setCurrentIndex(i);
        }
    }
}
Пример #28
0
bool JsonSerializer::serialize(
        const std::string& fileName,
        const MeshCrew& crew,
        const Mesh& mesh) const
{
    QJsonObject meshObj;
    meshObj.insert(MESH_MODEL_TAG, mesh.modelName.c_str());

    // Vertices
    QJsonArray vertArray;
    for(const MeshVert& vert : mesh.verts)
        vertArray.append(toJson(vert.p));
    meshObj.insert(MESH_VERTS_TAG, vertArray);


    // Tetrahedra
    QJsonArray tetArray;
    for(const MeshTet& elem : mesh.tets)
        tetArray.append(toJson(elem));
    meshObj.insert(MESH_TETS_TAG, tetArray);


    // Prisms
    QJsonArray priArray;
    for(const MeshPri& elem : mesh.pris)
        priArray.append(toJson(elem));
    meshObj.insert(MESH_PRIS_TAG, priArray);


    // Hexahedra
    QJsonArray hexArray;
    for(const MeshHex& elem : mesh.hexs)
        hexArray.append(toJson(elem));
    meshObj.insert(MESH_HEXS_TAG, hexArray);


    QJsonDocument doc(meshObj);
    QFile jsonFile(fileName.c_str());
    if(!jsonFile.open(QFile::WriteOnly))
        return false;

    jsonFile.write(doc.toJson(QJsonDocument::Compact));
    return true;
}
void ProjectBuildSettings::Save(const String& path)
{
    SharedPtr<JSONFile> jsonFile(new JSONFile(context_));

    JSONValue& root = jsonFile->GetRoot();

    SharedPtr<File> file(new File(context_, path, FILE_WRITE));

    macBuildSettings_->Write(root);
    windowsBuildSettings_->Write(root);
    webBuildSettings_->Write(root);
    androidBuildSettings_->Write(root);
    iosBuildSettings_->Write(root);

    jsonFile->Save(*file, String("   "));

    file->Close();

}
Пример #30
0
    bool AEEditorPrefs::SavePreferences(JSONValue& prefs)
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String path = GetPreferencesPath();

        SharedPtr<File> file(new File(context_, path, FILE_WRITE));
        SharedPtr<JSONFile> jsonFile(new JSONFile(context_));

        jsonFile->GetRoot() = prefs;

        if (!file->IsOpen())
        {
            ATOMIC_LOGERRORF("Unable to open Atomic Editor preferences for writing: %s", path.CString());
            return false;
        }

        jsonFile->Save(*file, "   ");
        file->Close();

        return true;
    }