Esempio n. 1
0
void ctkDicomAppServer::incomingWSDLMessage(
  const QString& message, QString* reply)
{
  if (message == "?wsdl")
  {
    QFile wsdlfile(":/dah/ApplicationService.wsdl");
    wsdlfile.open(QFile::ReadOnly | QFile::Text);
    if(wsdlfile.isOpen())
    {
      QTextStream textstream(&wsdlfile);
      *reply = textstream.readAll();
      QString actualURL="http://localhost:";
      actualURL+=QString::number(port)+"/ApplicationInterface"; // FIXME: has to be replaced by url provided by host
      reply->replace("REPLACE_WITH_ACTUAL_URL",actualURL);
      reply->replace("ApplicationService_schema1.xsd",actualURL+"?xsd=1");
      //reply->replace("<soap:body use=\"literal\"/>","<soap:body use=\"literal\"></soap:body>");
    }
  }
  else if (message == "?xsd=1")
  {
    QFile wsdlfile(":/dah/HostService_schema1.xsd");
    wsdlfile.open(QFile::ReadOnly | QFile::Text);
    if(wsdlfile.isOpen())
    {
      QTextStream textstream(&wsdlfile);
      *reply = textstream.readAll();
    }
  }
}
Esempio n. 2
0
void Material::ReadAndCompileShaders()
{
	Renderer& renderer = Game::GetInstance().GetRenderer();
	std::string vertexShaderSource;
	std::string fragmentShaderSource;
	
	std::string line;
	
	//printf("Loading Vertex Shader %s\n",mVertexShaderPath.c_str());
	std::string fullpath;
	std::string file = mVertexShaderPath;
	GetFullFilePathFromResource(file,fullpath);
	std::ifstream textstream(fullpath.c_str());
	while (std::getline(textstream, line)) 
	{
		vertexShaderSource += line;
		vertexShaderSource += "\n";
	} 
	textstream.close();
	
	//printf("Loading Fragment Shader %s\n",mFragmentShaderPath.c_str());
	file = mVertexShaderPath;
	GetFullFilePathFromResource(file,fullpath);
	textstream.open(fullpath.c_str());
	while (std::getline(textstream, line)) 
	{
		fragmentShaderSource += line;
		fragmentShaderSource += "\n";
	} 
	textstream.close();
	
	mShaderProgramID = renderer.LoadProgram(vertexShaderSource.c_str(),fragmentShaderSource.c_str());
	
}
Esempio n. 3
0
	/*****************************************************
	**
	**   AtlasImportWorker   ---   readZipFile
	**
	******************************************************/
	int readZipFile()
	{
		wxString buf;

		wxFFileInputStream instream( sharedSection->sqlfile );
		wxZipInputStream zipstream( instream );
		wxTextInputStream textstream( zipstream );
		wxZipEntry *zipentry = zipstream.GetNextEntry();

		sharedSection->totalSize = (long)zipstream.GetSize();

		if ( zipentry )
		{
			printf( "Entry: %s\n", str2char( zipentry->GetName()));
			bool b = zipstream.OpenEntry( *zipentry );
			printf( "Open flag_ %d\n", b );

			while( zipstream.GetLastError() == wxSTREAM_NO_ERROR )
			{
				sharedSection->currentLine++;
				buf = textstream.ReadLine();
				if ( checkCancelOrExit() ) break;
				addQueryPart( buf );
				if ( checkCancelOrExit() ) break;
			}
			zipstream.CloseEntry();
		}
		else
		{
			printf( "Entry NULL\n" );
		}
		if ( qb.size() > 0 ) execQueryBundle();
		return 0;
	}
Esempio n. 4
0
QList<QString> ParserM3u::parse(QString sFilename)
{
    QFile file(sFilename);
    QString basepath = sFilename.section('/', 0, -2);

    clearLocations();
    //qDebug() << "ParserM3u: Starting to parse.";
    if (file.open(QIODevice::ReadOnly) && !isBinary(sFilename)) {
        /* Unfortunately, QT 4.7 does not handle <CR> (=\r or asci value 13) line breaks.
         * This is important on OS X where iTunes, e.g., exports M3U playlists using <CR>
         * rather that <LF>
         *
         * Using QFile::readAll() we obtain the complete content of the playlist as a ByteArray.
         * We replace any '\r' with '\n' if applicaple
         * This ensures that playlists from iTunes on OS X can be parsed
         */
        QByteArray ba = file.readAll();
        //detect encoding
        bool isCRLF_encoded = ba.contains("\r\n");
        bool isCR_encoded = ba.contains("\r");
        if(isCR_encoded && !isCRLF_encoded)
            ba.replace('\r','\n');
        QTextStream textstream(ba.constData());

        if (isUtf8(ba.constData())) {
            textstream.setCodec("UTF-8");
        } else {
            textstream.setCodec("windows-1252");
        }

        while(!textstream.atEnd()) {
            QString sLine = getFilepath(&textstream, basepath);
            if(sLine.isEmpty())
                break;

            //qDebug() << "ParserM3u: parsed: " << (sLine);
            m_sLocations.append(sLine);
        }

        file.close();

        if(m_sLocations.count() != 0)
            return m_sLocations;
        else
            return QList<QString>(); // NULL pointer returned when no locations were found

    }

    file.close();
    return QList<QString>(); //if we get here something went wrong
}
Esempio n. 5
0
/** Creates the file filename and put text into the file.
 */
bool savePlainFile(const QString & filename,
                   const QString & text,
                   const bool forceOverwrite,
                   QTextCodec * const fileCodec)
{
    Q_ASSERT(fileCodec);
    Q_ASSERT(!filename.isEmpty());

    QFile saveFile(filename);

    if (saveFile.exists()) {
        if (!forceOverwrite
            && message::showQuestion(0, QObject::tr("Overwrite File?"),
                QString::fromLatin1("<qt><b>%1</b><br/>%2</qt>")
                .arg( QObject::tr("The file already exists.") )
                .arg( QObject::tr("Do you want to overwrite it?")),
                QMessageBox::Yes | QMessageBox::No,
                QMessageBox::No) == QMessageBox::No)
        {
            return false;
        }
        else { //either the user chose yes or forceOverwrite is set
            saveFile.remove();
        }
    }

    if (saveFile.open(QIODevice::ReadWrite)) {
        QTextStream textstream(&saveFile);
        textstream.setCodec(fileCodec);
        textstream << text;
        textstream.flush();
        saveFile.close();
        if (saveFile.error() == QFile::NoError)
            return true;

        QMessageBox::critical(0, QObject::tr("Error"),
                              QString::fromLatin1("<qt>%1<br/><b>%2</b></qt>")
                                  .arg(QObject::tr("Error while writing to file."))
                                  .arg(QObject::tr("Please check that enough disk space is available.")));
    }
    else {
        QMessageBox::critical(0, QObject::tr("Error"),
                              QString::fromLatin1("<qt>%1<br/><b>%2</b></qt>")
                                  .arg(QObject::tr("The file couldn't be opened for saving."))
                                  .arg(QObject::tr("Please check permissions etc.")));
    }

    return false;
}
Esempio n. 6
0
void _PDF_GetTextStream_Unicode(CFX_WideTextBuf& buffer, CPDF_PageObjects* pPage, FX_BOOL bUseLF,
                                CFX_PtrArray* pObjArray)
{
    CPDF_TextStream textstream(buffer, bUseLF, pObjArray);
    FX_POSITION pos = pPage->GetFirstObjectPosition();
    while (pos) {
        CPDF_PageObject* pObject = pPage->GetNextObject(pos);
        if (pObject == NULL) {
            continue;
        }
        if (pObject->m_Type != PDFPAGE_TEXT) {
            continue;
        }
        textstream.ProcessObject((CPDF_TextObject*)pObject, FALSE);
    }
}
void Preferences::writeData()
{
    QDomDocument doc("preferences");

    // create the root element
    QDomElement root = doc.createElement(doc.doctype().name());
    root.setAttribute("version", version_);
    root.setAttribute("application", format_);

    // now do our options group by group
    QMap<QString, PrefMap>::Iterator git;
    PrefMap::Iterator pit;
    QDomElement group, option;
    for (git = groups_.begin(); git != groups_.end(); ++git) {
        // create a group element
        group = doc.createElement("group");
        group.setAttribute("name", git.key());
        // add in options
        for (pit = (*git).begin(); pit != (*git).end(); ++pit) {
            option = doc.createElement("option");
            option.setAttribute("key", pit.key());
            option.setAttribute("value", pit.data());
            group.appendChild(option);
        }
        root.appendChild(group);
    }
    doc.appendChild(root);

    // open file
    QFile* datafile = new QFile(file_);
    if (!datafile->open(IO_WriteOnly)) {
        // error opening file
        qWarning("Error: Cannot open preferences file " + file_);
        datafile->close();
        delete (datafile);
        filestate_ = false;
        return;
    }
    filestate_ = true;

    // write it out
    QTextStream textstream(datafile);
    doc.save(textstream, 4);
    datafile->close();
    delete (datafile);
    formatstate_ = true;
}
Esempio n. 8
0
/* Write chat message to disk */
void PrivateChat::logMessage(const QString& user, uint ts, const QString& speaker, const QString& _l) {
	if (! museeq->mLogPrivate) {
		return;
	}
	if (! museeq->mPrivateLogDir.isEmpty() and QDir(museeq->mPrivateLogDir).exists() ) {
		QFile logfile ( museeq->mPrivateLogDir+"/"+user);
		if (! logfile.open(QIODevice::WriteOnly | QIODevice::Append)) {
			museeq->output(QString("Write Error: could not write to: " +museeq->mPrivateLogDir+"/"+user));
			return;
		}
		QDateTime _t;
		_t.setTime_t(ts);
		QTextStream textstream( &logfile );
		textstream << _t.toString() << " [" << speaker << "]\t" << _l << "\n";
		logfile.close();
	} else {
		museeq->output(QString("Write Error: directory doesn't exist: " +museeq->mPrivateLogDir+"/"));
	}
}
Esempio n. 9
0
CFX_WideString PDF_GetFirstTextLine_Unicode(CPDF_Document* pDoc, CPDF_Dictionary* pPage)
{
    CFX_WideTextBuf buffer;
    buffer.EstimateSize(0, 1024);
    CPDF_Page page;
    page.Load(pDoc, pPage);
    CPDF_ParseOptions options;
    options.m_bTextOnly = TRUE;
    options.m_bSeparateForm = FALSE;
    page.ParseContent(&options);
    CPDF_TextStream textstream(buffer, FALSE, NULL);
    FX_POSITION pos = page.GetFirstObjectPosition();
    while (pos) {
        CPDF_PageObject* pObject = page.GetNextObject(pos);
        if (pObject->m_Type != PDFPAGE_TEXT) {
            continue;
        }
        if (textstream.ProcessObject((CPDF_TextObject*)pObject, TRUE)) {
            break;
        }
    }
    return buffer.GetWideString();
}
/** Creates the file filename and put text into the file.
 */
bool CToolClass::savePlainFile( const QString& filename, const QString& text, const bool& forceOverwrite, QTextCodec* fileCodec) {
	QFile saveFile(filename);
	bool ret;

	if (saveFile.exists()) {
		if (!forceOverwrite && QMessageBox::question(0, QObject::tr("Overwrite File?"),
				QString::fromLatin1("<qt><B>%1</B><BR>%2</qt>")
					.arg( QObject::tr("The file already exists.") )
					.arg( QObject::tr("Do you want to overwrite it?")),
				QMessageBox::Yes|QMessageBox::No,
				QMessageBox::No) == QMessageBox::No
		   ) 
		{
			return false;
		}
		else { //either the user chose yes or forceOverwrite is set
			saveFile.remove();
		}
	}

	if ( saveFile.open(QIODevice::ReadWrite) ) {
		QTextStream textstream( &saveFile );
		textstream.setCodec(fileCodec);
		textstream << text;
		saveFile.close();
		ret = true;
	}
	else {
		QMessageBox::critical(0, QObject::tr("Error"),
			QString::fromLatin1("<qt>%1<BR><B>%2</B></qt>")
				.arg( QObject::tr("The file couldn't be saved.") )
				.arg( QObject::tr("Please check permissions etc.")));
		saveFile.close();
		ret = false;
	}
	return ret;
}
Esempio n. 11
0
int main()
{
    QFile::remove("../db_result/city.base");
    QFile sourcesBase;
    sourcesBase.setFileName("../db_result/townBase.txt"); // копия его лежит в каталоге с исходниками
    sourcesBase.open(QIODevice::ReadOnly);
    int randsize = 0; //17589;
    char listTowns[17000][12];
    QString qstringtemp;
    QTextStream textstream(&sourcesBase);
    //for (int i = 0; i< 17589 ; i++)
    while(!textstream.atEnd())
    {
        qstringtemp = textstream.readLine();
        if ((qstringtemp.size()>0)&&(qstringtemp.size()<11))
        {
            for (int j =0; j<12; j++)
            {
                char mas = qstringtemp[j].toAscii();
                listTowns[randsize][j] = mas;
            }
            listTowns[randsize][11] = 0;
            randsize++;
        }
    }

    sourcesBase.close();

    QFile binbase;
    binbase.setFileName("../db_result/city.base");
    binbase.open(QIODevice::WriteOnly);
    QDataStream stream(&binbase);
    char j[dlina+1];
    for (int i = 0; i<dlina+1; i++)
    {
            j[i]='0';
    }

    for (long i = 0; i< 1000200;i++)
    {
            Record element ;
            if (j[0]=='Z')
            {
                    j[0] = '0';
                    j[1]++;
                    element.ID[0]=j[0];
            } else {
                    j[0]++;
                    element.ID[0]=j[0];

            }
            for (int k = 1; k< 7; k++)
            {
                    if (j[k]=='Z')
                    {
                            j[k] = '0';
                            j[k+1]++;
                            element.ID[k]=j[k];
                    } else {
                            element.ID[k]=j[k];
                    }
            }
            element.ID[6] = 0;

            int indexN = rand() % randsize;
            for (int j = 0; j<razmer-1; j++)
            {
                element.string[j]= listTowns[indexN][j];
            }
            element.string[razmer-1] = 0;
            element.number = rand() % 100;

            stream << element;
            //qDebug() << element.ID << element.string << element.number;
    }

    binbase.close();
    return 0; //a.exec();
}
Esempio n. 12
0
bool wxMatrix2D::LoadFile( const wxString &filename, const wxArrayInt *cols )
{
    if (filename.IsNull()) return false;

    // valid separators for data
//  const char comma = 44;  // comma
    const char tab = 9;     // tab
    const char space = 32;  // space
//  const char cr = 13;     // carrage return

    wxFile loadfile;
    loadfile.Open( filename, wxFile::read );

    if (!loadfile.IsOpened()) return false;

    m_file_comments.Clear();
//  m_file_comments_positions.Clear();

    wxFileInputStream filestream( loadfile );
    wxTextInputStream textstream( filestream );

    int sizeof_data = 4000;
    double *data = (double*)malloc(sizeof_data*sizeof(double));
    if (data == (double*)NULL) return false;

    wxString line_str, num_str;

    int i, a, b, pos;
    int num_cols = 0;
    int num_rows = 0;
    int num_points = 0;
    int num_lines = 0;
    double point;

    bool fail = false;


    while ( !filestream.Eof() && !fail )
    {
        ++num_lines;

        line_str = textstream.ReadLine();
        if ( filestream.Eof() ) break;

        line_str.Trim(false);
        line_str.Trim(true);


        if (line_str.Left(1) == wxT("#"))
        {
            m_file_comments.Add( line_str );
            //m_file_comments_positions.Add(num_lines);
        }
        else
        {
            ++num_rows;

            // do this once to figure out how many columns of data there is unless already given
            if ( num_cols < 1 )
            {
                for (i = 0; i < 10000; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[i] = point;
                        ++num_cols;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        i = 10000;
                        break;
                    }
                }
            }
            else
            {
                if ( num_points > sizeof_data - num_cols*2 )
                {
                    data = (double*)realloc( data, sizeof_data+1000 );
                }
                for (i = 0; i < num_cols; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[numpoints*numcolumns + i] = point;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        // if not just a blank line then data is wrong
                        if (i != 0)
                        {
                            fail = true;
                            wxMessageBox(wxT("# for comments\n7   4\n33  25\n..."),
                                         wxT("Invalid data file format"), wxOK);
                        }
                        i = num_cols;
                        break;
                    }
                }
            }
        }
    }

    // not static
    data = (double*)realloc( data, (num_points+1)*sizeof(double) );
    Create( num_cols, num_rows, data, false );
    loadfile.Close();
    return true;
}
Esempio n. 13
0
void ConfigProject::configProject(QString projectname)
{
	QDomDocument * projectdoc=new QDomDocument();
	QFile file(projectname);
	if(file.open(QIODevice::ReadOnly|QIODevice::Text))
	{
		if(!projectdoc->setContent(&file))
		{
			delete projectdoc;
			file.close();
			return;
		}
		file.close();
	}
	else
	{
		return;
	}
	QStringList conditions;
#ifdef Q_PROCESSOR_X86_64
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'";
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Release|Win32\'";
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Debug|x64\'";
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Release|x64\'";
#elif Q_PROCESSOR_X86
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'";
    conditions<<"\'$(Configuration)|$(Platform)\'==\'Release|Win32\'";
#endif
	int j,m=conditions.size();
	QDomElement projectroot=projectdoc->documentElement();
	QDomElement propertygroup=projectroot.firstChildElement("PropertyGroup");

	while(propertygroup.attribute("Label")!="Globals")
	{
		propertygroup=propertygroup.nextSiblingElement("PropertyGroup");
	}
	if(propertygroup.isNull())
	{
		propertygroup=projectroot.appendChild(projectdoc->createElement("PropertyGroup")).toElement();
		propertygroup.setAttribute("Label","Globals");
	}
	propertygroup=propertygroup.nextSiblingElement("PropertyGroup");

	for(j=0;j<m;j++)
	{
		if(propertygroup.isNull())
		{
			propertygroup=projectroot.appendChild(projectdoc->createElement("PropertyGroup")).toElement();
		}
		else if(propertygroup.attribute("Label")=="UserMacros")
		{
			propertygroup=projectroot.insertBefore(projectdoc->createElement("PropertyGroup"),propertygroup).toElement();
		}
		propertygroup.setAttribute("Condition",conditions.at(j));
		setText(projectdoc,propertygroup,"PlatformToolset",ui.VSVersion->currentText());
		propertygroup=propertygroup.nextSiblingElement("PropertyGroup");
	}

	while(propertygroup.attribute("Label")!="UserMacros")
	{
		propertygroup=propertygroup.nextSiblingElement("PropertyGroup");
	}
	if(propertygroup.isNull())
	{
		propertygroup=projectroot.appendChild(projectdoc->createElement("PropertyGroup")).toElement();
		propertygroup.setAttribute("Label","UserMacros");
	}
	propertygroup=propertygroup.nextSiblingElement("PropertyGroup");

	for(j=0;j<m;j++)
	{
		if(propertygroup.isNull())
		{
			propertygroup=projectroot.appendChild(projectdoc->createElement("PropertyGroup")).toElement();
		}
		propertygroup.setAttribute("Condition",conditions.at(j));
		if(ui.Library->isChecked())
		{
            setText(projectdoc,propertygroup,"OutDir","$(RobotSDK_SharedLibrary)");
		}
		else if(ui.Application->isChecked())
		{
            setText(projectdoc,propertygroup,"OutDir","$(SolutionDir)\\$(Configuration)\\");
		}
        setText(projectdoc,propertygroup,"IncludePath","$(RobotSDK_Kernel)\\include;$(RobotSDK_ModuleDev);$(RobotSDK_Module);$(RobotDep_Include);$(IncludePath)");
        setText(projectdoc,propertygroup,"LibraryPath","$(RobotSDK_Kernel)\\lib\\$(Configuration);$(RobotDep_Lib);$(LibraryPath)");
		propertygroup=propertygroup.nextSiblingElement("PropertyGroup");
	}
	while(!propertygroup.isNull())
	{
		QDomElement tmpelem=propertygroup.nextSiblingElement("PropertyGroup");
		projectroot.removeChild(propertygroup).clear();
		propertygroup=tmpelem;
	}

	QDomElement itemdefine=projectroot.firstChildElement("ItemDefinitionGroup");
	while(!itemdefine.isNull())
	{
		int conditionsid=conditions.indexOf(itemdefine.attribute("Condition"));
		if(conditionsid<0)
		{
			continue;
		}
		QDomElement predefineelem=itemdefine.firstChildElement("ClCompile").firstChildElement("PreprocessorDefinitions");
		QString predefine=predefineelem.text();

		if(ui.Library->isChecked())
		{
            if(!predefine.contains("RobotSDK_ModuleDev"))
			{
                predefine=QString("RobotSDK_ModuleDev;")+predefine;
			}
		}
		else
		{
            if(predefine.contains("RobotSDK_ModuleDev"))
			{
                predefine.remove(QString("RobotSDK_ModuleDev;"));
                predefine.remove(QString("RobotSDK_ModuleDev"));
			}
		}
		{
			QDomNode tmpnode=predefineelem.firstChild();
			while(!tmpnode.isNull()&&!tmpnode.isText())
			{
				tmpnode=tmpnode.nextSibling();
			}
			if(!tmpnode.isNull())
			{
				tmpnode.toText().setData(predefine);
			}
		}
		if(ui.Library->isChecked())
		{
			QDomElement outputfileelem=itemdefine.firstChildElement("Link").firstChildElement("OutputFile");
			QString outputfile=outputfileelem.text();
            outputfile=QString("$(OutDir)\\$(ProjectName)_$(Configuration).dll");
			QDomNode tmpnode=outputfileelem.firstChild();
			while(!tmpnode.isNull()&&!tmpnode.isText())
			{
				tmpnode=tmpnode.nextSibling();
			}
			if(!tmpnode.isNull())
			{
				tmpnode.toText().setData(outputfile);
			}
		}
		itemdefine=itemdefine.nextSiblingElement("ItemDefinitionGroup");
	}

	file.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream textstream(&file);
	projectdoc->save(textstream,2);
	file.close();
	delete projectdoc;
}
/*!
	Write data out to the file
*/
void Preferences::writeData()
{
    QDomDocument doc("preferences");

    // create the root element
    QDomElement root = doc.createElement(doc.doctype().name());
    root.setAttribute("version", d->version_);
    root.setAttribute("application", d->format_);

    // now do our options group by group
    QMap<QString, PreferencesPrivate::PrefMap>::Iterator git;
	PreferencesPrivate::PrefMap::Iterator pit;
    QDomElement group, option;
    for (git = d->groups_.begin(); git != d->groups_.end(); ++git) {
		// comment the group
		QString commentText = getGroupDoc(git.key());

		if (commentText != QString::null)
		{
			root.appendChild(doc.createTextNode("\n\n  "));
			root.appendChild(doc.createComment("\n  " + commentText.replace("\n", "\n  ") + "\n  "));
			root.appendChild(doc.createTextNode("\n  "));
		}

        // create a group element
        group = doc.createElement("group");
        group.setAttribute("name", git.key());
        // add in options
        for (pit = (*git).begin(); pit != (*git).end(); ++pit)
		{
			QString commentText = getEntryDoc(git.key(), pit.key());

			if (commentText != QString::null)
			{
				group.appendChild(doc.createTextNode("\n\n    "));
				group.appendChild(doc.createComment(" " + commentText.replace("\n", "\n      ") + " "));
				group.appendChild(doc.createTextNode("\n    "));
			}

            option = doc.createElement("option");
            option.setAttribute("key", pit.key());
            option.setAttribute("value", pit.data());
            group.appendChild(option);
        }
        root.appendChild(group);
    }
    doc.appendChild(root);

    // open file
    QFile datafile(d->file_);
    if (!datafile.open(IO_WriteOnly)) {
        // error opening file
        qWarning("Error: Cannot open preferences file " + d->file_);
        d->filestate_ = false;
        return;
    }
    d->filestate_ = true;

    // write it out
    QTextStream textstream(&datafile);
    doc.save(textstream, 2);
    datafile.close();
    d->formatstate_ = true;
}
Esempio n. 15
0
/**
 * @brief HashProject::openFile
 * @param filename
 * @return True if successful.
 *
 * Reads a SFV file and loads the list of files along with their values into a new file list.
 * See also HashProject::saveFile.
 */
bool HashProject::openFile(QString filename)
{
   if (!filelist->writeLock(true)) {
      QMessageBox::critical(0, "Error", "Can't load a new SFV file while data processing is in progress.");
      return false;
   }
   QFile file(filename);
   if (!file.exists()) {
      return false;
   }
   if (!file.open(QFile::ReadOnly)) {
      filelist->writeLock(false);
      return false;
   }

   filelist->clearContents();

   QTextStream textstream(&file);
   QString inpath = QFileInfo(filename).path();
   QString algorithm = "CRC32";

   QHash<QString, HashProject::File> newFiles;
   QLinkedList<QString> filesOrder;
   while(!textstream.atEnd()) {
      QString textline = textstream.readLine();
      bool isComment = false;
      if ((textline.indexOf(";") != -1) &&
          (textline.mid(0, textline.indexOf(";")).simplified().length() == 0)) {
         // Line starts with ;
         // Either comment or metadata
         isComment = true;
      }
      int algorithmSettingPos = textline.indexOf(algorithmSettingName);
      if (isComment && algorithmSettingPos != -1) {
         // It's algorithm metadata, use the new value for the following list entries.
         algorithm = textline.right(textline.length() - algorithmSettingPos - algorithmSettingName.length());
      } else {
         QStringList elements(textline);
         QString outfilename;
         QString filesize;
         if (isComment && textline.length() > 36) {
            filesize = textline.mid(1, 13).trimmed();
            textline = textline.right(textline.length() - 36);
         }
         if (textline.count("\"") > 1) {
            int firstPos = textline.indexOf("\"");
            int lastPos = textline.lastIndexOf("\"");
            outfilename = textline.mid(firstPos+1, lastPos-firstPos-1);
            textline.remove(firstPos+1, lastPos-firstPos-1);
         }
         elements = textline.split(" ", QString::SkipEmptyParts);
         if (outfilename.isNull()) {
            outfilename = elements.first();
         }
         elements.removeFirst();
         QString hash;
         if (elements.length() > 0) {
            hash = elements.takeLast();
         }
         HashProject::File newfile;
         if (newFiles.contains(outfilename)) {
            newfile = newFiles[outfilename];
         } else {
            filesOrder.push_back(outfilename);
         }
         if (!filesize.isNull()) {
            newfile.filesize = filesize.toInt();
         }
         if (!isComment) {
            newfile.filename = outfilename;
            newfile.hash = hash;
            newfile.algorithm = algorithm;
         }
         newFiles[outfilename] = newfile;
      }
   }

   QLinkedListIterator<QString> i(filesOrder);
   while (i.hasNext()) {
      HashProject::File newfile = newFiles[i.next()];
      if (!newfile.filename.isNull()) {
         filelist->addFile(newfile);
      }
   }

   sourceDirectory->setPath(inpath);
   verifyDirectory->setPath(inpath);

   filelist->fileAdditionFinished();
   file.close();
   return true;
}