Beispiel #1
0
std::string
GetNewTemplateSpecificationName()
{
#if defined(_WIN32)
    std::string templateFile(GetUserVisItDirectory() + "movietemplates\\new.mt");
#else
    std::string templateFile(GetUserVisItDirectory() + "movietemplates/new.mt");
#endif
    return templateFile;
}
Beispiel #2
0
bool dtkPluginGenerator::generateCMakeLists(void)
{
    QFile targetFile(d->target.absoluteFilePath("CMakeLists.txt"));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing";
	return false;
    }

    QFile templateFile(":template/cmake");

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);

    stream << QString(templateFile.readAll()).arg(QString(d->plugin));

    targetFile.close();

    templateFile.close();

    return true;
}
bool medPluginGenerator::generateTypeIOSourceFile()
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".cpp")));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString(d->plugin).append(".cpp") << "for writing";
        return false;
    }

    QFile templateFile(QString(":template/%1/type.cpp").arg(d->pluginFamily));

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);
    stream << QString(templateFile.readAll())
    .arg(d->plugin)
    .arg(d->type);

    targetFile.close();

    templateFile.close();

    return true;
}
bool medPluginGenerator::generateExportHeaderFile()
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("PluginExport.h")));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString(d->plugin).append("PluginExport.h") << "for writing";
        return false;
    }
    
    QFile templateFile(":template/export.h");
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll()).arg(d->plugin).arg(d->plugin.toUpper());
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
bool medPluginGenerator::generateRPISourceFile()
{
    QString baseName = QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper());
    QFile targetFile(d->target.absoluteFilePath(QString("rpi" + baseName).append(".hxx")));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString("rpi" + baseName).append(".hxx") << "for writing";
        return false;
    }
    
    QFile templateFile(QString(":template/%1/rpiBase.hxx").arg(d->pluginFamily));
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll())
    .arg(QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper()));
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
Beispiel #6
0
void SatellitesMSCItem::setDescription()
{
    /*QString description =
      QObject::tr( "Object name: %1 <br />"
                   "Category: %2 <br />"
                   "Pericentre: %3 km<br />"
                   "Apocentre: %4 km<br />"
                   "Inclination: %5 Degree<br />"
                   "Revolutions per day (24h): %6" )
        .arg( name(), category(), QString::number( m_perc, 'f', 2 ),
                                  QString::number( m_apoc, 'f', 2 ),
                                  QString::number( m_inc, 'f', 2 ),
                                  QString::number( m_n0, 'f', 2 ) );*/

    QFile templateFile(QStringLiteral(":/marble/satellites/satellite.html"));
    if (!templateFile.open(QIODevice::ReadOnly)) {
        placemark()->setDescription(QObject::tr("No info available."));
        return;
    }
    QString html = templateFile.readAll();

    html.replace("%name%", name());
    html.replace("%noradId%", QString::number(catalogIndex()));
    html.replace("%perigee%", QString::number(m_perc, 'f', 2));
    html.replace("%apogee%", QString::number(m_apoc, 'f', 2));
    html.replace("%inclination%", QString::number(m_inc, 'f', 2));
    html.replace("%period%", "?");
    html.replace("%semiMajorAxis%", "?");

    placemark()->setDescription( html );
}
Beispiel #7
0
bool dtkPluginGenerator::generateTypeSourceFile(void)
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".cpp")));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append(".cpp") << "for writing";
	return false;
    }

    QFile templateFile(":template/type.cpp");

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll())
        .arg(QString(d->plugin))
	.arg(QString(d->type))
	.arg(QString(d->plugin).remove(d->prefix).prepend(QString(d->prefix).replace(0, 1, QString(d->prefix).left(1).toUpper())));
    
    targetFile.close();
    
    templateFile.close();

    return true;
}
Beispiel #8
0
bool dtkPluginGenerator::generateHelpConfigurationFile(void)
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.doxyfile.in")));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.doxyfile.in") << "for writing";
	return false;
    }

    QFile templateFile(":template/doxyfile");

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll());
    
    targetFile.close();
    
    templateFile.close();

    return true;
}
Beispiel #9
0
void createFile(const QString pTemplate, const QString pDestination, const QString pClassName )
{
    // Open template file to read.
    QFile templateFile( pTemplate );
    if ( !templateFile.open(QFile::ReadOnly | QFile::Text) )
    {
        fprintf(stderr, "The project cannot be created because the template file '%s' could not be found.\n", pTemplate.toAscii().data());
        exit(1);  /* exit status of the program : non-zero for errors */
    }

    // Open project file to write
    QFile destinationFile( pDestination );
    if ( !destinationFile.open(QFile::WriteOnly | QFile::Text) )
    {
        fprintf(stderr, "The project cannot be created because the file '%s' could not be opened.\n", pDestination.toAscii().data());
        exit(1);  /* exit status of the program : non-zero for errors */
    }

    // Copy from template file to project file
    // Replace magic words
    QTextStream out( &destinationFile );
    QTextStream in( &templateFile );
    QString line;
    do
    {
        line = in.readLine();

        line.replace( "<%=class_name%>", pClassName );

        out << line << "\n";;
    } while (!line.isNull());

    destinationFile.close();
    templateFile.close();
}
Beispiel #10
0
void QgsComposerManager::on_mAddButton_clicked()
{
  QgsComposer* newComposer = 0;

  newComposer = QgisApp::instance()->createNewComposer();
  if ( !newComposer )
  {
    return;
  }

  if ( mTemplate->currentIndex() > 0 )
  {
    QDomDocument templateDoc;
    QFile templateFile( mTemplate->itemData( mTemplate->currentIndex() ).toString() );
    if ( templateFile.open( QIODevice::ReadOnly ) )
    {
      if ( templateDoc.setContent( &templateFile, false ) )
      {
        newComposer->readXML( templateDoc );
      }
    }
  }

  QListWidgetItem* item = new QListWidgetItem( newComposer->title(), mComposerListWidget );
  item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable );
  mItemComposerMap.insert( item, newComposer );
}
Beispiel #11
0
bool FileAnalyzer::createTemplate(void)
{
	if(m_templateFile)
	{
		qWarning("Template file already exists!");
		return true;
	}
	
	QString templatePath = QString("%1/%2.txt").arg(MUtils::temp_folder(), MUtils::next_rand_str());

	QFile templateFile(templatePath);
	if(!templateFile.open(QIODevice::WriteOnly))
	{
		return false;
	}

	templateFile.write("General;");
	for(size_t i = 0; g_tags_gen[i]; i++)
	{
		templateFile.write(QString("Gen_%1=%%1%\\n").arg(g_tags_gen[i]).toLatin1().constData());
	}
	templateFile.write("\\n\r\n");

	templateFile.write("Audio;");
	for(size_t i = 0; g_tags_aud[i]; i++)
	{
		templateFile.write(QString("Aud_%1=%%1%\\n").arg(g_tags_aud[i]).toLatin1().constData());
	}
	templateFile.write("\\n\r\n");

	bool success = (templateFile.error() == QFile::NoError);
	templateFile.close();
	
	if(!success)
	{
		QFile::remove(templatePath);
		return false;
	}

	try
	{
		m_templateFile = new LockedFile(templatePath, true);
	}
	catch(const std::exception &error)
	{
		qWarning("Failed to lock template file:\n%s\n", error.what());
		return false;
	}
	catch(...)
	{
		qWarning("Failed to lock template file!");
		return false;
	}

	return true;
}
Beispiel #12
0
std::string
GetVisItMovieTemplateBaseClass()
{
    std::string templateFile(GetVisItResourcesDirectory(VISIT_RESOURCES_MOVIETEMPLATES));
    templateFile += VISIT_SLASH_STRING;
    templateFile += "visitmovietemplate.py";

    debug1 << "GetVisItMovieTemplateBaseClass = " << templateFile.c_str() << endl;
    return templateFile;
}
Beispiel #13
0
bool QgsLayout::saveAsTemplate( const QString &path, const QgsReadWriteContext &context ) const
{
  QFile templateFile( path );
  if ( !templateFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
  {
    return false;
  }

  QDomDocument saveDocument;
  QDomElement elem = writeXml( saveDocument, context );
  saveDocument.appendChild( elem );

  if ( templateFile.write( saveDocument.toByteArray() ) == -1 )
    return false;

  return true;
}
/*!
  Saves game state to a file.

  For now, it always uses file with name "saves/save1.qml".
  */
void CcfGameManager::saveGame(const QObjectList &unitList,
                              const QString &mapFile,
                              const QString &saveFileName)
{
    // As a first attempt, I will generate the whole file myself.
    // A better approach for the future might be to copy and modify
    // a real scenario file, OR create a QML element like ScenarioLoader
    // which would have "map", "units" properties.

    // Init. Read template.
    QFile templateFile("src/config/saveFileTemplate.txt");
    if (!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qFatal("Template file could not be read! Cannot continue, bailing out.");
        return;
    }

    // File numbers incrementation should go here, or at least overwrite warnings!
    QFile saveFile(saveFileName);
    if (!saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        enterErrorState("Could not save the file: " + saveFileName);
        return;
    }

    QString fileContent = templateFile.readAll();

    // Fill template with given data.
    fileContent.replace("%customImports%", "");
    fileContent.replace("%mapFile%", mapFile);

    // Save units. Hope this will work.
    QString units;
    foreach (QObject *obj, unitList) {
        // In release code, this needs to include order queue,
        // soldier states, damages etc.
        CcfQmlBaseUnit *unit = CcfQmlBaseUnit::ccfUnit(obj);
        units += mTab + unit->getUnitFileName() + " {\n"
                + mTab + mTab + "objectName: \"" + unit->objectName() + "\"\n"
                + mTab + mTab + "x: " + unit->getString("x") + "\n"
                + mTab + mTab + "y: " + unit->getString("y") + "\n"
                + mTab + mTab + "rotation: " + unit->getString("rotation") + "\n"
                + mTab + mTab + "unitSide: \"" + unit->getUnitSide() + "\"\n"
                + mTab + mTab + "state: \"" + unit->getString("state") + "\"\n";
        units += addSavePropertyIfExists(unit, "turretRotation");
        units += addSavePropertyIfExists(unit, "hullColor", true);
        units += mTab + "}\n";
    }
/*
  Create a new project.
  - a new directory for the project
  - an XML project file for the project, from template
  - a stubbed out source file, from template
  Make sure the path name doesn't have any spaces in it, so make can work happily.
  Return the new project's name, or an empty string on failure.
*/
QString ProjectManager::createNewProject(const QString & newProjectPath)
{
  QString projectPath = confirmValidProjectName(newProjectPath);
  QDir newProjectDir;
  newProjectDir.mkpath(projectPath);
  newProjectDir.setPath(projectPath);
  QString newProjName = newProjectDir.dirName();

  // grab the templates for a new project
  QString templatePath = "resources/templates";
  #ifdef MCBUILDER_TEST_SUITE
  templatePath.prepend("../");
  #endif
  QDir templatesDir(MainWindow::appDirectory().filePath(templatePath));

  // create the project file from our template
  QFile templateFile(templatesDir.filePath("project_template.xml"));
  templateFile.copy(newProjectDir.filePath(newProjName + ".xml"));
  templateFile.close();

  templateFile.setFileName(templatesDir.filePath("makefile_template.txt"));
  templateFile.copy(newProjectDir.filePath("Makefile"));
  templateFile.close();

  templateFile.setFileName(templatesDir.filePath("config_template.txt"));
  templateFile.copy(newProjectDir.filePath("config.h"));
  templateFile.close();

  templateFile.setFileName(templatesDir.filePath("source_template.txt"));
  if (templateFile.open(QIODevice::ReadOnly | QFile::Text)) {
    // and create the main file
    QFile mainFile(newProjectDir.filePath(newProjName + ".c"));
    if (mainFile.open(QIODevice::WriteOnly | QFile::Text)) {
      QTextStream out(&mainFile);
      out << QString("// %1.c").arg(newProjName) << endl;
      out << QString("// created %1").arg(QDate::currentDate().toString("MMM d, yyyy") ) << endl;
      out << templateFile.readAll();
      mainFile.close();
    }
    QFileInfo fi(mainFile);
    addToProjectFile(newProjectDir.path(), fi.filePath());
    templateFile.close();
  }
  return newProjectDir.path();
}
bool AkaiFileHandler::getTemplateDataMPC1000( QByteArray& pgmData )
{
    QFile templateFile( ":/resources/akai/Template.pgm" );

    bool isSuccessful = templateFile.open( QIODevice::ReadOnly );

    if ( isSuccessful )
    {
        QDataStream inStream( &templateFile );

        const int numBytesRead = inStream.readRawData( pgmData.data(), MPC1000_PGM::FILE_SIZE );

        if ( numBytesRead != MPC1000_PGM::FILE_SIZE )
        {
            isSuccessful = false;
        }
    }

    return isSuccessful;
}
Beispiel #17
0
bool AddTool::_addOneFile(QString templateName, QString targetName,
                          const QList<QPair<QRegExp, QString> > &mapping)
{
    qDebug() << "Adding file:" << targetName << "from" << templateName;

    { //block to make sure file processing is done when we get out of it
        QFile templateFile(templateName);
        QFile targetFile(targetName);

        if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            toolError(QString("Could not open file: ") + targetName + " for write.");
            return false;
        }

        if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            toolError(QString("Could not open file: ") + templateName + " for read.");
            return false;
        }

        QTextStream fromStream(&templateFile);
        QTextStream toStream(&targetFile);

        transformStream(fromStream, toStream, mapping);
    }

    //Now add it to mercurial
    QProcess process;
    process.setWorkingDirectory(QFileInfo(targetName).absolutePath());
    process.start(QString("hg add ") + QFileInfo(targetName).fileName());
    if(!process.waitForFinished(3000)) //3 seconds delay
    {
        toolError(QString("Couldn't hg add the file: ") + targetName);
        return false;
    }

    FormatTool::formatFile(targetName);

    return true;
}
PlayingContextWidget::PlayingContextWidget(QWidget * parent, Qt::WindowFlags f)
	: QWidget(parent, f)
{
	p = new Private;

	p->webview = new QWebView(this);

	// create layout
	QVBoxLayout *layout = new QVBoxLayout(this);
	layout->addWidget(p->webview);
	//view->show();
	this->setLayout(layout);

	setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);

	QFile templateFile(":/page-template.html");
	templateFile.open(QIODevice::ReadOnly);
	p->pageTemplate = QString(templateFile.readAll());

	p->webview->setHtml(p->pageTemplate.arg(tr("<i>Playing track info</i>")));
}
Beispiel #19
0
bool dtkPluginGenerator::generateCopyingFile(void)
{
    QFile targetFile(d->target.absoluteFilePath("COPYING.txt"));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open COPYING.txt for writing";
	return false;
    }

    QFile templateFile(QString(":template/license/").append(d->license));
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);

    stream << QString(templateFile.readAll());

    targetFile.close();

    return true;
}
Beispiel #20
0
void ServerImpl::handleRoot(QHttpResponse *resp)
{
    QString templateFile(":/resources/template.html");
    QFile f(templateFile);
    f.open(QIODevice::ReadOnly);
    QString html = QString::fromUtf8(f.readAll());

    QString data;

    {
        QXmlStreamWriter writer(&data);
        writer.setAutoFormatting(true);

        QHashIterator<QString, FileInfo> it(mRegisteredFiles);
        while (it.hasNext()) {
            it.next();
            writer.writeStartElement("tr");

            writer.writeTextElement("td", it.value().hash);
            writer.writeTextElement("td", it.value().filename);
            writer.writeTextElement("td", it.value().filepath);
            writer.writeTextElement("td", it.value().registeredTime.toString());
            writer.writeTextElement("td", QString::number(it.value().ttl));

            writer.writeEndElement();
        }

    }
    QByteArray content = html.arg(data).toUtf8();


    resp->setHeader("Content-Length", QString::number(content.length()));
    resp->setHeader("Content-Type", "text/html");
    resp->writeHead(200); // everything is OK
    resp->write(content);
    resp->end();
}
/*
  Create a new project.
  - a new directory for the project
  - an XML project file for the project, from template
  - a stubbed out source file, from template
  Make sure the path name doesn't have any spaces in it, so make can work happily.
  Return the new project's name, or an empty string on failure.
*/
QString ProjectManager::createNewProject(QString newProjectPath)
{
  confirmValidProjectName(&newProjectPath);
  if(newProjectPath.contains(" ")) // if there are still spaces in the path, we have problems
    return "";
  QDir newProjectDir;
  newProjectDir.mkpath(newProjectPath);
  newProjectDir.setPath(newProjectPath);
  QString newProjName = newProjectDir.dirName();
  
  // grab the templates for a new project
  QDir templatesDir = QDir::current().filePath("resources/templates");
    
  // create the project file from our template
  QFile templateFile(templatesDir.filePath("project_template.xml"));
  templateFile.copy(newProjectDir.filePath(newProjName + ".xml"));
  templateFile.close();
  
  templateFile.setFileName(templatesDir.filePath("source_template.txt"));
  if( templateFile.open(QIODevice::ReadOnly | QFile::Text) )
  {
    // and create the main file
    QFile mainFile(newProjectDir.filePath(newProjName + ".c"));
    if( mainFile.open(QIODevice::WriteOnly | QFile::Text) )
    {
      QTextStream out(&mainFile);
      out << QString("// %1.c").arg(newProjName) << endl;
      out << QString("// created %1").arg(QDate::currentDate().toString("MMM d, yyyy") ) << endl;
      out << templateFile.readAll();
      mainFile.close();
    }
    QFileInfo fi(mainFile);
    addToProjectFile(newProjectDir.path(), fi.filePath(), "thumb");
    templateFile.close();
  }
  return newProjectDir.path();
}
void QgsComposerManager::show_clicked()
{
  QListWidgetItem* item = mComposerListWidget->currentItem();
  if ( !item )
  {
    return;
  }

  QMap<QListWidgetItem*, QgsComposer*>::iterator it = mItemComposerMap.find( item );
  if ( it != mItemComposerMap.end() )
  {
    QgsComposer* c = 0;
    if ( it.value() ) //a normal composer
    {
      c = it.value();
      if ( c )
      {
        // extra activation steps for Windows
        bool shown = c->isVisible();
        hide();

        c->activate();

        // extra activation steps for Windows
        if ( !shown )
        {
          c->on_mActionZoomAll_triggered();
        }
      }
    }
  }
#if 0
  else //create composer from default template
  {
    QMap<QString, QString>::const_iterator templateIt = mDefaultTemplateMap.find( it.key()->text() );
    if ( templateIt == mDefaultTemplateMap.constEnd() )
    {
      return;
    }

    QDomDocument templateDoc;
    QFile templateFile( templateIt.value() );
    if ( !templateFile.open( QIODevice::ReadOnly ) )
    {
      return;
    }

    if ( !templateDoc.setContent( &templateFile, false ) )
    {
      return;
    }
    c = QgisApp::instance()->createNewComposer();
    c->setTitle( it.key()->text() );
    if ( c )
    {
      c->readXML( templateDoc );
      mItemComposerMap.insert( it.key(), c );
    }
  }

  if ( c )
  {
    c->activate();
  }
#endif //0
  close();
}
Beispiel #23
0
Template::Ptr TemplateCache::getTemplate(const Path& path)
{
	if ( _logger )
	{
		poco_trace_f1(*_logger, "Trying to load %s", path.toString());
	}
	Path templatePath = resolvePath(path);
	std::string templatePathname = templatePath.toString();
	if ( _logger )
	{
		poco_trace_f1(*_logger, "Path resolved to %s", templatePathname);
	}
	File templateFile(templatePathname);

	Template::Ptr tpl;

	std::map<std::string, Template::Ptr>::iterator it = _cache.find(templatePathname);
	if ( it == _cache.end() )
	{
		if ( templateFile.exists() )
		{
			if ( _logger )
			{
				poco_information_f1(*_logger, "Loading template %s", templatePath.toString());
			}

			tpl = new Template(templatePath);

			try
			{
				tpl->parse();
				_cache[templatePathname] = tpl;
			}
			catch(JSONTemplateException& jte)
			{
				if ( _logger )
				{
					poco_error_f2(*_logger, "Template %s contains an error: %s", templatePath.toString(), jte.message());
				}
			}
		}
		else
		{
			if ( _logger )
			{
				poco_error_f1(*_logger, "Template file %s doesn't exist", templatePath.toString());
			}
			throw FileNotFoundException(templatePathname);
		}
	}
	else
	{
		tpl = it->second;
		if ( tpl->parseTime() < templateFile.getLastModified() )
		{
			if ( _logger )
			{
				poco_information_f1(*_logger, "Reloading template %s", templatePath.toString());
			}

			tpl = new Template(templatePath);

			try
			{
				tpl->parse();
				_cache[templatePathname] = tpl;
			}
			catch(JSONTemplateException& jte)
			{
				if ( _logger )
				{
					poco_error_f2(*_logger, "Template %s contains an error: %s", templatePath.toString(), jte.message());
				}
			}
		}
	}

	return tpl;
}
Beispiel #24
0
void wxFormBuilder::DoCreateWxFormBuilderProject(const wxFBItemInfo& data)
{
	// add new virtual folder to the selected virtual directory
	wxString formbuilderVD;
	formbuilderVD = data.virtualFolder.BeforeFirst(wxT(':'));

	m_mgr->CreateGroupFolder(formbuilderVD, wxT("formbuilder"));
	wxString templateFile(m_mgr->GetInstallDirectory() + wxT("/templates/formbuilder/"));     //todo,todo

	switch (data.kind) {
	default:
	case wxFBItemKind_Dialog:
		templateFile << wxT("DialogTemplate.fbp");
		break;
	case wxFBItemKind_Frame:
		templateFile << wxT("FrameTemplate.fbp");
		break;
	case wxFBItemKind_Panel:
		templateFile << wxT("PanelTemplate.fbp");
		break;
	case wxFBItemKind_Dialog_With_Buttons:
		templateFile << wxT("DialogTemplateWithButtons.fbp");
		break;
	}

	wxFileName tmplFile(templateFile);
	if (!tmplFile.FileExists()) {
		wxMessageBox(wxString::Format(wxT("Cant find wxFormBuilder template file '%s'"), tmplFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
		return;
	}

	// place the files under the VD's project owner
	wxString err_msg;
	wxString project = data.virtualFolder.BeforeFirst(wxT(':'));
	ProjectPtr proj = m_mgr->GetSolution()->FindProjectByName(project, err_msg);
	if (proj) {
		wxString files_path = proj->GetFileName().GetPath(wxPATH_GET_SEPARATOR|wxPATH_GET_VOLUME);
		// copy the file to here
		wxFileName fbpFile(files_path, data.file + wxT(".fbp"));
		if (!wxCopyFile(tmplFile.GetFullPath(), fbpFile.GetFullPath())) {
			wxMessageBox(wxString::Format(wxT("Failed to copy tempalte file to '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}
		// open the file, and replace expand its macros
		wxString content;
		if (!ReadFileWithConversion(fbpFile.GetFullPath().c_str(), content)) {
			wxMessageBox(wxString::Format(wxT("Failed to read file '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}

		content.Replace(wxT("$(BaseFileName)"), data.file);
		content.Replace(wxT("$(ProjectName)"), data.className);
		content.Replace(wxT("$(Title)"), data.title);
		content.Replace(wxT("$(ClassName)"), data.className);

		if (!WriteFileWithBackup(fbpFile.GetFullPath().c_str(), content, false)) {
			wxMessageBox(wxString::Format(wxT("Failed to write file '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}

		// add the file to the project
		wxArrayString paths;
		paths.Add(fbpFile.GetFullPath());
		m_mgr->AddFilesToGroupFolder(project + wxT(":formbuilder"), paths);

		// // first we launch wxFB with the -g flag set
		wxString genFileCmd;
		genFileCmd << GetWxFBPath() << wxT(" -g ") << fbpFile.GetFullPath();

		wxArrayString dummy, filesToAdd;
		ProcUtils::SafeExecuteCommand(genFileCmd, dummy);

		wxFileName cppFile(fbpFile.GetPath(), data.file + wxT(".cpp"));
		wxFileName headerFile(fbpFile.GetPath(), data.file + wxT(".h"));

		if (cppFile.FileExists()) {
			filesToAdd.Add(cppFile.GetFullPath());
		}

		if (headerFile.FileExists()) {
			filesToAdd.Add(headerFile.GetFullPath());
		}

		if (filesToAdd.GetCount()) {
			m_mgr->AddFilesToGroupFolder(data.virtualFolder, filesToAdd);
		}

		DoLaunchWxFB(fbpFile.GetFullPath());
	}
}
Beispiel #25
0
bool PaperWallet::genWallet()
{
    QRcode      *codePublic,
                *codePrivate;
    QImage      scaledPublic,
                scaledPrivate;
    QByteArray  byteArrayPublic,
                byteArrayPrivate;
    QBuffer     bufferPublic(&byteArrayPublic),
                bufferPrivate(&byteArrayPrivate);
    QString     htmlTemplate;

    unsigned char *p;


    if ((addressURL != "") && (privateKeyURL != "")) {
        codePublic = QRcode_encodeString(addressURL.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
        if (!codePublic) {
            return false;
        }
        publicImage = QImage(codePublic->width + 8, codePublic->width + 8, QImage::Format_RGB32);
        publicImage.fill(0xffffff);
        p = codePublic->data;
        for (int y = 0; y < codePublic->width; y++) {
            for (int x = 0; x < codePublic->width; x++) {
                publicImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                p++;
            }
        }

        QRcode_free(codePublic);

        scaledPublic = publicImage.scaledToHeight(256);
        scaledPublic.save(&bufferPublic, "PNG");
        QString publicImageBase64 = QString::fromLatin1(byteArrayPublic.toBase64().data());

        codePrivate = QRcode_encodeString(privateKeyURL.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
        if (!codePrivate) {
            return false;
        }
        privateImage = QImage(codePrivate->width + 8, codePrivate->width + 8, QImage::Format_RGB32);
        privateImage.fill(0xffffff);
        p = codePrivate->data;
        for (int y = 0; y < codePrivate->width; y++) {
            for (int x = 0; x < codePrivate->width; x++) {
                privateImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                p++;
            }
        }
        QRcode_free(codePrivate);

        scaledPrivate = privateImage.scaledToHeight(256);
        scaledPrivate.save(&bufferPrivate, "PNG");
        QString privateImageBase64 = QString::fromLatin1(byteArrayPrivate.toBase64().data());

        QFile templateFile(templateName);
        if (templateFile.open(QIODevice::ReadOnly)) {
            QTextStream templateStream(&templateFile);
            htmlTemplate = templateStream.readAll();

            htmlTemplate.replace(QString("#PUBLIC_KEY_IMAGE#"), publicImageBase64);
            htmlTemplate.replace(QString("#PUBLIC_KEY_ADDRESS#"), address);
            htmlTemplate.replace(QString("#PRIVATE_KEY_IMAGE#"), privateImageBase64);
            htmlTemplate.replace(QString("#PRIVATE_KEY_ADDRESS#"), privateKey);
            htmlTemplate.replace(QString("#DATE_GENERATED#"), date);
            htmlTemplate.replace(QString("#BALANCE#"), amount);
            htmlTemplate.replace(QString("#LABEL#"), label);
        }

        if (!fileName.isNull()) {
            printf("fileName = %s\n", fileName.toStdString().c_str());

            QFile file(fileName);
            if (file.open(QIODevice::ReadWrite)) {
                QTextStream stream(&file);
                stream << htmlTemplate;
                stream << endl;
            }
        }


       return true;
    }
    return false;
}
ExtOscPatternEditor::ExtOscPatternEditor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ExtOscPatternEditor) {
    ui->setupUi(this);
    textLock  = false;
    itemLock  = false;
    isTrigger = false;
    patternNbValues = 0;

    trees.clear();
    trees << qMakePair(ui->argument1Combo, qMakePair(ui->argument1Label, ui->argument1Clear));
    trees << qMakePair(ui->argument2Combo, qMakePair(ui->argument2Label, ui->argument2Clear));
    trees << qMakePair(ui->argument3Combo, qMakePair(ui->argument3Label, ui->argument3Clear));
    trees << qMakePair(ui->argument4Combo, qMakePair(ui->argument4Label, ui->argument4Clear));
    trees << qMakePair(ui->argument5Combo, qMakePair(ui->argument5Label, ui->argument5Clear));
    trees << qMakePair(ui->argument6Combo, qMakePair(ui->argument6Label, ui->argument6Clear));
    trees << qMakePair(ui->argument7Combo, qMakePair(ui->argument7Label, ui->argument7Clear));
    trees << qMakePair(ui->argument8Combo, qMakePair(ui->argument8Label, ui->argument8Clear));
    trees << qMakePair(ui->argument9Combo, qMakePair(ui->argument9Label, ui->argument9Clear));
    trees << qMakePair(ui->argument10Combo, qMakePair(ui->argument10Label, ui->argument10Clear));

    foreach(const HelpInfo &info, Help::categories["protocols"].infos)
        ui->protocolCombo->addItem(info.keyword + QString(" - ") + info.title);
    foreach(const HelpInfo &info, Help::categories["hostIp"].infos)
        ui->hostIpCombo->addItem(info.keyword + QString(" - ") + info.title);
    foreach(const HelpInfo &info, Help::categories["hostMidi"].infos)
        ui->hostMidiCombo->addItem(info.keyword + QString(" - ") + info.title);
    foreach(const HelpInfo &info, Help::categories["port"].infos)
        ui->portCombo->addItem(info.keyword + QString(" - ") + info.title);
    foreach(const HelpInfo &info, Help::categories["addressOsc"].infos)
        ui->addressOscCombo->addItem(info.keyword + QString(" - ") + info.title);
    foreach(const HelpInfo &info, Help::categories["addressMidi"].infos)
        ui->addressMidiCombo->addItem(info.keyword + QString(" - ") + info.title);
    for(quint16 treeIndex = 0 ; treeIndex < trees.count() ; treeIndex++) {
        QStringList completerHelp;
        foreach(const HelpInfo &info, Help::categories["values"].infos) {
            trees.at(treeIndex).first->addItem(info.keyword + QString(" - ") + info.title);
            completerHelp << info.keyword + QString(" - ") + info.title;
        }
        QCompleter *completer = new QCompleter(completerHelp, this);
        completer->setCaseSensitivity(Qt::CaseInsensitive);
        trees.at(treeIndex).first->setCompleter(completer);
    }


    //Templates
    ui->templates->clear();
    addTemplate("Templates", true);
    addTemplate("--");
    QFileInfoList files = QDir(Application::pathApplication.absoluteFilePath() + "/Tools/Templates/").entryInfoList(QStringList() << "*.txt", QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
    files <<              QDir(Application::pathDocuments.absoluteFilePath()   + "/Templates/").entryInfoList(QStringList() << "*.txt", QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
    bool firstTemplate = true;
    QString title;
    foreach(const QFileInfo &file, files) {
        QString header;
        QHash<QString, QString> params;
        QFile templateFile(file.absoluteFilePath());
        if(templateFile.open(QFile::ReadOnly)) {
            QStringList templatesLong = QString(templateFile.readAll()).split("\n", QString::SkipEmptyParts);
            foreach(const QString &templateLong, templatesLong) {
                if(templateLong.startsWith("["))
                    header = templateLong.toLower();
                else if(header == "[general]") {
                    QStringList templateLongSplit = templateLong.split("=");
                    if(templateLongSplit.count() > 1) {
                        QString key = templateLongSplit.at(0).toLower(), value = templateLongSplit.at(1);
                        params.insert(key, value);
                        if(key == "name")
                            title = value;
                    }
                }
                else if(header == "[messages]") {
                    if(!title.isEmpty()) {
                        if(!firstTemplate)
                            addTemplate("--");
                        firstTemplate = false;
                        addTemplate(title);
                        title.clear();
                    }
                    addTemplate("          " + templateLong.trimmed(), true);
                }
            }
        }
Beispiel #27
0
/**
 * Export the information in the current view and filter to an HTML file at
 * the specified path.  The records are listed in the current sorting order.
 * Unlike the HTML generated for printing, this method's output is intended
 * to be a standalone page viewable in normal web browsers, with easily
 * overridden display properties.
 *
 * @param filename The HTML file to create or overwrite
 */
void View::exportToHTML(const QString &filename)
{
    // Open the output template
    QFile templateFile(":/templates/export.html");
    if (!templateFile.open(QFile::ReadOnly)) {
        return;
    }
    QTextStream stream(&templateFile);
    QString result = stream.readAll();
    templateFile.close();

    // populate the title and row colors
    result = result.arg(QFileInfo(filename).completeBaseName());
    result = result.arg(Factory::evenRowColor.name());
    result = result.arg(Factory::oddRowColor.name());

    // populate the column headers
    QStringList lines;
    int colCount = columns.count();
    int i, j;
    QString headerPattern("<th>%1</th>\n");
    for (i = 0; i < colCount; i++) {
        lines.append(headerPattern.arg(Qt::escape(columns[i])));
    }
    QFile f(filename);
    if (!f.open(QFile::WriteOnly)) {
        return;
    }
    QTextStream output(&f);
    output.setCodec("UTF-8");
    output << result.arg(lines.join(""));

    // populate the data
    QStringList data;
    int type;
    QStringList rowStarts;
    rowStarts << "<tr class=\"even\">\n" << "<tr class=\"odd\">\n";
    QString rowEnd("</tr>\n");
    QString leftPattern = "<td>%1</td>\n";
    QString rightPattern = "<td class=\"r\">%1</td>\n";
    QStringList divs;
    divs << "<td><div class=\"n\">&#9744;</div></td>\n";
    divs << "<td><div class=\"y\">&#9745;</div></td>\n";
    divs << "<td><div class=\"i\">&#9997;</div></td>\n";
    QString newline("\n");
    QString br("<br>");
    QString value;
    for (i = 0; i < rowCnt; i++) {
        output << rowStarts[i % 2];
        data = getRow(i);
        for (j = 0; j < colCount; j++) {
            type = dataTypes[j];
            if (type == INTEGER || type == FLOAT || type == CALC
                || type == SEQUENCE) {
                output << rightPattern.arg(data[j]);
            }
            else if (type == BOOLEAN) {
                output << divs[data[j].toInt()];
            }
            else if (type == IMAGE && !data[j].isEmpty()) {
                output << divs[2];
            }
            else if (type == NOTE || type == STRING) {
                value = Qt::escape(data[j]).replace(newline, br);
                output << leftPattern.arg(value);
            }
            else {
                output << leftPattern.arg(data[j]);
            }
        }
        output << rowEnd;
    }
    output << "</tbody>\n</table>\n</body>\n</html>\n";
    f.close();
}
Beispiel #28
0
void generator::generate(string classname, membersVector mv)
{
    cout << "Start generating for template: " << m_templatePath << endl;

    membersMap mmap;
    for (membersVector::iterator p = mv.begin(); p != mv.end(); ++p)
    {
        string type = p->second;
        string name = p->first;

        mmap[name] = type;
    }


    stringstream inStream;
    ifstream  templateFile(m_templatePath);
    if (templateFile.is_open())
    {
        string line;
        while ( getline (templateFile, line) )
        {
            inStream << line << endl;
        }
        templateFile.close();
    }

    string result = inStream.str();

    //Установка имени класса
    size_t pos;
    while ( (pos = result.find(cCNTemplate)) != std::string::npos)
    {
        result.replace(pos, cCNTemplate.size(), classname);
    }

    parseFields(result, mmap);

    cout << "----------- found members" << endl;
    for (membersMap::iterator p = mmap.begin(); p != mmap.end(); ++p)
        std::cout << p->first << " => " << p->second << '\n';

    cout << "-----------" << endl;
    //Генерация полей
    stringstream fieldString;
    fieldString << endl;
    for (membersMap::iterator p = mmap.begin(); p != mmap.end(); ++p)
    {
        fieldString << "\t" << p->second << " m_" << p->first << ";" << endl;
    }
    fieldString << "\t";
    replaceBetween(cPFBounds, fieldString.str(), result);

    //Генерация акксессоров
    stringstream accString;
    for (membersMap::iterator p = mmap.begin(); p != mmap.end(); ++p)
    {
        string type = p->second;
        string name = p->first;

        accString << endl;
        //генерация геттера
        accString   << "\t" << "const " << type << " get_" << name << "(){" << endl
                    << "\t\t" << "return m_" << name << ";" << endl
                    << "\t}" << endl;

        //генерация сеттера
        accString   << "\tvoid set_" << name << "(" << type << " val){" << endl
                    << "\t\tm_" << name << " = val;" << endl
                    << "\t}" << endl;
    }
    accString << "\t";
    replaceBetween(cPMBounds, accString.str(), result);
    //cout << "Result: " << endl << result << endl;

    if (!m_dryRun)
    {
        ofstream ofile (m_resultPath);
        cout << "Writing to file " << m_resultPath << endl;
        if (ofile.is_open())
        {
            ofile << result;
            ofile.close();
        }
    }
}
Beispiel #29
-3
Path TemplateCache::resolvePath(const Path& path) const
{
	if ( path.isAbsolute() )
		return path;

	for(std::vector<Path>::const_iterator it = _includePaths.begin(); it != _includePaths.end(); ++it)
	{
		Path templatePath(*it, path);

		File templateFile(templatePath);
		if ( templateFile.exists() )
		{
			if ( _logger )
			{
				poco_trace_f2(*_logger, "%s template file resolved to %s", path.toString(), templatePath.toString());
			}
			return templatePath;
		}
		if ( _logger )
		{
			poco_trace_f1(*_logger, "%s doesn't exist", templatePath.toString());
		}
	}

	throw FileNotFoundException(path.toString());
}