Exemplo n.º 1
0
static QHash<QString, QString> _parseSvgPathsForLayers( const QString &projectFilename )
{
  QHash<QString, QString> projectFileSvgPaths;   // key = layer name, value = svg path

  QDomDocument doc;
  QFile projectFile( projectFilename );
  bool res = projectFile.open( QIODevice::ReadOnly );
  Q_ASSERT( res );
  res = doc.setContent( &projectFile );
  Q_ASSERT( res );
  projectFile.close();

  QDomElement docElem = doc.documentElement();
  QDomElement layersElem = docElem.firstChildElement( QStringLiteral( "projectlayers" ) );
  QDomElement layerElem = layersElem.firstChildElement();
  while ( !layerElem.isNull() )
  {
    QString layerName = layerElem.firstChildElement( QStringLiteral( "layername" ) ).text();
    QString svgPath;
    QDomElement symbolElem = layerElem.firstChildElement( QStringLiteral( "renderer-v2" ) ).firstChildElement( QStringLiteral( "symbols" ) ).firstChildElement( QStringLiteral( "symbol" ) ).firstChildElement( QStringLiteral( "layer" ) );
    QDomElement propElem = symbolElem.firstChildElement( QStringLiteral( "prop" ) );
    while ( !propElem.isNull() )
    {
      if ( propElem.attribute( QStringLiteral( "k" ) ) == QLatin1String( "name" ) )
      {
        svgPath = propElem.attribute( QStringLiteral( "v" ) );
        break;
      }
      propElem = propElem.nextSiblingElement( QStringLiteral( "prop" ) );
    }
    projectFileSvgPaths[layerName] = svgPath;
    layerElem = layerElem.nextSiblingElement();
  }
  return projectFileSvgPaths;
}
Exemplo n.º 2
0
/*
  Remove the file in the current project's project file.
  The file has already been removed from the filebrowser UI.
*/
void ProjectInfo::onRemoveFileRequest(QString filename)
{
  QFile projectFile(projectFilePath(mainWindow->currentProjectPath()));
  QDir projectDir(mainWindow->currentProjectPath());
  if(projectManager.removeFromProjectFile(projectDir.path(), filename))
    mainWindow->removeFileFromProject(projectDir.filePath(filename));
}
Exemplo n.º 3
0
void Project::load()
{
    QDir storageLocation(PeceraApplication::instance()->getProjectStorageLocation());
    if (!storageLocation.exists())
        return;

    QFile projectFile(storageLocation.filePath(m_name + ".db"));
    if (!projectFile.exists())
        return;

    // FIXME: Better error reporting
    // From: http://www.sqlite.org/c3ref/open.html -- The encoding used for
    // the filename argument of sqlite3_open() and  sqlite3_open_v2() must be
    // UTF-8, not whatever codepage is currently defined.
    sqlite3* database;
    int rc = sqlite3_open(projectFile.fileName().toUtf8().data(), &database);
    if (rc) {
        reportError(sqlite3_errmsg(database));
        sqlite3_close(database);
        return;
    }

    char* errorMessage;
    rc = sqlite3_exec(database, "SELECT * from files", fileReadFromStorageCallback, this, &errorMessage);
    if (rc)
        sqlite3_free(errorMessage);

    sqlite3_close(database);
}
Exemplo n.º 4
0
void QgsEmbedLayerDialog::changeProjectFile()
{
  QFile projectFile( mProjectFileLineEdit->text() );
  if ( !projectFile.exists() )
  {
    return;
  }

  if ( mProjectPath == mProjectFileLineEdit->text() )
  {
    //already up to date
    return;
  }

  //check we are not embedding from/to the same project
  if ( mProjectFileLineEdit->text() == QgsProject::instance()->fileName() )
  {
    QMessageBox::critical( 0, tr( "Recursive embeding not possible" ), tr( "It is not possible to embed layers / groups from the current project" ) );
    return;
  }

  mTreeWidget->clear();

  //parse project file and fill tree
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return;
  }

  QDomDocument projectDom;
  if ( !projectDom.setContent( &projectFile ) )
  {
    return;
  }

  QDomElement legendElem = projectDom.documentElement().firstChildElement( "legend" );
  if ( legendElem.isNull() )
  {
    return;
  }

  QDomNodeList legendChildren = legendElem.childNodes();
  QDomElement currentChildElem;

  for ( int i = 0; i < legendChildren.size(); ++i )
  {
    currentChildElem = legendChildren.at( i ).toElement();
    if ( currentChildElem.tagName() == "legendlayer" )
    {
      addLegendLayerToTreeWidget( currentChildElem );
    }
    else if ( currentChildElem.tagName() == "legendgroup" )
    {
      addLegendGroupToTreeWidget( currentChildElem );
    }
  }

  mProjectPath = mProjectFileLineEdit->text();
}
Exemplo n.º 5
0
bool Project::rename(const std::string& newName)
{
    if (isLoaded()) 
    {
        ofLogVerbose("Project::rename") << "renaming project \"" << getName() << "\" to \"" << newName + "\"";

        ofFile projectDir(getPath());

        std::string oldProjectName = getName();

        ofLogVerbose("Project::rename") << "project path: " << getPath() << " Renamed to: " << projectDir.getEnclosingDirectory() + newName;

        if (!projectDir.renameTo(projectDir.getEnclosingDirectory() + newName)) return false;

        _path = projectDir.getAbsolutePath();

        ofFile projectFile(projectDir.getAbsolutePath() + "/sketch/" + oldProjectName + "." + SKETCH_FILE_EXTENSION);


        // remove old executable
        ofDirectory bin;
        bin.listDir(projectDir.path() + "/bin");
        std::vector<ofFile> files = bin.getFiles();

        Poco::RegularExpression appExpression( oldProjectName + "(.exe|.app)*$", Poco::RegularExpression::RE_ANCHORED);

        for (unsigned int i = 0; i < files.size(); ++i)
        {
            std::string baseName = files[i].getBaseName();
            if (appExpression.match(baseName)) {
                files[i].remove(true);
                ofLogVerbose("Project::rename")
                    << "removed " << files[i].getFileName() << " from " << bin.getAbsolutePath() << endl;
            }
        }


        ofLogVerbose("Project::rename") << "projectDir path after rename: " << projectDir.getAbsolutePath();
        ofLogVerbose("Project::rename") << "projectFile path: " << projectFile.getAbsolutePath();

        if (!projectFile.renameTo(projectDir.getAbsolutePath() + "/sketch/" + newName + "." + SKETCH_FILE_EXTENSION)) return false;

        ofLogVerbose("Project::rename") << "projectFile path after rename: " << projectFile.getAbsolutePath();

        _data["projectFile"]["name"] = newName;

        _data["projectFile"]["fileName"] = newName + "." + SKETCH_FILE_EXTENSION;

        return true;
    }
    else
    {
        ofLogVerbose("Project::rename") << "Cannot rename project, it is not loaded.";
        return false;
    }

}
// Загрузка значений настроек из файла
// Если параметр не удастся загрузить - будет использоваться значение по умолчанию
bool ProjectSettingsLoader::load(const QString settingsFolder)
{
    bool result = false;

    mSettingsFolder = settingsFolder;
    QFile projectFile(mSettingsFolder + mSlash + mFileName);

    // Если файл не существует
    result = projectFile.exists();
    if (!result)
        return false;

    // Если нет прав на чтение
    result = projectFile.open(QIODevice::ReadOnly);
    if (!result)
        return false;

    QDomDocument mainXML;
    QDomElement rootElement;

    // Если файл - не xml
    result = mainXML.setContent(&projectFile);
    if (!result)
        return false;

    // Индикатор успешности парсинга
    bool readFail = false;

    // Используемые переменные
    qint32 contentInt = 0;
    QString contentString;

    // Настройки проекта
    rootElement = mainXML.documentElement().firstChildElement("projectSettings");
    if (rootElement.isNull())
        return false;

    // Количество закладок
    contentInt = rootElement.firstChildElement("unitsCount").text().toInt();
    if (!result)
        readFail = true;
    else
        mUnitsCount = contentInt;

    if (mUnitsCount < 1)
        readFail = true;

    // Название проекта
    contentString = rootElement.firstChildElement("projectName").text();
    if (!result)
        readFail = true;
    else
        mProjectName = contentString;

    return !readFail;
}
Exemplo n.º 7
0
TestOutputReader *QtTestConfiguration::outputReader(const QFutureInterface<TestResultPtr> &fi,
                                                    QProcess *app) const
{
    static const Core::Id id
            = Core::Id(Constants::FRAMEWORK_PREFIX).withSuffix(QtTest::Constants::FRAMEWORK_NAME);
    TestFrameworkManager *manager = TestFrameworkManager::instance();
    auto qtSettings = qSharedPointerCast<QtTestSettings>(manager->settingsForTestFramework(id));
    const QtTestOutputReader::OutputMode mode = qtSettings && qtSettings->useXMLOutput
            ? QtTestOutputReader::XML
            : QtTestOutputReader::PlainText;
    return new QtTestOutputReader(fi, app, buildDirectory(), projectFile(), mode, TestType::QtTest);
}
Exemplo n.º 8
0
void build_commands_write(const char* filename)
{
  TextFileOutputStream projectFile(filename);
  if(!projectFile.failed())
  {
    XMLStreamWriter writer(projectFile);
    ProjectXMLExporter projectExporter(g_build_project, g_build_tools);
    writer << "\n";
    projectExporter.exportXML(writer);
    writer << "\n";
  }
}
Exemplo n.º 9
0
void TestProjectFile::checkSuppressions()
{
    ProjectFile projectFile("/foo/bar/test.cppcheck");
    QList<Suppressions::Suppression> suppressions;
    suppressions.append(Suppressions::Suppression("id", "file.c"));
    suppressions.append(Suppressions::Suppression("id", "/abc/file.c"));
    projectFile.setSuppressions(suppressions);

    const QList<Suppressions::Suppression> s = projectFile.getCheckSuppressions();
    QCOMPARE(s.size(), 2);
    QCOMPARE(s[0].fileName, std::string("/foo/bar/file.c"));
    QCOMPARE(s[1].fileName, std::string("/abc/file.c"));
}
Exemplo n.º 10
0
void Player::Start()
{
#if URHO3D_SYSTEMUI
    ui::GetIO().IniFilename = nullptr;              // Disable of imgui.ini creation,
#endif
#if URHO3D_CSHARP
    if (Script* script = GetSubsystem<Script>())    // Graceful failure when managed runtime support is present but not in use.
        script->LoadRuntime();
#endif

    GetCache()->AddResourceRouter(new BakedResourceRouter(context_));

    context_->RegisterSubsystem(new SceneManager(context_));

    ea::shared_ptr<JSONFile> projectFile(GetCache()->GetResource<JSONFile>("Project.json", false));
    if (!projectFile)
    {
        projectFile = new JSONFile(context_);
        if (!projectFile->LoadFile(ToString("%s%s", APK, "Project.json")))
        {
            ErrorExit("Project.json missing.");
            return;
        }
    }

    const JSONValue& projectRoot = projectFile->GetRoot();
    if (!projectRoot.Contains("plugins"))
    {
        ErrorExit("Project.json does not have 'plugins' section.");
        return;
    }

    const JSONValue& plugins = projectRoot["plugins"];
    if (!LoadPlugins(plugins))
        ErrorExit("Loading of required plugins failed.");

    for (auto& plugin : plugins_)
        plugin->Start();

    // Load main scene.
    {
        SceneManager* manager = GetSubsystem<SceneManager>();
        Scene* scene = manager->CreateScene();

        if (scene->LoadFile(projectRoot["default-scene"].GetString()))
            manager->SetActiveScene(scene);
        else
            ErrorExit("Invalid scene file.");
    }
}
Exemplo n.º 11
0
void QgsServerProjectParser::sublayersOfEmbeddedGroup( const QString& projectFilePath, const QString& groupName, QSet<QString>& layerSet )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return;
  }

  QDomDocument xmlDoc;
  if ( !xmlDoc.setContent( &projectFile ) )
  {
    return;
  }

  //go to legend node
  QDomElement legendElem = xmlDoc.documentElement().firstChildElement( "legend" );
  if ( legendElem.isNull() )
  {
    return;
  }

  //get group node list of embedded project
  QDomNodeList groupNodes = legendElem.elementsByTagName( "legendgroup" );
  QDomElement groupElem;
  for ( int i = 0; i < groupNodes.size(); ++i )
  {
    groupElem = groupNodes.at( i ).toElement();
    if ( groupElem.attribute( "name" ) == groupName )
    {
      //get all subgroups and sublayers and add to layerSet
      QDomElement subElem;
      QDomNodeList subGroupList = groupElem.elementsByTagName( "legendgroup" );
      for ( int j = 0; j < subGroupList.size(); ++j )
      {
        subElem = subGroupList.at( j ).toElement();
        layerSet.insert( subElem.attribute( "name" ) );
      }
      QDomNodeList subLayerList = groupElem.elementsByTagName( "legendlayer" );
      for ( int j = 0; j < subLayerList.size(); ++j )
      {
        subElem = subLayerList.at( j ).toElement();
        layerSet.insert( subElem.attribute( "name" ) );
      }
    }
  }
}
Exemplo n.º 12
0
/*
  Return the buildtype of a file in the project file.
*/
QString ProjectManager::fileBuildType(QString projectPath, QString filename)
{
  QString buildtype;
  QDir dir(projectPath);
  QFile projectFile(dir.filePath(dir.dirName() + ".xml"));
  QDomDocument doc;
  if(doc.setContent(&projectFile))
  {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for(int i = 0; i < files.count(); i++)
    {
      if(files.at(i).toElement().text() == dir.relativeFilePath(filename))
        buildtype = files.at(i).toElement().attribute("type");
    }
  }
  return buildtype;
}
Exemplo n.º 13
0
bool
Project::load( const QString& fileName )
{
    Project* self = getInstance();
    if ( fileName.isEmpty() == true )
        return false;
    QFile   projectFile( fileName );
    if ( projectFile.exists() == false )
        return false;
    if ( self->closeProject() == false )
        return false;
    Project::destroyInstance();

    // Now let's start over with a clean state.
    self = getInstance();
    Core::getInstance()->onProjectLoaded( self );
    self->loadProject( fileName );

    return true;
}
Exemplo n.º 14
0
/*
  Toggle the file's build type in the project file.
  The filebrowser UI has already been updated.
*/
void ProjectInfo::onChangeBuildType(QString filename, QString newtype)
{
  QFile projectFile(projectFilePath( ));
  QDomDocument doc;
  if(doc.setContent(&projectFile))
  {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for(int i = 0; i < files.count(); i++)
    {
      if(files.at(i).toElement().text() == filename)
      {
        files.at(i).toElement().setAttribute("type", newtype);
        if(projectFile.open(QIODevice::WriteOnly|QFile::Text))
          projectFile.write(doc.toByteArray());
        return;
      }
    }
  }
}
Exemplo n.º 15
0
bool build_commands_parse(const char* filename)
{
  TextFileInputStream projectFile(filename);
  if(!projectFile.failed())
  {
    ProjectXMLConstructor projectConstructor(g_build_project, g_build_tools);
    RootXMLConstructor rootConstructor("project", projectConstructor, BUILDMENU_VERSION);
    XMLParser importer(rootConstructor);
    XMLStreamParser parser(projectFile);
    parser.exportXML(importer);

    if(rootConstructor.versionCompatible())
    {
      project_verify(g_build_project, g_build_tools);

      return true;
    }
    globalErrorStream() << "failed to parse build menu: " << makeQuoted(filename) << "\n";
  }
  return false;
}
Exemplo n.º 16
0
static QMap<QString, QString> getInitializedArguments()
{
    QMap<QString, QString> args;
    QStringList arguments = QCoreApplication::arguments();
    QString appName = arguments.first();
    arguments.removeFirst();

    QString projectFileName;
    foreach (const QString& arg, arguments) {
        if (arg.startsWith("--project-file")) {
            int split = arg.indexOf("=");
            if (split > 0)
                projectFileName = arg.mid(split + 1).trimmed();
            break;
        }
    }

    if (projectFileName.isNull())
        return args;

    if (!QFile::exists(projectFileName)) {
        std::cerr << qPrintable(appName) << ": Project file \"";
        std::cerr << qPrintable(projectFileName) << "\" not found.";
        std::cerr << std::endl;
        return args;
    }

    QFile projectFile(projectFileName);
    if (!projectFile.open(QIODevice::ReadOnly))
        return args;

    if (!processProjectFile(projectFile, args)) {
        std::cerr << qPrintable(appName) << ": first line of project file \"";
        std::cerr << qPrintable(projectFileName) << "\" must be the string \"[generator-project]\"";
        std::cerr << std::endl;
        return args;
    }

    return args;
}
Exemplo n.º 17
0
ProjectPtr clCxxWorkspace::DoAddProject(const wxString& path, wxString& errMsg)
{
    // Add the project
    ProjectPtr proj(new Project());

    // Convert the path to absolute path
    wxFileName projectFile(path);
    if(projectFile.IsRelative()) {
        projectFile.MakeAbsolute(m_fileName.GetPath());
    }

    if(!proj->Load(projectFile.GetFullPath())) {
        errMsg = wxT("Corrupted project file '");
        errMsg << projectFile.GetFullPath() << wxT("'");
        return NULL;
    }

    // Add an entry to the projects map
    m_projects.insert(std::make_pair(proj->GetName(), proj));
    proj->AssociateToWorkspace(this);
    return proj;
}
Exemplo n.º 18
0
/*
  Remove the file in the current project's project file.
  The file has already been removed from the filebrowser UI.
*/
void ProjectInfo::onRemoveFileRequest(QString filename)
{
  QFile projectFile(projectFilePath( ));
  QDomDocument doc;
  if(doc.setContent(&projectFile))
  {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for(int i = 0; i < files.count(); i++)
    {
      if(files.at(i).toElement().text() == filename)
      {
        QDomNode parent = files.at(i).parentNode();
        parent.removeChild(files.at(i));
        if(projectFile.open(QIODevice::WriteOnly|QFile::Text))
          projectFile.write(doc.toByteArray());
        mainWindow->removeFileFromProject(filename);
        return;
      }
    }
  }
}
Exemplo n.º 19
0
/*
  Remove a file from the project file.
  Don't delete the file.
*/
bool ProjectManager::removeFromProjectFile(const QString & projectPath, const QString & filePath)
{
  bool retval = false;
  QDomDocument doc;
  QDir dir(projectPath);
  QFile projectFile(dir.filePath(dir.dirName() + ".xml"));
  if (doc.setContent(&projectFile)) {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for (int i = 0; i < files.count(); i++) {
      if (files.at(i).toElement().text() == dir.relativeFilePath(filePath)) {
        QDomNode parent = files.at(i).parentNode();
        parent.removeChild(files.at(i));
        if (projectFile.open(QIODevice::WriteOnly|QFile::Text)) {
          projectFile.write(doc.toByteArray(2));
          retval = true;
        }
      }
    }
  }
  return retval;
}
Exemplo n.º 20
0
/*
  Add a filepath to this project's file list.
  It's path should be relative to the project directory.
*/
bool ProjectManager::addToProjectFile(const QString & projectPath, const QString & newFilePath)
{
  bool retval = false;
  QDomDocument newProjectDoc;
  QDir projectDir(projectPath);
  QFile projectFile(projectDir.filePath(projectDir.dirName() + ".xml"));
  // read in the existing file, and add a node to the "files" section
  if (newProjectDoc.setContent(&projectFile)) {
    projectFile.close();
    QDomElement newFileElement = newProjectDoc.createElement("file");
    QDomText newFilePathElement = newProjectDoc.createTextNode(projectDir.relativeFilePath(newFilePath));
    newFileElement.appendChild(newFilePathElement);
    newProjectDoc.elementsByTagName("files").at(0).toElement().appendChild(newFileElement);

    // write our newly manipulated file
    if (projectFile.open(QIODevice::WriteOnly | QFile::Text)) { // reopen as WriteOnly
      projectFile.write(newProjectDoc.toByteArray(2));
      projectFile.close();
      retval = true;
    }
  }
  return retval;
}
Exemplo n.º 21
0
void
Project::saveProject( const QString& fileName )
{
    QByteArray          projectString;

    QXmlStreamWriter    project( &projectString );

    project.setAutoFormatting( true );
    project.writeStartDocument();
    project.writeStartElement( "vlmc" );

    foreach ( ILoadSave* listener, m_loadSave )
        listener->save( project );

    project.writeEndElement();
    project.writeEndDocument();

    //FIXME: why not m_projectFile?!
    QFile   projectFile( fileName );
    projectFile.open( QFile::WriteOnly );
    projectFile.write( projectString );
    emit projectSaved();
}
Exemplo n.º 22
0
bool TupFileManager::save(const QString &fileName, TupProject *project)
{
    #ifdef K_DEBUG
        QString msg = "TupFileManager::save() - Saving file -> " + fileName;
            #ifdef Q_OS_WIN32
                qWarning() << msg;
            #else
                tWarning() << msg;
        #endif
    #endif

	/* 
    int indexPath = fileName.lastIndexOf(QDir::separator());
    int indexFile = fileName.length() - indexPath;
    QString name = fileName.right(indexFile - 1);
    int indexDot = name.lastIndexOf(".");
    name = name.left(indexDot);
    */
	
	QFileInfo info(fileName);
	QString name = info.baseName();	
    QString oldDirName = CACHE_DIR + project->projectName();
    QDir projectDir(oldDirName);

    if (name.compare(project->projectName()) != 0) {
        project->setProjectName(name);
        projectDir.setPath(CACHE_DIR + name);    
        project->library()->updatePaths(CACHE_DIR + name);
        if (!projectDir.exists()) {
            if (projectDir.rename(oldDirName, projectDir.path())) {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Directory renamed to -> " + projectDir.path(); 
                    #ifdef Q_OS_WIN32
                        qWarning() << msg;
                    #else
                        tWarning() << msg;
                    #endif
                #endif
            } else {
                // SQA: Check if these lines are really needed
                if (! projectDir.mkdir(projectDir.path())) {
                    #ifdef K_DEBUG
                        QString msg = "TupFileManager::save() - Error: Can't create path -> " + projectDir.path();
                        #ifdef Q_OS_WIN32
                            qDebug() << msg;
                        #else
                            tError() << msg;
                        #endif
                    #endif
                    return false;
                } else {
                    #ifdef K_DEBUG
                        QString msg = "TupFileManager::save() - Directory was created successfully -> " + projectDir.path();
                        #ifdef Q_OS_WIN32
                            qWarning() << msg;
                        #else
                            tWarning() << msg;
                        #endif
                    #endif
                }
            }
        }
    } else {
        if (!projectDir.exists()) {
            if (! projectDir.mkdir(projectDir.path())) {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Error: Can't create path -> " + projectDir.path();
                    #ifdef Q_OS_WIN32
                        qDebug() << msg;
                    #else
                        tError() << msg;
                    #endif
                #endif
                return false;
            } else {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Directory was created successfully -> " + projectDir.path();
                    #ifdef Q_OS_WIN32
                        qWarning() << msg;
                    #else
                        tWarning() << msg;
                    #endif
                #endif
            }
        }
    }

    {
     // Save project
     QFile projectFile(projectDir.path() + QDir::separator() + "project.tpp");

     if (projectFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
         QTextStream ts(&projectFile);
         QDomDocument doc;
         project->setProjectName(name);
         doc.appendChild(project->toXml(doc));
         ts << doc.toString();
         projectFile.close();
     } else {
         #ifdef K_DEBUG
             QString msg = "TupFileManager::save() - Error: Can't create file -> " + projectDir.path() + QDir::separator() + "project.tpp";
             #ifdef Q_OS_WIN32
                 qDebug() << msg;
             #else
                 tError() << msg;
             #endif
         #endif
     }
    }

    // Save scenes
    {
     int index = 0;
     int totalScenes = project->scenes().size();
     for (int i = 0; i < totalScenes; i++) {
          TupScene *scene = project->scenes().at(i);
          QDomDocument doc;
          doc.appendChild(scene->toXml(doc));
          QString scenePath = projectDir.path() + QDir::separator() + "scene" + QString::number(index) + ".tps";
          QFile sceneFile(scenePath);

          if (sceneFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
              QTextStream st(&sceneFile);
              st << doc.toString();
              index += 1;
              sceneFile.close();
          } else {
              #ifdef K_DEBUG
                  QString msg = "TupFileManager::save() - Error: Can't create file -> " + scenePath;
                  #ifdef Q_OS_WIN32
                      qDebug() << msg;
                  #else
                      tError() << msg;
                  #endif
              #endif
          }
     }
    }

    {
     // Save library
     QFile lbr(projectDir.path() + QDir::separator() + "library.tpl");

     if (lbr.open(QIODevice::WriteOnly | QIODevice::Text)) {
         QTextStream ts(&lbr);

         QDomDocument doc;
         doc.appendChild(project->library()->toXml(doc));

         ts << doc.toString();
         lbr.close();
     } else {
         #ifdef K_DEBUG
             QString msg = "TupFileManager::save() - Error: Can't create file -> " + projectDir.path() + QDir::separator() + "library.tpl";
             #ifdef Q_OS_WIN32
                 qDebug() << msg;
             #else
                 tError() << msg;
             #endif
         #endif
     }
    }

    TupPackageHandler packageHandler;
    bool ok = packageHandler.makePackage(projectDir.path(), fileName);

    if (ok) {
        #ifdef K_DEBUG
            QString msg = "TupFileManager::save() - Project saved in -> " + fileName;
            #ifdef Q_OS_WIN32
                qWarning() << msg;
            #else
                tWarning() << msg;
            #endif
        #endif
    } else {
        #ifdef K_DEBUG
            QString msg = "TupFileManager::save() - Error: Project couldn't be saved in -> " + fileName;
            #ifdef Q_OS_WIN32
                qDebug() << msg;
            #else
                tError() << msg;
            #endif
        #endif
    }

    return ok;
}
Exemplo n.º 23
0
/**
   presuming that the caller has already reset the map canvas, map registry, and legend
 */
bool QgsProject::read()
{
  clearError();

  std::auto_ptr< QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( "qgis" ) );

  if ( !imp_->file.open( QIODevice::ReadOnly ) )
  {
    imp_->file.close();

    setError( tr( "Unable to open %1" ).arg( imp_->file.fileName() ) );

    return false;
  }

  // location of problem associated with errorMsg
  int line, column;
  QString errorMsg;

  if ( !doc->setContent( &imp_->file, &errorMsg, &line, &column ) )
  {
    // want to make this class as GUI independent as possible; so commented out
#if 0
    QMessageBox::critical( 0, tr( "Project File Read Error" ),
                           tr( "%1 at line %2 column %3" ).arg( errorMsg ).arg( line ).arg( column ) );
#endif

    QString errorString = tr( "Project file read error: %1 at line %2 column %3" )
                          .arg( errorMsg ).arg( line ).arg( column );

    QgsDebugMsg( errorString );

    imp_->file.close();

    setError( tr( "%1 for file %2" ).arg( errorString ).arg( imp_->file.fileName() ) );

    return false;
  }

  imp_->file.close();


  QgsDebugMsg( "Opened document " + imp_->file.fileName() );
  QgsDebugMsg( "Project title: " + imp_->title );

  // get project version string, if any
  QgsProjectVersion fileVersion =  _getVersion( *doc );
  QgsProjectVersion thisVersion( QGis::QGIS_VERSION );

  if ( thisVersion > fileVersion )
  {
    QgsLogger::warning( "Loading a file that was saved with an older "
                        "version of qgis (saved in " + fileVersion.text() +
                        ", loaded in " + QGis::QGIS_VERSION +
                        "). Problems may occur." );

    QgsProjectFileTransform projectFile( *doc, fileVersion );

    //! Shows a warning when an old project file is read.
    emit oldProjectVersionWarning( fileVersion.text() );
    QgsDebugMsg( "Emitting oldProjectVersionWarning(oldVersion)." );

    projectFile.dump();

    projectFile.updateRevision( thisVersion );

    projectFile.dump();

  }

  // before we start loading everything, let's clear out the current set of
  // properties first so that we don't have the properties from the previous
  // project still hanging around

  imp_->clear();
  mEmbeddedLayers.clear();

  // now get any properties
  _getProperties( *doc, imp_->properties_ );

  QgsDebugMsg( QString::number( imp_->properties_.count() ) + " properties read" );

  dump_( imp_->properties_ );


  // restore the canvas' area of interest

  // now get project title
  _getTitle( *doc, imp_->title );


  // get the map layers
  QPair< bool, QList<QDomNode> > getMapLayersResults =  _getMapLayers( *doc );

  // review the integrity of the retrieved map layers
  bool clean = getMapLayersResults.first;

  if ( !clean )
  {
    QgsDebugMsg( "Unable to get map layers from project file." );

    if ( ! getMapLayersResults.second.isEmpty() )
    {
      QgsDebugMsg( "there are " + QString::number( getMapLayersResults.second.size() ) + " broken layers" );
    }

    // we let a custom handler to decide what to do with missing layers
    // (default implementation ignores them, there's also a GUI handler that lets user choose correct path)
    mBadLayerHandler->handleBadLayers( getMapLayersResults.second, *doc );
  }

  // read the project: used by map canvas and legend
  emit readProject( *doc );

  // if all went well, we're allegedly in pristine state
  if ( clean )
    dirty( false );

  return true;

} // QgsProject::read
Exemplo n.º 24
0
bool QgsProject::createEmbeddedLayer( const QString& layerId, const QString& projectFilePath, QList<QDomNode>& brokenNodes,
                                      QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList, bool saveFlag )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return false;
  }

  QDomDocument projectDocument;
  if ( !projectDocument.setContent( &projectFile ) )
  {
    return false;
  }

  //does project store pathes absolute or relative?
  bool useAbsolutePathes = true;
  QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" );
    if ( !absElem.isNull() )
    {
      useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0;
    }
  }

  QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" );
  if ( projectLayersElem.isNull() )
  {
    return false;
  }

  QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" );
  for ( int i = 0; i < mapLayerNodes.size(); ++i )
  {
    //get layer id
    QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
    QString id = mapLayerElem.firstChildElement( "id" ).text();
    if ( id == layerId )
    {
      //layer can be embedded only once
      if ( mapLayerElem.attribute( "embedded" ) == "1" )
      {
        return false;
      }

      mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );

      //change datasource path from relative to absolute if necessary
      if ( !useAbsolutePathes )
      {
        QDomElement provider = mapLayerElem.firstChildElement( "provider" );
        if ( provider.text() == "spatialite" )
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );

          QgsDataSourceURI uri( dsElem.text() );

          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + uri.database() );
          if ( absoluteDs.exists() )
          {
            uri.setDatabase( absoluteDs.absoluteFilePath() );
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( uri.uri() ) );
          }
        }
        else
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );
          QString debug( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          if ( absoluteDs.exists() )
          {
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( absoluteDs.absoluteFilePath() ) );
          }
        }
      }

      if ( addLayer( mapLayerElem, brokenNodes, vectorLayerList ) )
      {
        return true;
      }
      else
      {
        mEmbeddedLayers.remove( layerId );
        return false;
      }
    }
  }

  return false;
}
Exemplo n.º 25
0
void QgsProjectLayerGroupDialog::changeProjectFile()
{
  QFile projectFile( mProjectFileWidget->filePath() );
  if ( !projectFile.exists() )
  {
    return;
  }

  if ( mProjectPath == mProjectFileWidget->filePath() )
  {
    //already up to date
    return;
  }

  //check we are not embedding from/to the same project
  if ( mProjectFileWidget->isVisible() && mProjectFileWidget->filePath() == QgsProject::instance()->fileName() )
  {
    QMessageBox::critical( nullptr, tr( "Embed Layers and Groups" ), tr( "Recursive embedding is not supported. It is not possible to embed layers / groups from the current project." ) );
    return;
  }

  //parse project file and fill tree
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return;
  }

  std::unique_ptr<QgsProjectArchive> archive;

  QDomDocument projectDom;
  if ( QgsZipUtils::isZipFile( mProjectFileWidget->filePath() ) )
  {

    archive = qgis::make_unique<QgsProjectArchive>();

    // unzip the archive
    if ( !archive->unzip( mProjectFileWidget->filePath() ) )
    {
      return;
    }

    // test if zip provides a .qgs file
    if ( archive->projectFile().isEmpty() )
    {
      return;
    }

    projectFile.setFileName( archive->projectFile() );
    if ( !projectFile.exists() )
    {
      return;
    }
  }
  QString errorMessage;
  int errorLine;
  if ( !projectDom.setContent( &projectFile, &errorMessage, &errorLine ) )
  {
    QgsDebugMsg( QStringLiteral( "Error reading the project file %1 at line %2: %3" )
                 .arg( projectFile.fileName() )
                 .arg( errorLine )
                 .arg( errorMessage ) );
    return;
  }

  mRootGroup->removeAllChildren();

  QDomElement layerTreeElem = projectDom.documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) );
  if ( !layerTreeElem.isNull() )
  {
    mRootGroup->readChildrenFromXml( layerTreeElem, QgsReadWriteContext() );
  }
  else
  {
    QgsLayerTreeUtils::readOldLegend( mRootGroup, projectDom.documentElement().firstChildElement( QStringLiteral( "legend" ) ) );
  }

  if ( !mShowEmbeddedContent )
    removeEmbeddedNodes( mRootGroup );

  connect( mTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsProjectLayerGroupDialog::onTreeViewSelectionChanged );

  mProjectPath = mProjectFileWidget->filePath();
}
Exemplo n.º 26
0
	INT_PTR CALLBACK NewH86ProjectDlg::DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
		switch(uMsg){
		case WM_CLOSE:
			EndDialog(hWnd, WM_QUIT);
			break;
		case WM_COMMAND:
			switch(LOWORD(wParam)){
			case IDC_BROWSE_PROJECT_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"Hard86 Project files\0*.h86\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_PROJECT_PATH, path);
				}
				break;
			case IDC_BROWSE_BINARY_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"Binary files\0*.com\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_BINARY_PATH, path);
				}
				break;

			case IDC_BROWSE_FAS_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"FASM symbol files\0*.fas\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_FAS_PATH, path);
				}
				break;
			case IDOK:
			{
					wchar_t tmp_path[MAX_PATH]={ 0 };
					GetDlgItemText(hWnd, IDC_PROJECT_PATH, tmp_path, MAX_PATH);
					m_projectPath=tmp_path;
					GetDlgItemText(hWnd, IDC_BINARY_PATH, tmp_path, MAX_PATH);
					m_binPath=File::GetRelativePath(tmp_path, m_projectPath);
					GetDlgItemText(hWnd, IDC_FAS_PATH, tmp_path, MAX_PATH);
					m_fasPath=File::GetRelativePath(tmp_path, m_projectPath);
					try{
						xml_document<>* doc=new xml_document<>();
						doc->append_node(doc->allocate_node(node_element, "Hard86Project"));
						xml_node<>* node=doc->first_node();
						node->append_node(doc->allocate_node(node_element, "Variables"));
						node=node->first_node();
						node->append_node(doc->allocate_node(node_element, "LoadSegAddr"));
						node=node->first_node();
						node->append_attribute(doc->allocate_attribute("seg", doc->allocate_string("0")));
						node->append_attribute(doc->allocate_attribute("addr", doc->allocate_string("0")));
						node=node->parent();	// Variables
						node=node->parent();	// Hard86Project
						node->append_node(doc->allocate_node(node_element, "Paths"));
						node=node->first_node("Paths");
						node->append_attribute(doc->allocate_attribute("binaryPath", doc->allocate_string(wstrtostr(m_binPath).c_str())));
						node->append_attribute(doc->allocate_attribute("FASPath", doc->allocate_string(wstrtostr(m_fasPath).c_str())));
						node->append_attribute(doc->allocate_attribute("userVDevPath", ""));
						node=node->parent();	// Hard86Project
						node->append_node(doc->allocate_node(node_element, "VDevs"));
						node->append_node(doc->allocate_node(node_element, "BPList"));

						File projectFile(m_projectPath);
						if(projectFile.Exists()){
							projectFile.Delete();
						}
						projectFile.Create();
						projectFile.Open();
						
						char* xmlBuffer=new char[1024*1024];

						*(print(xmlBuffer, *doc, 0))=NULL;
						projectFile.Write(xmlBuffer);
						projectFile.Close();

						delete[] xmlBuffer;
					}
					catch(rapidxml::parse_error e){
						OUT_DEBUG("RapidXML error encountered");
					}
					Application::GetInstance()->mainFrame->LoadProjectToFrontend(m_projectPath);
					EndDialog(hWnd, WM_QUIT);
				}
				break;
			}
		default:
			return 0;
		}
		return 0;
	}
Exemplo n.º 27
0
void ProjectManager::onNewProject(QString name, QString logicFile, QString directory)
{
    if(name.isEmpty())
    {
        QString errorMsg("Please enter a name for your project.");
        emit(createProjectFailed(errorMsg));
        return;
    }

    if(logicFile.isEmpty())
    {
        QString errorMsg("Please enter a name for the main logic file of your project.");
        emit(createProjectFailed(errorMsg));
        return;
    }

    if(!logicFile.endsWith(".js", Qt::CaseInsensitive))
    {
        logicFile += ".js";
    }

    QUrl url = QUrl(directory);
    if(!url.isValid() || url.isEmpty())
    {
        QString errorMsg = QString("Directory at %1 is not a valid directory.")
                                    .arg(url.toLocalFile());

        emit(createProjectFailed(errorMsg));
        return;
    }

    QDir dir(url.toLocalFile());
    if(!dir.exists())
    {
        QString errorMsg = QString("Project directory at %1 doesn't exist.")
                                    .arg(url.toLocalFile());

        emit(createProjectFailed(errorMsg));
        return;
    }

    QString encodedName = QUrl::toPercentEncoding(name);
    if(!dir.mkdir(encodedName))
    {
        QString errorMsg = QString("Failed to create new project directory at %1/%2.")
                                    .arg(url.toLocalFile())
                                    .arg(encodedName);

        emit(createProjectFailed(errorMsg));
        return;
    }

    dir.cd(encodedName);
    dir.absolutePath();

    QString projectFileName = dir.absolutePath() + "/project.js";
    QFile projectFile(projectFileName);
    if(!projectFile.open(QIODevice::ReadWrite))
    {
        QString errorMsg = QString("Failed to open the new project file at %1.")
                                    .arg(projectFileName);

        emit(createProjectFailed(errorMsg));
        return;
    }

    QString newProjectContent = QString(sNewProjectTemplate).arg(name)
                                                            .arg(logicFile);
    projectFile.write(newProjectContent.toLocal8Bit());
    projectFile.close();

    QString encodedLogic = QUrl::toPercentEncoding(logicFile);
    QString mainFileName = dir.absolutePath() + "/" + encodedLogic;
    QFile mainFile(mainFileName);
    if(!mainFile.open(QIODevice::ReadWrite))
    {
        QString errorMsg = QString("Failed to open the new project file at %1.")
                                    .arg(mainFileName);

        emit(createProjectFailed(errorMsg));
        return;
    }

    mainFile.write(sLogicFileTemplate.toLocal8Bit());
    mainFile.close();
}
Exemplo n.º 28
0
/**
   @note it's presumed that the caller has already reset the map canvas, map
   registry, and legend
*/
bool QgsProject::read()
{
  std::auto_ptr< QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( "qgis" ) );

  if ( !imp_->file.open( QIODevice::ReadOnly ) )
  {
    imp_->file.close();     // even though we got an error, let's make
    // sure it's closed anyway

    throw QgsIOException( QObject::tr( "Unable to open " ) + imp_->file.fileName() );
  }

  // location of problem associated with errorMsg
  int line, column;
  QString errorMsg;

  if ( !doc->setContent( &imp_->file, &errorMsg, &line, &column ) )
  {
    // want to make this class as GUI independent as possible; so commented out
    // QMessageBox::critical( 0x0, "Project File Read Error",
    // errorMsg + " at line " + QString::number( line ) +
    // " column " + QString::number( column ) );

    QString errorString = QObject::tr( "Project file read error: " ) +
                          errorMsg + QObject::tr( " at line " ) + QString::number( line ) + QObject::tr( " column " ) +
                          QString::number( column );

    qDebug( "%s", errorString.toUtf8().constData() );

    imp_->file.close();

    throw QgsException( errorString + QObject::tr( " for file " ) + imp_->file.fileName() );
  }

  imp_->file.close();


  QgsDebugMsg( "Opened document " + imp_->file.fileName() );
  QgsDebugMsg( "Project title: " + imp_->title );

  // get project version string, if any
  QgsProjectVersion fileVersion =  _getVersion( *doc );
  QgsProjectVersion thisVersion( QGis::QGIS_VERSION );

  if ( thisVersion > fileVersion )
  {
    QgsLogger::warning( "Loading a file that was saved with an older "
                        "version of qgis (saved in " + fileVersion.text() +
                        ", loaded in " + QGis::QGIS_VERSION +
                        "). Problems may occur." );

    QgsProjectFileTransform projectFile( *doc, fileVersion );

    //! Shows a warning when an old project file is read.
    emit oldProjectVersionWarning( fileVersion.text() );
    QgsDebugMsg( "Emitting oldProjectVersionWarning(oldVersion)." );

    projectFile.dump();

    projectFile.updateRevision( thisVersion );

    projectFile.dump();

  }

  // before we start loading everything, let's clear out the current set of
  // properties first so that we don't have the properties from the previous
  // project still hanging around

  imp_->clear();

  // now get any properties
  _getProperties( *doc, imp_->properties_ );

  QgsDebugMsg( QString::number( imp_->properties_.count() ) + " properties read" );

  dump_( imp_->properties_ );


  // restore the canvas' area of interest

  // now get project title
  _getTitle( *doc, imp_->title );


  // get the map layers
  std::pair< bool, std::list<QDomNode> > getMapLayersResults =  _getMapLayers( *doc );

  // review the integrity of the retrieved map layers

  if ( ! getMapLayersResults.first )
  {
    QgsDebugMsg( "Unable to get map layers from project file." );

    if ( ! getMapLayersResults.second.empty() )
    {
      QgsDebugMsg( "there are " + QString::number( getMapLayersResults.second.size() ) + " broken layers" );
    }

    // Since we could be executing this from the test harness which
    // doesn't *have* layers -- nor a GUI for that matter -- we'll just
    // leave in the whining and boldly stomp on.
    emit readProject( *doc );
    throw QgsProjectBadLayerException( getMapLayersResults.second );

//         return false;
  }

  // read the project: used by map canvas and legend
  emit readProject( *doc );

  // can't be dirty since we're allegedly in pristine state
  dirty( false );

  return true;

} // QgsProject::read
Exemplo n.º 29
0
wxString ProjectListBox::GetAttributeString(int i, Project* project)
{
    wxString str;
    switch(i)
    {
        case 0:
            return wxString::Format(_T("%ld"),project->id);
        case 1:
            return project->path;
        case 2:
            if(project->target==Project::STITCHING)
            {
                //make prefix relative to project path
                wxFileName prefix(project->prefix);
                wxFileName projectFile(project->path);
                prefix.MakeRelativeTo(projectFile.GetPath());
                return prefix.GetFullPath();
            }
            else
            {
                return _("Assistant");
            };
        case 7:
            return project->GetStatusText();	
        //all following cases default to an empty string if file is missing
        case 3:
            if(project->status!=Project::MISSING)
            {
                if (project->modDate.IsValid())
                {
                    return project->modDate.Format();
                };
            };
            return wxEmptyString;
        case 4:
            if(project->status!=Project::MISSING)
            {
                str = GetLongerFormatName(project->options.outputImageType);
                str = str+wxT(" (.")+wxString::FromAscii(project->options.outputImageType.c_str())+wxT(")");
                return str;
            };
            return wxEmptyString;
        case 5:
            if(project->status!=Project::MISSING)
            {
                pano_projection_features proj;
                if (panoProjectionFeaturesQuery(project->options.getProjection(), &proj))
                {
                    wxString str2(proj.name, wxConvLocal);
                    return wxGetTranslation(str2);
                }
                else
                {
                    return _T("");
                }
            };
            return wxEmptyString;
        case 6:
            if(project->status!=Project::MISSING)
            {
                str = wxString() << project->options.getWidth();
                str = str+_T("x");
                str = str << project->options.getHeight();
                return str;
            }
            return wxEmptyString;
        default:
            return _T("");
    }
}
bool QExternalTestPrivate::createProjectFile()
{
    Q_ASSERT(!temporaryDir.isEmpty());

    QFile projectFile(temporaryDir + QLatin1String("/project.pro"));
    if (!projectFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
        std_err = projectFile.errorString().toLocal8Bit();
        return false;
    }

    projectFile.write(
        "TEMPLATE = app\n"
        "\n"
        "TARGET   = externaltest\n"
        "CONFIG   -= app_bundle\n"        // for the Mac
        "CONFIG   -= debug_and_release\n"
        "DESTDIR  = .\n"
        "OBJECTS_DIR = .\n"
        "UI_DIR   = .\n"
        "MOC_DIR  = .\n"
        "RCC_DIR  = .\n"
        "HEADERS  +=\n"
        "SOURCES  += project.cpp\n"
        "QT       -= core gui\n"
        "INCLUDEPATH += . ");
    projectFile.write(QFile::encodeName(QDir::currentPath()));

#ifndef QT_NO_DEBUG
    projectFile.write("\nCONFIG  += debug\n");
#else
    projectFile.write("\nCONFIG  += release\n");
#endif

    QByteArray extraSources = QFile::encodeName(extraProgramSources.join(" "));
    if (!extraSources.isEmpty()) {
        projectFile.write("SOURCES  += ");
        projectFile.write(extraSources);
        projectFile.putChar('\n');
    }

    // Add Qt modules
    if (qtModules & QExternalTest::QtCore)
        projectFile.write("QT += core\n");
    if (qtModules & QExternalTest::QtGui)
        projectFile.write("QT += gui\n");
    if (qtModules & QExternalTest::QtNetwork)
        projectFile.write("QT += network\n");
    if (qtModules & QExternalTest::QtXml)
        projectFile.write("QT += xml\n");
    if (qtModules & QExternalTest::QtXmlPatterns)
        projectFile.write("QT += xmlpatterns\n");
    if (qtModules & QExternalTest::QtOpenGL)
        projectFile.write("QT += opengl\n");
    if (qtModules & QExternalTest::QtSql)
        projectFile.write("QT += sql\n");
    if (qtModules & QExternalTest::Qt3Support)
        projectFile.write("QT += qt3support\n");
    if (qtModules & QExternalTest::QtSvg)
        projectFile.write("QT += svg\n");
    if (qtModules & QExternalTest::QtScript)
        projectFile.write("QT += script\n");
    if (qtModules & QExternalTest::QtTest)
        projectFile.write("QT += testlib\n");
    if (qtModules & QExternalTest::QtDBus)
        projectFile.write("QT += dbus\n");
    if (qtModules & QExternalTest::QtWebKit)
        projectFile.write("QT += webkit\n");
    if (qtModules & QExternalTest::Phonon)
        projectFile.write("QT += phonon\n");

    projectFile.write("\n### User-specified settings start ###\n");
    foreach (QByteArray line, qmakeLines) {
        projectFile.write(line);
        projectFile.write("\n");
    }