示例#1
0
void ThreadedTracer::run(){

qDebug()<<"loadScan input: "<<latestString;
//QString latestString = getFileString();
//    latestString =QString("/data/mat/BRL/DATA_FOR_GROUP/testDataForZhi/ZSeries-06092016-1407-8470/ZSeries-06092016-1407-8470_Cycle00001_Ch1_000001.ome.tif");
//    bool isAdaptive = 1;
//    int methodChoice = 1;

//LandmarkList inputRootList;
QString fString;
fString = QString("Cycle%1").arg(tileNumber,5,10,QLatin1Char('0'));
qDebug()<<tileNumber;

QList<LandmarkList> newTipsList;
LandmarkList newTargetList;

QFileInfo imageFileInfo = QFileInfo(latestString);
if (imageFileInfo.isReadable()){
    Image4DSimple * pNewImage = cb->loadImage(latestString.toLatin1().data());
    QDir imageDir =  imageFileInfo.dir();
    QStringList filterList;
    filterList.append(QString("*").append(fString).append("_Ch").append(channel).append("*.tif"));
    qDebug()<<"filterlist.first()"<<filterList.first();
    imageDir.setNameFilters(filterList);
    QStringList fileList = imageDir.entryList();

    //use this to id the number of images in the stack (in one channel?!)
    V3DLONG x = pNewImage->getXDim();
    V3DLONG y = pNewImage->getYDim();
    V3DLONG nFrames = fileList.length();

    V3DLONG tunits = x*y*nFrames;
    unsigned short int * total1dData = new unsigned short int [tunits];
    unsigned short int * total1dData_mip= new unsigned short int [x*y];
    for(V3DLONG i =0 ; i < x*y; i++)
        total1dData_mip[i] = 0;
    V3DLONG totalImageIndex = 0;
    double p_vmax=0;
    qDebug()<<"nFrames = "<<nFrames;
    for (int f=0; f<nFrames; f++){
        qDebug()<<fileList[f];
        Image4DSimple * pNewImage = cb->loadImage(imageDir.absoluteFilePath(fileList[f]).toLatin1().data());
        if (pNewImage->valid()){
            unsigned short int * data1d = 0;
            data1d = new unsigned short int [x*y];
            data1d = (unsigned short int*)pNewImage->getRawData();
            for (V3DLONG i = 0; i< (x*y); i++)
            {
                total1dData[totalImageIndex]= data1d[i];
                if(data1d[i] > p_vmax) p_vmax = data1d[i];
                if(total1dData_mip[i] < data1d[i]) total1dData_mip[i] = data1d[i];
                totalImageIndex++;
            }
            if(data1d) {delete []data1d; data1d = 0;}
        }else{
            qDebug()<<imageDir.absoluteFilePath(fileList[f])<<" failed!";
        }
    }

    Image4DSimple* total4DImage = new Image4DSimple;
    total4DImage->setData((unsigned char*)total1dData, x, y, nFrames, 1, V3D_UINT16);

    Image4DSimple* total4DImage_mip = new Image4DSimple;
    total4DImage_mip->setData((unsigned char*)total1dData_mip, x, y, 1, 1, V3D_UINT16);


    QString swcString = saveDirString;
    swcString.append("/x_").append(QString::number((int)tileLocation.x)).append("_y_").append(QString::number((int)tileLocation.y)).append("_").append(imageFileInfo.fileName()).append(fString).append(".swc");


    QString scanDataFileString = saveDirString;
    scanDataFileString.append("/").append("scanData.txt");
    qDebug()<<scanDataFileString;
    QFile saveTextFile;
    saveTextFile.setFileName(scanDataFileString);// add currentScanFile
    if (!saveTextFile.isOpen()){
        if (!saveTextFile.open(QIODevice::Text|QIODevice::Append  )){
            qDebug()<<"unable to save file!";
            return;}     }
    QTextStream outputStream;
    outputStream.setDevice(&saveTextFile);
    total4DImage->setOriginX(tileLocation.x);
    total4DImage->setOriginY(tileLocation.y);

    qDebug()<<total4DImage->getOriginX();


    outputStream<< (int) total4DImage->getOriginX()<<" "<< (int) total4DImage->getOriginY()<<" "<<swcString<<" "<< (int) x<<" "<< (int) y<<" "<<"\n";

    saveTextFile.close();
    V3DLONG mysz[4];
    mysz[0] = total4DImage->getXDim();
    mysz[1] = total4DImage->getYDim();
    mysz[2] = total4DImage->getZDim();
    mysz[3] = total4DImage->getCDim();

    tileLocation.ev_pc1 = (double) total4DImage->getXDim();
    tileLocation.ev_pc2 = (double) total4DImage->getYDim();


    QString imageSaveString = saveDirString;


    // add bit of code to image green - red channels. This will require an additional argument or another signal/slot combination to monitor the value of a combobox in the GUI...
    // add button to do || nT on mXtls




    //convert to 8bit image using 8 shiftnbits
    unsigned char * total1dData_8bit = 0;
    try
    {
        total1dData_8bit = new unsigned char [tunits];
    }
    catch (...)
    {
        v3d_msg("Fail to allocate memory in total1dData_8bit.\n");

        return;
    }
    double dn = pow(2.0, double(5));
    for (V3DLONG i=0;i<tunits;i++)
    {
        double tmp = (double)(total1dData[i]) / dn;
        if (tmp>255) total1dData_8bit[i] = 255;
        else
            total1dData_8bit[i] = (unsigned char)(tmp);
    }




    total4DImage->setData((unsigned char*)total1dData_8bit, x, y, nFrames, 1, V3D_UINT8);

    imageSaveString.append("/x_").append(QString::number((int)tileLocation.x)).append("_y_").append(QString::number((int)tileLocation.y)).append("_").append(imageFileInfo.fileName()).append(imageFileInfo.fileName()).append(fString).append(".v3draw");
    simple_saveimage_wrapper(*cb, imageSaveString.toLatin1().data(),(unsigned char *)total1dData_8bit, mysz, V3D_UINT8);
    qDebug()<<"=== immediately before tracing =====";
//-------------
    V3DPluginArgItem arg;
    V3DPluginArgList input;
    V3DPluginArgList output;

    QString full_plugin_name;
    QString func_name;

    arg.type = "random";std::vector<char*> arg_input;
    std:: string fileName_Qstring(imageSaveString.toStdString());char* fileName_string =  new char[fileName_Qstring.length() + 1]; strcpy(fileName_string, fileName_Qstring.c_str());
    arg_input.push_back(fileName_string);
    arg.p = (void *) & arg_input; input<< arg;

    char* char_swcout =  new char[swcString.length() + 1];strcpy(char_swcout, swcString.toStdString().c_str());
    arg.type = "random";std::vector<char*> arg_output;arg_output.push_back(char_swcout); arg.p = (void *) & arg_output; output<< arg;

    arg.type = "random";
    std::vector<char*> arg_para;



    arg_para.push_back("1");
    arg_para.push_back("1");
    full_plugin_name = "neuTube";
    func_name =  "neutube_trace";

    arg.p = (void *) & arg_para; input << arg;

    if(!cb->callPluginFunc(full_plugin_name,func_name,input,output))
    {

         qDebug()<<("Can not find the tracing plugin!\n");

         return;
    }
    emit done();

}else{
    qDebug()<<"invalid image";
}
}
void LoacalFileServer::display(QString* currentPath)
{
	//QString currentPath = root;
	this->setWindowTitle("LocalFileServer : "+(*currentPath));
	QDir rootDir(*currentPath);
	QList<QTreeWidgetItem *> itemList;
	QStringList tmplist;
	tmplist << "*";
	QFileInfoList list = rootDir.entryInfoList(tmplist);

	for(unsigned int i = 0;i<list.count();i++)
	{
		QFileInfo tmpFileInfo = list.at(i);

		QTreeWidgetItem *item = new QTreeWidgetItem;
		
		if(tmpFileInfo.fileName() == "." || tmpFileInfo.fileName() == "..")
				continue;

		item->setText(0,tmpFileInfo.fileName());
		
		if(tmpFileInfo.isDir())
		{
			item->setText(1,QString(""));
		}
		else
		{
			item->setText(1,QString::number(tmpFileInfo.size()));
		}
		
		item->setText(2,tmpFileInfo.created().toString("MMM dd yyyy"));
		
		item->setText(3,tmpFileInfo.lastModified().toString("MMM dd yyyy"));

		QPixmap pixmap(tmpFileInfo.isDir()?"./dir.png":"./file.png");
		item->setIcon(0,pixmap);
		
		itemList.push_back(item);

		//the path is whether the directory
		isDirectory[tmpFileInfo.fileName()] = tmpFileInfo.isDir();
	}

	fileWidget->addTopLevelItems(itemList);
}
示例#3
0
void GitWrapper::commitBasket(BasketScene *basket)
{
    GIT_RETURN_IF_DISABLED()
    QMutexLocker l(&gitMutex);
    git_repository* repo = openRepository();
    if(repo==0)
        return;

    const QDateTime gitdate = getLastCommitDate(repo);

    const QString fullpath = basket->fullPath();
    const QDir basketdir(fullpath);
    bool changed = false;
    QDirIterator it(basketdir);
    while(!changed && it.hasNext())
    {
        const QFileInfo file(it.next());
        if(file.fileName() != ".basket")
        {
            if(file.lastModified() >= gitdate)
                changed = true;
        }
    }

    if(changed)
    {
        git_index *index = NULL;

        int error = git_repository_index(&index, repo);
        if(error < 0)
        {
            gitErrorHandling();
            return;
        }

        const QString pattern("baskets/" + basket->folderName() + "*");

        QByteArray patternba = pattern.toUtf8();
        char *patternCString = patternba.data();
        git_strarray arr = { &patternCString, 1};
        error = git_index_add_all(index, &arr, 0, 0, 0);
        if(error < 0)
        {
            gitErrorHandling();
            return;
        }
        const QString basketxml("baskets/baskets.xml");
        QByteArray basketxmlba = basketxml.toUtf8();
        char *basketxmlCString = basketxmlba.data();
        error = git_index_add_bypath(index, basketxmlCString);
        if(error < 0)
        {
            gitErrorHandling();
            return;
        }

        removeDeletedFromIndex(repo,index);

        bool result = commitIndex(repo,index);

        git_index_free(index);
    }

    git_repository_free(repo);
}
示例#4
0
void ThumbView::handleSelectionChanged(const QItemSelection&)
{
	QString info;
	QModelIndexList indexesList = selectionModel()->selectedIndexes();
	int nSelected = indexesList.size();
	QString imageFullPath;
	QString statusStr;

	infoView->clear();

	if (nSelected == 1) {
		QString imageFullPath = thumbViewModel->item(indexesList.first().row())->data(FileNameRole).toString();
		imageInfoReader.setFileName(imageFullPath);
		QString key;
		QString val;

		QFileInfo imageInfo = QFileInfo(imageFullPath);
		infoView->addTitleEntry(tr("General"));

		key = tr("File name");
		val = imageInfo.fileName();
		infoView->addEntry(key, val);

		key = tr("Location");
		val = imageInfo.path();
		infoView->addEntry(key, val);

		key = tr("Size");
		val = QString::number(imageInfo.size() / 1024.0, 'f', 2) + "K";
		infoView->addEntry(key, val);

		key = tr("Modified");
		val = imageInfo.lastModified().toString(Qt::SystemLocaleShortDate);
		infoView->addEntry(key, val);

		if (imageInfoReader.size().isValid()) {
			key = tr("Format");
			val = imageInfoReader.format().toUpper();
			infoView->addEntry(key, val);

			key = tr("Resolution");
			val = QString::number(imageInfoReader.size().width())
					+ "x"
					+ QString::number(imageInfoReader.size().height());
			infoView->addEntry(key, val);

			key = tr("Megapixel");
			val = QString::number((imageInfoReader.size().width() * imageInfoReader.size().height()) / 1000000.0, 'f', 2);
			infoView->addEntry(key, val);

			updateExifInfo(imageFullPath);
			recentThumb = imageFullPath;
		} else {
			imageInfoReader.read();
			key = tr("Error");
			val = imageInfoReader.errorString();
			infoView->addEntry(key, val);
		}
	}

	if (imageTags->currentDisplayMode == SelectionTagsDisplay) {
		imageTags->showSelectedImagesTags();
	}

	/* update status bar */
	if (!nSelected) {
		updateThumbsCount();
		return;
	} else if (nSelected >= 1) {
		statusStr = tr("Selected %1 of%2")
					.arg(QString::number(nSelected))
					.arg(tr(" %n image(s)", "", thumbViewModel->rowCount()));
	}

	emit setStatus(statusStr);
}
示例#5
0
QStringList ScribusQApp::getLang(QString lang)
{
	QStringList langs;

	// read the locales
	if (!lang.isEmpty())
		langs.push_back(lang);

	//add in user preferences lang, only overridden by lang command line option
	QString Pff = QDir::toNativeSeparators(ScPaths::getApplicationDataDir());
	QFileInfo Pffi = QFileInfo(Pff);
	if (Pffi.exists())
	{
		QString PrefsPfad;
		if (Pffi.isDir())
			PrefsPfad = Pff;
		else
			PrefsPfad = QDir::homePath();
		QString prefsXMLFile=QDir::toNativeSeparators(PrefsPfad + "/prefs140.xml");
		QFileInfo infoPrefsFile(prefsXMLFile);
		if (infoPrefsFile.exists())
		{
			PrefsFile* prefsFile = new PrefsFile(prefsXMLFile);
			if (prefsFile) {
				PrefsContext* userprefsContext = prefsFile->getContext("user_preferences");
				if (userprefsContext) {
					QString prefslang = userprefsContext->get("gui_language","");
					if (!prefslang.isEmpty())
						langs.push_back(prefslang);
				}
			}
			delete prefsFile;
		}
	}

	if (!(lang = ::getenv("LC_ALL")).isEmpty())
		langs.push_back(lang);
	if (!(lang = ::getenv("LC_MESSAGES")).isEmpty())
		langs.push_back(lang);
	if (!(lang = ::getenv("LANG")).isEmpty())
		langs.push_back(lang);

#if defined(_WIN32)
	wchar_t out[256];
	QString language, sublanguage;
	LCID lcIdo = GetUserDefaultLCID();
	WORD sortId = SORTIDFROMLCID(lcIdo);
	LANGID langId = GetUserDefaultUILanguage();
	LCID lcIdn = MAKELCID(langId, sortId);
	if ( GetLocaleInfoW(lcIdn, LOCALE_SISO639LANGNAME , out, 255) )
	{
		language = QString::fromUtf16( (ushort*)out );
		if ( GetLocaleInfoW(lcIdn, LOCALE_SISO3166CTRYNAME, out, 255) )
		{
			sublanguage = QString::fromUtf16( (ushort*)out ).toLower();
			lang = language;
			if ( sublanguage != language && !sublanguage.isEmpty() )
				lang += "_" + sublanguage.toUpper();
			langs.push_back(lang);
		}
	}
#endif

	langs.push_back(QString(QLocale::system().name()));

	// remove duplicate entries...
	QStringList::Iterator it = langs.end();
	while (it != langs.begin())
	{
		--it;
		if (langs.count(*it) > 1)
			it = langs.erase(it);
	}

	return langs;
}
示例#6
0
// IRIX 6.x
void qt_parseSpoolInterface(QList<QPrinterDescription> *printers)
{
    QDir lp(QLatin1String("/usr/spool/lp/interface"));
    if (!lp.exists())
        return;
    QFileInfoList files = lp.entryInfoList();
    if(files.isEmpty())
        return;

    for (int i = 0; i < files.size(); ++i) {
        QFileInfo printer = files.at(i);

        if (!printer.isFile())
            continue;

        // parse out some information
        QFile configFile(printer.filePath());
        if (!configFile.open(QIODevice::ReadOnly))
            continue;

        QByteArray line;
        line.resize(1025);
        QString namePrinter;
        QString hostName;
        QString hostPrinter;
        QString printerType;

        QString nameKey(QLatin1String("NAME="));
        QString typeKey(QLatin1String("TYPE="));
        QString hostKey(QLatin1String("HOSTNAME="));
        QString hostPrinterKey(QLatin1String("HOSTPRINTER="));

        while (!configFile.atEnd() &&
                (configFile.readLine(line.data(), 1024)) > 0) {
            QString uline = QString::fromLocal8Bit(line);
            if (uline.startsWith(typeKey) ) {
                printerType = uline.mid(nameKey.length());
                printerType = printerType.simplified();
            } else if (uline.startsWith(hostKey)) {
                hostName = uline.mid(hostKey.length());
                hostName = hostName.simplified();
            } else if (uline.startsWith(hostPrinterKey)) {
                hostPrinter = uline.mid(hostPrinterKey.length());
                hostPrinter = hostPrinter.simplified();
            } else if (uline.startsWith(nameKey)) {
                namePrinter = uline.mid(nameKey.length());
                namePrinter = namePrinter.simplified();
            }
        }
        configFile.close();

        printerType = printerType.trimmed();
        if (printerType.indexOf(QLatin1String("postscript"), 0, Qt::CaseInsensitive) < 0)
            continue;

        int ii = 0;
        while ((ii = namePrinter.indexOf(QLatin1Char('"'), ii)) >= 0)
            namePrinter.remove(ii, 1);

        if (hostName.isEmpty() || hostPrinter.isEmpty()) {
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 QLatin1String(""), namePrinter);
        } else {
            QString comment;
            comment = namePrinter;
            comment += QLatin1String(" (");
            comment += hostPrinter;
            comment += QLatin1Char(')');
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 hostName, comment);
        }
    }
}
示例#7
0
void beamtest::writebinarytochunkswithcolor()
	{
QFileInfo fileInfo;

QString filename = QFileDialog::getOpenFileName ( this,tr("Import File"),
												 "",tr( "All point cloud formats (*.ptx);;"
												 "XYZ (*.xyz *XYZ);;"
												 "PTX (*.ptx *.PTX)"));



	
		 int chunk = 2000000;
		 //int numfiles = floor((double) shapecount / (double) chunk);
		 int shapecounter=0;
		 int filecounter = 0;

double chunksize= 2000000;
int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveBinary"), " ",tr("dat (*.dat "));
QFile file2(filename2);
 file2.open(QIODevice::WriteOnly);
 QDataStream out(&file2);   // we will serialize the data into the file

 	fileInfo.setFile(filename2);

	QString dirname = fileInfo.absoluteDir().absolutePath();
	filename = fileInfo.fileName();
	QString basename = fileInfo.baseName();
	QString bundlename = fileInfo.bundleName();

 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
			
			double x = linelist.at(0).toDouble();
            double y = linelist.at(1).toDouble();
            double z = linelist.at(2).toDouble();
			double intensity= linelist.at(3).toDouble();
			if(x != 0 && y != 0 && z != 0 )
			{
			count++;
			shapecounter++;
				if(shapecounter == chunk)
					{
					
					shapecounter = 0;
					filecounter++;
					QString curfilename = dirname + tr("/") + basename + QString::number(filecounter) + tr(".data");
					file2.close();
					file2.setFileName(curfilename);
					file2.open(QFile::WriteOnly);
					
			
					}


			if (count % 100000 == 0) qDebug() << count;

			out << x << y << z << intensity;
			}

        }

   //if (count > 10000) break;


    }
        }while (lineLength != -1);
 }


if(file2.isOpen()) file2.close();






	}
extern "C" Q_DECL_EXPORT
int generate()
{
    Options::headerList = ParserOptions::headerList;
    
    QFileInfo smokeConfig;
    
    const QStringList& args = QCoreApplication::arguments();
    for (int i = 0; i < args.count(); i++) {
        if ((args[i] == "-m" || args[i] == "-p" || args[i] == "-pm" || args[i] == "-o" ||
             args[i] == "-st" || args[i] == "-vt" || args[i] == "-smokeconfig") && i + 1 >= args.count())
        {
            qCritical() << "generator_smoke: not enough parameters for option" << args[i];
            return EXIT_FAILURE;
        } else if (args[i] == "-m") {
            Options::module = args[++i];
        } else if (args[i] == "-p") {
            bool ok = false;
            Options::parts = args[++i].toInt(&ok);
            if (!ok) {
                qCritical() << "generator_smoke: couldn't parse argument for option" << args[i - 1];
                return EXIT_FAILURE;
            }
        } else if (args[i] == "-pm") {
            Options::parentModules = args[++i].split(',');
        } else if (args[i] == "-st") {
            Options::scalarTypes = args[++i].split(',');
        } else if (args[i] == "-vt") {
            Options::voidpTypes = args[++i].split(',');
        } else if (args[i] == "-smokeconfig") {
            smokeConfig = QFileInfo(args[++i]);
        } else if (args[i] == "-o") {
            Options::outputDir = QDir(args[++i]);
        } else if (args[i] == "-h" || args[i] == "--help") {
            showUsage();
            return EXIT_SUCCESS;
        }
    }
    
    if (smokeConfig.exists()) {
        QFile file(smokeConfig.filePath());
        file.open(QIODevice::ReadOnly);
        QDomDocument doc;
        doc.setContent(file.readAll());
        file.close();
        QDomElement root = doc.documentElement();
        QDomNode node = root.firstChild();
        while (!node.isNull()) {
            QDomElement elem = node.toElement();
            if (elem.isNull()) {
                node = node.nextSibling();
                continue;
            }
            if (elem.tagName() == "outputDir") {
                Options::outputDir = QDir(elem.text());
            } else if (elem.tagName() == "moduleName") {
                Options::module = elem.text();
            } else if (elem.tagName() == "parts") {
                Options::parts = elem.text().toInt();
            } else if (elem.tagName() == "parentModules") {
                QDomNode parent = elem.firstChild();
                while (!parent.isNull()) {
                    QDomElement elem = parent.toElement();
                    if (elem.isNull()) {
                        parent = parent.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "module") {
                        Options::parentModules << elem.text();
                    }
                    parent = parent.nextSibling();
                }
            } else if (elem.tagName() == "scalarTypes") {
                QDomNode typeName = elem.firstChild();
                while (!typeName.isNull()) {
                    QDomElement elem = typeName.toElement();
                    if (elem.isNull()) {
                        typeName = typeName.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "typeName") {
                        Options::scalarTypes << elem.text();
                    }
                    typeName = typeName.nextSibling();
                }
            } else if (elem.tagName() == "voidpTypes") {
                QDomNode typeName = elem.firstChild();
                while (!typeName.isNull()) {
                    QDomElement elem = typeName.toElement();
                    if (elem.isNull()) {
                        typeName = typeName.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "typeName") {
                        Options::voidpTypes << elem.text();
                    }
                    typeName = typeName.nextSibling();
                }
            } else if (elem.tagName() == "classList") {
                QDomNode klass = elem.firstChild();
                while (!klass.isNull()) {
                    QDomElement elem = klass.toElement();
                    if (elem.isNull()) {
                        klass = klass.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "class") {
                        Options::classList << elem.text();
                    }
                    klass = klass.nextSibling();
                }
            } else if (elem.tagName() == "exclude") {
                QDomNode typeName = elem.firstChild();
                while (!typeName.isNull()) {
                    QDomElement elem = typeName.toElement();
                    if (elem.isNull()) {
                        typeName = typeName.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "signature") {
                        Options::excludeExpressions << QRegExp(elem.text());
                    }
                    typeName = typeName.nextSibling();
                }
            } else if (elem.tagName() == "functions") {
                QDomNode function = elem.firstChild();
                while (!function.isNull()) {
                    QDomElement elem = function.toElement();
                    if (elem.isNull()) {
                        function = function.nextSibling();
                        continue;
                    }
                    if (elem.tagName() == "name") {
                        Options::includeFunctionNames << QRegExp(elem.text());
                    } else if (elem.tagName() == "signature") {
                        Options::includeFunctionSignatures << QRegExp(elem.text());
                    }
                    function = function.nextSibling();
                }
            }
            node = node.nextSibling();
        }
    } else {
        qWarning() << "Couldn't find config file" << smokeConfig.filePath();
    }
    
    if (!Options::outputDir.exists()) {
        qWarning() << "output directoy" << Options::outputDir.path() << "doesn't exist; creating it...";
        QDir::current().mkpath(Options::outputDir.path());
    }
    
    Options::qtMode = ParserOptions::qtMode;

    Options::voidpTypes << "long long" << "long long int" << "unsigned long long" << "unsigned long long int";
    
    // Fill the type map. It maps some long integral types to shorter forms as used in SMOKE.
    Util::typeMap["long int"] = "long";
    Util::typeMap["short int"] = "short";
    Util::typeMap["long double"] = "double";
    Util::typeMap["wchar_t"] = "int";   // correct?
    
    qDebug() << "Generating SMOKE sources...";
    
    SmokeDataFile smokeData;
    smokeData.write();
    SmokeClassFiles classFiles(&smokeData);
    classFiles.write();
    
    qDebug() << "Done.";
    
    return EXIT_SUCCESS;
}
QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
                                       QString *initialDirectory,
                                       QString *selectedFilter)
{
    QFileInfo fi;
    QDir dir;

    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
        initialDirectory->remove(0, 5);
    fi = QFileInfo(*initialDirectory);

    if (initialDirectory && !fi.isDir()) {
        *initialDirectory = fi.absolutePath();
    }

    if (!fi.exists())
        *initialDirectory = QDir::homePath();

    DWORD selFilIdx = 0;

    QStringList filterLst = qt_win_make_filters_list(args.filter);
    int idx = 0;
    if (selectedFilter) {
        idx = filterLst.indexOf(*selectedFilter);
    }
    // Windows Vista (& above) allows users to search from file dialogs. If user selects
    // multiple files belonging to different folders from these search results, the
    // GetOpenFileName() will return only one folder name for all the files. To retrieve
    // the correct path for all selected files, we have to use Common Item Dialog interfaces.
#ifndef Q_WS_WINCE
    if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))
        return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
#endif

    QStringList result;
    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
    OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
                                        args.directory, args.caption,
                                        qt_win_filter(args.filter, hideFiltersDetails),
                                        QFileDialog::ExistingFiles,
                                        args.options);
    if (idx)
        ofn->nFilterIndex = idx + 1;
    if (GetOpenFileName(ofn)) {
        QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
        selFilIdx = ofn->nFilterIndex;
        int offset = fileOrDir.length() + 1;
        if (ofn->lpstrFile[offset] == 0) {
            // Only one file selected; has full path
            fi.setFile(fileOrDir);
            QString res = fi.absoluteFilePath();
            if (!res.isEmpty())
                result.append(res);
        }
        else {
            // Several files selected; first string is path
            dir.setPath(fileOrDir);
            QString f;
            while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
                fi.setFile(dir, f);
                QString res = fi.absoluteFilePath();
                if (!res.isEmpty())
                    result.append(res);
                offset += f.length() + 1;
            }
        }
    }
    qt_win_clean_up_OFN(&ofn);

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (!result.isEmpty()) {
        *initialDirectory = fi.path();    // only save the path if there is a result
        if (selectedFilter)
            *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
    }
    return result;
}
示例#10
0
			bool PackageProcessor::HandleEntry (int packageId, const QFileInfo& fi,
					const QString& stagingDir, QDir& packageDir)
			{
				QFile dbFile (DBDir_.filePath (QString::number (packageId)));
				if (!dbFile.open (QIODevice::WriteOnly | QIODevice::Append))
				{
					qWarning () << Q_FUNC_INFO
							<< "could not open DB file"
							<< dbFile.fileName ()
							<< "for write:"
							<< dbFile.errorString ();
					return false;
				}

				QString sourceName = fi.absoluteFilePath ();
				sourceName = sourceName.mid (stagingDir.length ());
				if (sourceName.at (0) == '/')
					sourceName = sourceName.mid (1);

				if (fi.isFile ())
				{
					QString destName = packageDir.filePath (sourceName);
#ifndef QT_NO_DEBUG
					qDebug () << Q_FUNC_INFO
							<< "gotta copy"
							<< fi.absoluteFilePath ()
							<< "to"
							<< destName;
#endif

					QFile file (fi.absoluteFilePath ());
					if (!file.copy (destName))
					{
						qWarning () << Q_FUNC_INFO
								<< "could not copy"
								<< fi.absoluteFilePath ()
								<< "to"
								<< destName
								<< "because of"
								<< file.errorString ();

						QString errorString = tr ("Could not copy file %1 because of %2.")
								.arg (sourceName)
								.arg (file.errorString ());
						emit packageInstallError (packageId, errorString);
						return false;
					}
				}
				else if (fi.isDir ())
				{
#ifndef QT_NO_DEBUG
					qDebug () << Q_FUNC_INFO
							<< "gotta create"
							<< sourceName
							<< "for"
							<< fi.absoluteFilePath ();
#endif

					if (!packageDir.mkpath (sourceName))
					{
						qWarning () << Q_FUNC_INFO
								<< "unable to mkdir"
								<< sourceName
								<< "in"
								<< packageDir.path ();

						QString errorString = tr ("Unable to create directory %1.")
								.arg (sourceName);
						emit packageInstallError (packageId, errorString);
						return false;
					}
				}

				dbFile.write (sourceName.toUtf8 ());
				dbFile.write ("\n");

				return true;
			}
示例#11
0
FileMatchContext::FileMatchContext(const QFileInfo &fi) :
    m_fileInfo(fi),
    m_fileName(fi.fileName()),
    m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable)
{
}
示例#12
0
			void PackageProcessor::handlePackageUnarchFinished (int ret, QProcess::ExitStatus)
			{
				sender ()->deleteLater ();

				QProcess *unarch = qobject_cast<QProcess*> (sender ());
				int packageId = unarch->property ("PackageID").toInt ();
				QString stagingDir = unarch->property ("StagingDirectory").toString ();
				Mode mode = static_cast<Mode> (unarch->property ("Mode").toInt ());

				if (ret)
				{
					QString errString = QString::fromUtf8 (unarch->readAllStandardError ());
					qWarning () << Q_FUNC_INFO
							<< "unpacker exited with"
							<< ret
							<< errString
							<< "for"
							<< packageId
							<< unarch->property ("Path").toString ();

					QString errorString = tr ("Unable to unpack package archive, unpacker exited with %1: %2.")
							.arg (ret)
							.arg (errString);
					emit packageInstallError (packageId, errorString);

					CleanupDir (stagingDir);

					return;
				}

				int oldId = -1;
				if (mode == MUpdate)
				{
					oldId = Core::Instance ().GetStorage ()->FindInstalledPackage (packageId);
					if (!CleanupBeforeUpdate (oldId, packageId))
					{
						qWarning () << Q_FUNC_INFO
								<< "unable to cleanup";
						return;
					}
				}

				QDir packageDir;
				try
				{
					packageDir = Core::Instance ().GetPackageDir (packageId);
				}
				catch (const std::exception& e)
				{
					qWarning () << Q_FUNC_INFO
							<< "while trying to get dir for package"
							<< packageId
							<< "got we exception"
							<< e.what ();
					QString errorString = tr ("Unable to get directory for the package: %1.")
							.arg (QString::fromUtf8 (e.what ()));
					emit packageInstallError (packageId, errorString);
					CleanupDir (stagingDir);
					return;
				}

				QDirIterator dirIt (stagingDir,
						QDir::NoDotAndDotDot |
							QDir::Readable |
							QDir::NoSymLinks |
							QDir::Dirs |
							QDir::Files,
						QDirIterator::Subdirectories);
				while (dirIt.hasNext ())
				{
					dirIt.next ();
					QFileInfo fi = dirIt.fileInfo ();

					if (fi.isDir () ||
							fi.isFile ())
						if (!HandleEntry (packageId, fi, stagingDir, packageDir))
						{
							try
							{
								Remove (packageId);
							}
							catch (const std::exception& e)
							{
								qWarning () << Q_FUNC_INFO
										<< "while removing partially installed package"
										<< packageId
										<< "got:"
										<< e.what ();
							}

							QString errorString = tr ("Unable to copy "
									"files from staging area to "
									"destination directory.");
							emit packageInstallError (packageId, errorString);
							CleanupDir (stagingDir);
							return;
						}
				}

				switch (mode)
				{
				case MInstall:
					emit packageInstalled (packageId);
					break;
				case MUpdate:
					emit packageUpdated (oldId, packageId);
					break;
				}
			}
示例#13
0
void SpawnMonitor::loadSpawnPoints()
{
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findExistingFile("spawnpoints", fileName, false);

  if (!fileInfo.exists())
  {
    seqWarn("Can't find spawn point file %s", 
	   (const char*)fileInfo.absFilePath());
    return;
  }
  
  fileName = fileInfo.absFilePath();

  QFile spFile(fileName);
  
  if (!spFile.open(IO_ReadOnly))
  {
    seqWarn( "Can't open spawn point file %s", (const char*)fileName );
    return;
  }
  
  QTextStream input( &spFile );
  
  int16_t x, y, z;
  unsigned long diffTime;
  uint32_t count;
  QString name;

  while (!input.atEnd())
  {
    input >> x;
    input >> y;
    input >> z;
    input >> diffTime;
    input >> count;
    name = input.readLine();
    name = name.stripWhiteSpace();
    
    EQPoint	loc(x, y, z);
    SpawnPoint*	p = new SpawnPoint( 0, loc, name, diffTime, count );
    if (p)
    {
      QString key = p->key();
      
      if (!m_points.find(key))
      {
	m_points.insert(key, p);
	emit newSpawnPoint(p);
      }
      else
      {
	seqWarn("Warning: spawn point key already in use!");
	delete p;
      }
    }
  }

  seqInfo("Loaded spawn points: %s", (const char*)fileName);
  m_modified = false;
}
示例#14
0
void SpawnMonitor::saveSpawnPoints()
{
  // only save if modified
  if (!m_modified)
    return;

  if ( !m_zoneName.length() )
  {
    seqWarn("Zone name not set in 'SpawnMonitor::saveSpawnPoints'!" );
    return;
  }
  
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findWriteFile("spawnpoints", fileName, false);

  fileName = fileInfo.absFilePath();

  QString newName = fileName + ".new";
  QFile spFile( newName );
  
  if (!spFile.open(IO_WriteOnly))
  {
    seqWarn("Failed to open %s for writing", (const char*)newName);
    return;
  }
  
  QTextStream output(&spFile);
  
  QAsciiDictIterator<SpawnPoint> it( m_points );
  SpawnPoint* sp;
  
  while ((sp = it.current()))
  {
    ++it;
    output	<< sp->x()
		<< " "
		<< sp->y()
		<< " "
		<< sp->z()
		<< " "
		<< (unsigned long)sp->diffTime()
		<< " "
		<< sp->count()
		<< " "
		<< sp->name()
		<< '\n';
  }
  
  spFile.close();
  
  QFileInfo fi( spFile );
  QFile old( fileName );
  QDir dir( fi.dir() );
  QString backupName = fileName + ".bak";
  
  if (old.exists())
  {
    if (dir.rename( fileName, backupName))
    {
      if (!dir.rename( newName, fileName))
	seqWarn( "Failed to rename %s to %s", 
		(const char*)newName, (const char*)fileName);
    }
  }
  else
  {
    if (!dir.rename(newName, fileName))
      seqWarn("Failed to rename %s to %s", 
	     (const char*)newName, (const char*)fileName);
  }
  m_modified = false;
  seqInfo("Saved spawn points: %s", (const char*)fileName);
}
void VSFolderObserver::onLoad( const QFileInfo& path )
{
    /**/
    volatile QString hoge = path.absoluteFilePath();
    QFile scriptFile( path.absoluteFilePath() );
    if( !scriptFile.exists() )
    {
        /* TODO ログ */
        return ;
    }
    /* ロードするインデックスを判定 */
    ShaderScripts& shaderScripts = cxt_->shaderScripts;
    ShaderScriptGroup& vsScripts = shaderScripts.vsScripts;
    int vi;
    for( vi=0;vi<vsScripts.numScript;++vi)
    {
        const ShaderScriptGroup& scriptGroup = vsScripts;
        const ShaderScript& script = scriptGroup.scripts[vi];
        QByteArray baBaseName = path.baseName().toLocal8Bit();
        if( !strcmp( baBaseName.data(), script.name ) ) 
        {
            NL_SAFE_RELEASE( cxt_->vss[vi].shader_ );
            NL_SAFE_RELEASE( cxt_->vss[vi].inputLayout_ );
            break;
        }
    }
    /**/
    ShaderScript& script = vsScripts.scripts[vi];
    /* ロードが初の場合 */
    if( vi == vsScripts.numScript )
    {
        /* 総ロード数を増やす */
        ++vsScripts.numScript;
        /* IDの再登録 */
        setId( groupName_, path.baseName() );
    }
    /* リロードになる場合 */
    else
    {
        /* スクリプト文字列の解放 */
        if( script.name )
        {
            free( script.name ); 
            script.name = NULL;
        }
        if( script.script )
        {
            free( script.script ); 
            script.script = NULL;
        }
    }
    /**/
    scriptFile.open(QIODevice::ReadOnly|QIODevice::Text);
    QByteArray scriptData = scriptFile.readAll();
    script.script = (nlInt8*)calloc((scriptData.size()+1)*sizeof(nlInt8),1);
    strcpy( script.script, scriptData.data() );
    QByteArray baBaseName = path.baseName().toLocal8Bit();
    script.name = (nlInt8*)calloc((baBaseName.size()+1)*sizeof(nlInt8),1);
    strcpy( script.name, baBaseName.data() );
    /* ターゲットをロードする */
    nlCreateShaders( ShaderType_VS, vi, shaderScripts, *cxt_ );
}
示例#16
0
bool processXmlFile(const QString &xmlFile)
{
    QFile file(xmlFile);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    const QLatin1String tag_app("app");
    const QLatin1String attrib_mainQmlFile("mainqmlfile");
    const QLatin1String attrib_projectPath("projectpath");
    const QLatin1String attrib_projectName("projectname");
    const QLatin1String attrib_screenOrientation("screenorientation");
    const QLatin1String value_screenOrientationLockLandscape("LockLandscape");
    const QLatin1String value_screenOrientationLockPortrait("LockPortrait");
    const QLatin1String attrib_networkAccess("networkaccess");

    static const QString qtDir =
        QLibraryInfo::location(QLibraryInfo::PrefixPath) + QLatin1Char('/');

    QXmlStreamReader reader(&file);
    while (!reader.atEnd()) {
        const QXmlStreamReader::TokenType token = reader.readNext();
        switch (token) {
        case QXmlStreamReader::StartElement:
            if (reader.name() == tag_app) {
                QtQuickApp app;
                QFileInfo projectPath;
                if (!reader.attributes().hasAttribute(attrib_projectPath)) {
                    qDebug() << "Project without path found";
                    continue;
                }
                projectPath = qtDir + reader.attributes().value(attrib_projectPath).toString();
                app.setProjectPath(projectPath.absoluteFilePath());
                if (reader.attributes().hasAttribute(attrib_mainQmlFile)) {
                    const QFileInfo qmlFileOrigin(
                        qtDir + reader.attributes().value(attrib_mainQmlFile).toString());
                    if (!qmlFileOrigin.exists()) {
                        qDebug() << "Cannot find" <<
                                 QDir::toNativeSeparators(qmlFileOrigin.absoluteFilePath());
                        continue;
                    }
                    const QFileInfo qmlTargetPath(QString(projectPath.absoluteFilePath()
                                                          + QLatin1Char('/') + qmlFileOrigin.baseName()
                                                          + QLatin1String("/qml")));
#ifdef Q_OS_WIN
                    const QString sourcePath =
                        QDir::toNativeSeparators(qmlFileOrigin.canonicalPath() + QLatin1String("/*"));
                    const QString targetPath =
                        QDir::toNativeSeparators(qmlTargetPath.absoluteFilePath() + QLatin1Char('/'));
                    QProcess xcopy;
                    QStringList parameters;
                    parameters << QLatin1String("/E") << sourcePath << targetPath;
                    xcopy.start(QLatin1String("xcopy.exe"), parameters);
                    if (!xcopy.waitForStarted() || !xcopy.waitForFinished()) {
                        qDebug() << "Could not copy" <<
                                 QDir::toNativeSeparators(sourcePath);
                        continue;
                    }
#else // Q_OS_WIN
                    // Implement me!
#endif // Q_OS_WIN
                    app.setMainQmlFile(qmlTargetPath.absoluteFilePath()
                                       + QLatin1Char('/') + qmlFileOrigin.fileName());
                }
                app.setProjectName(reader.attributes().hasAttribute(attrib_projectName)
                                   ? reader.attributes().value(attrib_projectName).toString()
                                   : QFileInfo(app.mainQmlFile()).baseName());
                if (reader.attributes().hasAttribute(attrib_screenOrientation)) {
                    const QStringRef orientation = reader.attributes().value(attrib_screenOrientation);
                    app.setOrientation(orientation == value_screenOrientationLockLandscape ?
                                       AbstractMobileApp::ScreenOrientationLockLandscape
                                       : orientation == value_screenOrientationLockPortrait ?
                                       AbstractMobileApp::ScreenOrientationLockPortrait
                                       : AbstractMobileApp::ScreenOrientationAuto);
                }
                if (reader.attributes().hasAttribute(attrib_networkAccess))
                    app.setNetworkEnabled(
                        reader.attributes().value(attrib_networkAccess).toString() == QLatin1String("true"));
                if (!app.generateFiles(0))
                    qDebug() << "Unable to generate the files for" << app.projectName();
            }
            break;
        default:
            break;
        }
    }
    return true;
}
示例#17
0
// solaris, not 2.6
void qt_parseEtcLpPrinters(QList<QPrinterDescription> *printers)
{
    QDir lp(QLatin1String("/etc/lp/printers"));
    QFileInfoList dirs = lp.entryInfoList();
    if (dirs.isEmpty())
        return;

    QString tmp;
    for (int i = 0; i < dirs.size(); ++i) {
        QFileInfo printer = dirs.at(i);
        if (printer.isDir()) {
            tmp.sprintf("/etc/lp/printers/%s/configuration",
                         printer.fileName().toAscii().data());
            QFile configuration(tmp);
            char *line = new char[1025];
            QString remote(QLatin1String("Remote:"));
            QString contentType(QLatin1String("Content types:"));
            QString printerHost;
            bool canPrintPostscript = false;
            if (configuration.open(QIODevice::ReadOnly)) {
                while (!configuration.atEnd() &&
                        configuration.readLine(line, 1024) > 0) {
                    if (QString::fromLatin1(line).startsWith(remote)) {
                        const char *p = line;
                        while (*p != ':')
                            p++;
                        p++;
                        while (isspace((uchar) *p))
                            p++;
                        printerHost = QString::fromLocal8Bit(p);
                        printerHost = printerHost.simplified();
                    } else if (QString::fromLatin1(line).startsWith(contentType)) {
                        char *p = line;
                        while (*p != ':')
                            p++;
                        p++;
                        char *e;
                        while (*p) {
                            while (isspace((uchar) *p))
                                p++;
                            if (*p) {
                                char s;
                                e = p;
                                while (isalnum((uchar) *e))
                                    e++;
                                s = *e;
                                *e = '\0';
                                if (!qstrcmp(p, "postscript") ||
                                     !qstrcmp(p, "any"))
                                    canPrintPostscript = true;
                                *e = s;
                                if (s == ',')
                                    e++;
                                p = e;
                            }
                        }
                    }
                }
                if (canPrintPostscript)
                    qt_perhapsAddPrinter(printers, printer.fileName(),
                                         printerHost, QLatin1String(""));
            }
            delete[] line;
        }
    }
}
QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const
{
  QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME);
  return settingsInfo.canonicalFilePath();
}
示例#19
0
int qt_getLprPrinters(QList<QPrinterDescription>& printers)
{
    QByteArray etcLpDefault;
    qt_parsePrintcap(&printers, QLatin1String("/etc/printcap"));
    qt_parseEtcLpMember(&printers);
    qt_parseSpoolInterface(&printers);
    qt_parseQconfig(&printers);

    QFileInfo f;
    f.setFile(QLatin1String("/etc/lp/printers"));
    if (f.isDir()) {
        qt_parseEtcLpPrinters(&printers);
        QFile def(QLatin1String("/etc/lp/default"));
        if (def.open(QIODevice::ReadOnly)) {
            etcLpDefault.resize(1025);
            if (def.readLine(etcLpDefault.data(), 1024) > 0) {
                QRegExp rx(QLatin1String("^(\\S+)"));
                if (rx.indexIn(QString::fromLatin1(etcLpDefault)) != -1)
                    etcLpDefault = rx.cap(1).toAscii();
            }
        }
    }

    char *def = 0;
    f.setFile(QLatin1String("/etc/nsswitch.conf"));
    if (f.isFile()) {
        def = qt_parseNsswitchConf(&printers);
    } else {
        f.setFile(QLatin1String("/etc/printers.conf"));
        if (f.isFile())
            def = qt_parsePrintersConf(&printers);
    }

    if (def) {
        etcLpDefault = def;
        delete [] def;
    }

    QString homePrintersDefault = qt_getDefaultFromHomePrinters();

    // all printers hopefully known.  try to find a good default
    QString dollarPrinter;
    {
        dollarPrinter = QString::fromLocal8Bit(qgetenv("PRINTER"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("LPDEST"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("NPRINTER"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("NGPRINTER"));
#ifndef QT_NO_PRINTDIALOG
        if (!dollarPrinter.isEmpty())
            qt_perhapsAddPrinter(&printers, dollarPrinter,
                                 QPrintDialog::tr("unknown"),
                                 QLatin1String(""));
#endif
    }

    QRegExp ps(QLatin1String("[^a-z]ps(?:[^a-z]|$)"));
    QRegExp lp(QLatin1String("[^a-z]lp(?:[^a-z]|$)"));

    int quality = 0;
    int best = 0;
    for (int i = 0; i < printers.size(); ++i) {
        QString name = printers.at(i).name;
        QString comment = printers.at(i).comment;
        if (quality < 5 && name == dollarPrinter) {
            best = i;
            quality = 5;
        } else if (quality < 4 && !homePrintersDefault.isEmpty() &&
                   name == homePrintersDefault) {
            best = i;
            quality = 4;
        } else if (quality < 3 && !etcLpDefault.isEmpty() &&
                    name == QLatin1String(etcLpDefault)) {
            best = i;
            quality = 3;
        } else if (quality < 2 &&
                    (name == QLatin1String("ps") ||
                     ps.indexIn(comment) != -1)) {
            best = i;
            quality = 2;
        } else if (quality < 1 &&
                    (name == QLatin1String("lp") ||
                     lp.indexIn(comment) > -1)) {
            best = i;
            quality = 1;
        }
    }

    return best;
}
示例#20
0
void HttpWindow::httpFinished()
{
    songBeingDownloaded = false;
    if (!songsThatNeedToBeDownloaded.isEmpty())
    {
    QUrl tempURL = songsThatNeedToBeDownloaded.dequeue();
    startRequest(tempURL);
    }
    QFileInfo fi;

    if (file) {
        fi.setFile(file->fileName());
        file->close();
        delete file;
        file = Q_NULLPTR;
    }

    if (httpRequestAborted) {
        reply->deleteLater();
        reply = Q_NULLPTR;
        return;
    }

    if (reply->error()) {
        QFile::remove(fi.absoluteFilePath());
        statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString()));
        downloadButton->setEnabled(true);
        reply->deleteLater();
        reply = Q_NULLPTR;
        return;
    }

    const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    reply->deleteLater();
    reply = Q_NULLPTR;

    if (!redirectionTarget.isNull()) {
        const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl());
        file = openFileForWrite(fi.absoluteFilePath());
        if (!file) {
            downloadButton->setEnabled(true);
            return;
        }
        startRequest(redirectedUrl);
        return;
    }

    if (fi.size() < 21000){
        statusLabel->setText("Error downloading song, try again or try a new link.");
}
    else{
    statusLabel->setText(tr("Downloaded %1 bytes to %2\nin\n%3")
                         .arg(fi.size()).arg(fi.fileName(), QDir::toNativeSeparators(fi.absolutePath())));
}
    songNameList.append(fi.fileName());

    if (launchCheckBox->isChecked()){
    //Just added these below so you aren't forced to have the launchBox checked
     //playlist->addMedia(QUrl::fromLocalFile(fi.absoluteFilePath()));//**********
     //player->setVolume(50);
     //player->setPlaylist(playlist);

     //All these if/elses were some of my attempts to hold the player state when songs are being downloaded
     /**
     if(songIndex == 0)
     {
        firstSongAdded = QUrl::fromLocalFile(fi.absoluteFilePath());
     }

     if (QMediaPlayer::NoMedia == 1)//playing (0 = stopped, 1 = playing, 2 = paused)
     {
         if(!songsThatNeedToBeAdded.isEmpty()){
             while(!songsThatNeedToBeAdded.isEmpty())
             {
                 playlist->addMedia((songsThatNeedToBeAdded.dequeue()));
             }
            player->setPlaylist(playlist);
         }
         else{
             player->setPlaylist(playlist);
         }
     }
     else
     {
         songsThatNeedToBeAdded.enqueue(QUrl::fromLocalFile(fi.absoluteFilePath()));
     }
     */
}
    //newlyAddedSong = QUrl::fromLocalFile(fi.absoluteFilePath());
    //player->setMedia(currentSong);
    tempPlaylist.append(QUrl::fromLocalFile(fi.absoluteFilePath()));
    playlist->addMedia(QUrl::fromLocalFile(fi.absoluteFilePath()));
    player->setVolume(50);
    player->setPlaylist(playlist);
    downloadButton->setEnabled(true);
    //songIndex++;
    totalNumberOfSongs++;
}
示例#21
0
FileInfo toFileInfo(const QFileInfo &info)
{
    FileInfo fi;

    fi.m_valid = true;
    fi.m_exists = info.exists();
    fi.m_permissions = info.permissions();
    fi.m_isSymlink = info.isSymLink();
    fi.m_type = FileInfo::System;
    fi.m_hidden = info.isHidden();
    fi.m_size = -1;
    fi.m_lastModified = info.lastModified();

    if (info.isDir())
        fi.m_type = FileInfo::Dir;
    else if (info.isFile())
        fi.m_type = FileInfo::File;
    else if (!info.exists() && info.isSymLink())
        fi.m_type = FileInfo::System;

    if (fi.type() == FileInfo::Dir)
        fi.m_size = 0;
    else if (fi.type() == FileInfo::File)
        fi.m_size = info.size();
    if (!info.exists() && !info.isSymLink())
        fi.m_size = -1;

    return fi;
}
示例#22
0
void Q3LocalFs::operationListChildren( Q3NetworkOperation *op )
{
#ifdef QLOCALFS_DEBUG
    qDebug( "Q3LocalFs: operationListChildren" );
#endif
    op->setState( StInProgress );

    dir = QDir( url()->path() );
    dir.setNameFilter( url()->nameFilter() );
    dir.setMatchAllDirs( true );
    if ( !dir.isReadable() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    QFileInfoList filist = dir.entryInfoList(QDir::All | QDir::Hidden | QDir::System);
    if ( filist.isEmpty() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    emit start( op );

    Q3ValueList<QUrlInfo> infos;
    for (int i = 0; i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);
	infos << QUrlInfo( fi.fileName(), convertPermissions(&fi), fi.owner(), fi.group(),
			   fi.size(), fi.lastModified(), fi.lastRead(), fi.isDir(), fi.isFile(),
			   fi.isSymLink(), fi.isWritable(), fi.isReadable(), fi.isExecutable() );
    }
    emit newChildren( infos, op );
    op->setState( StDone );
    emit finished( op );
}
示例#23
0
void QrcEditor::resolveLocationIssues(QStringList &files)
{
    const QDir dir = QFileInfo(m_treeview->fileName()).absoluteDir();
    const QString dotdotSlash = QLatin1String("../");
    int i = 0;
    int count = files.count();

    // Find first troublesome file
    for (; i < count; i++) {
        QString const &file = files.at(i);
        const QString relativePath = dir.relativeFilePath(file);
        if (relativePath.startsWith(dotdotSlash))
            break;
    }

    // All paths fine -> no interaction needed
    if (i == count) {
        return;
    }

    // Interact with user from now on
    bool abort = false;
    for (; i < count; i++) {
        // Path fine -> skip file
        QString const &file = files.at(i);
        QString const relativePath = dir.relativeFilePath(file);
        if (!relativePath.startsWith(dotdotSlash)) {
            continue;
        }

        // Path troublesome and aborted -> remove file
        if (abort) {
            files.removeAt(i);
            count--;
            i--;
            continue;
        } else {
            // Path troublesome -> query user
            QMessageBox message(this);
            message.setWindowTitle(tr("Invalid file"));
            message.setIcon(QMessageBox::Warning);
            QPushButton * const continueButton = message.addButton(tr("Add anyway"), QMessageBox::AcceptRole);
            QPushButton * const copyButton = message.addButton(tr("Copy"), QMessageBox::ActionRole);
            QPushButton * const skipButton = message.addButton(tr("Don't add"), QMessageBox::DestructiveRole);
            QPushButton * const abortButton = message.addButton(tr("Abort"), QMessageBox::RejectRole);
            message.setDefaultButton(copyButton);
            message.setEscapeButton(skipButton);
            message.setText(tr("The file %1 is not in a subdirectory of the resource file. Continuing will result in an invalid resource file.")
                            .arg(QDir::toNativeSeparators(file)));
            message.exec();
            if (message.clickedButton() == continueButton) {
                continue;
            } else if (message.clickedButton() == skipButton) {
                files.removeAt(i);
                count--;
                i--; // Compensate i++
            } else if (message.clickedButton() == copyButton) {
                const QFileInfo fi(file);
                const QFileInfo suggestion(dir, fi.fileName());
                const QString copyName = QFileDialog::getSaveFileName(this, tr("Choose copy location"),
                                                                suggestion.absoluteFilePath());
                if (!copyName.isEmpty()) {
                    if (QFile::exists(copyName)) {
                        if (!QFile::remove(copyName)) {
                            QMessageBox::critical(this, tr("Overwrite failed"),
                                                  tr("Could not overwrite file %1.")
                                                  .arg(QDir::toNativeSeparators(copyName)));
                            // Remove file
                            files.removeAt(i);
                            count--;
                            i--; // Compensate i++
                            continue;
                        }
                    }
                    if (!QFile::copy(file, copyName)) {
                        QMessageBox::critical(this, tr("Copying failed"),
                                              tr("Could not copy the file to %1.")
                                              .arg(QDir::toNativeSeparators(copyName)));
                        // Remove file
                        files.removeAt(i);
                        count--;
                        i--; // Compensate i++
                        continue;
                    }
                    files[i] = copyName;
                } else {
                    // Remove file
                    files.removeAt(i);
                    count--;
                    i--; // Compensate i++
                }
            } else if (message.clickedButton() == abortButton) {
                abort = true;

                files.removeAt(i);
                count--;
                i--; // Compensate i++
            }
        }
    }
}
示例#24
0
QString MirallConfigFile::excludeFile() const
{
    // prefer sync-exclude.lst, but if it does not exist, check for
    // exclude.lst for compatibility reasonsin the user writeable
    // directories.
    const QString exclFile("sync-exclude.lst");

    QFileInfo fi;
    fi.setFile( configPath(), exclFile );

    if( ! fi.isReadable() ) {
        fi.setFile( configPath(), QLatin1String("exclude.lst") );
    }

    // Check alternative places...
    if( ! fi.isReadable() ) {
#ifdef Q_OS_WIN32
        fi.setFile( QApplication::applicationDirPath(), exclFile );
#endif
#ifdef Q_OS_LINUX
        fi.setFile( QString("/etc/%1").arg(Theme::instance()->appName()), exclFile );
#endif
#ifdef Q_OS_MAC
        // exec path is inside the bundle
        fi.setFile( QApplication::applicationDirPath(),
                    QLatin1String("../Resources/") + exclFile );
#endif
    }

    if( fi.isReadable() ) {
        qDebug() << "  ==> returning exclude file path: " << fi.absoluteFilePath();
        return fi.absoluteFilePath();
    }
    qDebug() << "EMPTY exclude file path!";
    return QString::null;
}
示例#25
0
// Locate a binary in a directory, applying all kinds of
// extensions the operating system supports.
static QString checkBinary(const QDir &dir, const QString &binary)
{
    // naive UNIX approach
    const QFileInfo info(dir.filePath(binary));

    if (info.isFile() && info.isExecutable()) {
        return info.absoluteFilePath();
    }

    // Does the OS have some weird extension concept or does the
    // binary have a 3 letter extension?
    if (pathOS == OS_Unix) {
        return QString();
    }
    const int dotIndex = binary.lastIndexOf(QLatin1Char('.'));
    if (dotIndex != -1 && dotIndex == binary.size() - 4) {
        return QString();
    }

    switch (pathOS) {
    case OS_Unix:
        break;
    case OS_Windows:
    {
        static const char *windowsExtensions[] = { ".cmd", ".bat", ".exe", ".com" };
        // Check the Windows extensions using the order
        const int windowsExtensionCount = sizeof(windowsExtensions) / sizeof(const char *);
        for (int e = 0; e < windowsExtensionCount; e++) {
            const QFileInfo windowsBinary(dir.filePath(binary + QLatin1String(windowsExtensions[e])));
            if (windowsBinary.isFile() && windowsBinary.isExecutable()) {
                return windowsBinary.absoluteFilePath();
            }
        }
    }
    break;
    case OS_Mac:
    {
        // Check for Mac app folders
        const QFileInfo appFolder(dir.filePath(binary + QLatin1String(".app")));
        if (appFolder.isDir()) {
            QString macBinaryPath = appFolder.absoluteFilePath();
            macBinaryPath += QLatin1String("/Contents/MacOS/");
            macBinaryPath += binary;
            const QFileInfo macBinary(macBinaryPath);
            if (macBinary.isFile() && macBinary.isExecutable()) {
                return macBinary.absoluteFilePath();
            }
        }
    }
    break;
    }
    return QString();
}
void CSFolderObserver::onLoad( const QFileInfo& path )
{
    QByteArray ba = path.absoluteFilePath().toLocal8Bit();
    //printf( "%s\n",ba.data());
    /* TODO 実際にリソースをロードする */
}
示例#27
0
PDB_Country::PDB_Country(QWidget *parent) : QWidget(parent) {
  QLabel *l = new QLabel(i18n("Select the location where you plan to use this\n"
			    "account from the list below. If your country or\n"
			    "location is not listed, you have to create the\n"
			    "account with the normal, dialog based setup.\n\n"
			    "If you click \"Cancel\", the dialog based setup\n"
			    "will start."),
		       this);
  QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
  tl->addWidget(l);

  QHBoxLayout *l1 = new QHBoxLayout;
  tl->addLayout(l1);
  l1->addStretch(1);

  lb = new QListBox(this);
  connect(lb, SIGNAL(highlighted(int)),
	  this, SLOT(selectionChanged(int)));
  lb->setMinimumSize(220, 100);
  l1->addWidget(lb, 2);
  l1->addStretch(1);

  list = new QStringList;

  // fill the listbox
  // set up filter
  QDir d(KGlobal::dirs()->findDirs("appdata", "Provider").first());
  d.setFilter(QDir::Dirs);
  d.setSorting(QDir::Name);

  // read the list of files
  const QFileInfoList *flist = d.entryInfoList();
  if(flist) {
    QFileInfoListIterator it( *flist );
    QFileInfo *fi;
    // traverse the flist and insert into a map for sorting
    QMap<QString, QString> countries;
    for(; (fi = it.current()) != 0; ++it) {
      if(fi->fileName() != "." && fi->fileName() != "..") {
        QString dirFile(fi->absFilePath()+"/.directory");
        QString entryName;
        if(QFile::exists(dirFile)){
          KSimpleConfig config(dirFile);
          config.setDesktopGroup();
          entryName = config.readEntry("Name");
        }
        if (entryName.isNull()) entryName = fi->fileName();
	countries.insert(entryName, fi->fileName());
      }
    }
    // insert sorted entries into list box and string list
    QMap<QString, QString>::const_iterator mit = countries.begin();
    QMap<QString, QString>::const_iterator mend = countries.end();
    while(mit != mend) {
        lb->insertItem(mit.key());
        list->append(*mit);
	++mit;
    }
  }

  tl->activate();
}
void GSFolderObserver::onLoad( const QFileInfo& path )
{
    QByteArray ba = path.absoluteFilePath().toLocal8Bit();
    //printf( "%s\n",ba.data());
    /* TODO 実際にリソースをロードする */
    /**/
    QFile scriptFile( path.absoluteFilePath() );
    if( !scriptFile.exists() )
    {
        /* TODO ログ */
        return ;
    }
    /* ロードするインデックスを判定 */
    ShaderScripts& shaderScripts = cxt_->shaderScripts;
    ShaderScriptGroup& gsScripts = shaderScripts.gsScripts;
    int gi;
    for( gi=0;gi<gsScripts.numScript;++gi)
    {
        const ShaderScriptGroup& scriptGroup = gsScripts;
        const ShaderScript& script = scriptGroup.scripts[gi];
        QByteArray baBaseName = path.baseName().toLocal8Bit();
        if( !strcmp( baBaseName.data(), script.name ) ) 
        {
            NL_SAFE_RELEASE( cxt_->gss[gi].shader );
            break;
        }
    }
    /**/
    ShaderScript& script = gsScripts.scripts[gi];
    /* ロードが初の場合 */
    if( gi == gsScripts.numScript )
    {
        /* 総ロード数を増やす */
        ++gsScripts.numScript;
        /* IDの再登録 */
        setId( groupName_, path.baseName() );
    }
    /* リロードになる場合 */
    else
    {
        /* スクリプト文字列の解放 */
        if( script.name )
        {
            free( script.name ); 
            script.name = NULL;
        }
        if( script.script )
        {
            free( script.script ); 
            script.script = NULL;
        }
    }
    /**/
    scriptFile.open(QIODevice::ReadOnly|QIODevice::Text);
    QByteArray scriptData = scriptFile.readAll();
    script.script = (nlInt8*)calloc((scriptData.size()+1)*sizeof(nlInt8),1);
    strcpy( script.script, scriptData.data() );
    QByteArray baBaseName = path.baseName().toLocal8Bit();
    script.name = (nlInt8*)calloc((baBaseName.size()+1)*sizeof(nlInt8),1);
    strcpy( script.name, baBaseName.data() );
    /* ターゲットをロードする */
    nlCreateShaders( ShaderType_GS, gi, shaderScripts, *cxt_ );
}
// Returns the whole proj4 string for the selected srsid
//this is a static method! NOTE I've made it private for now to reduce API clutter TS
QString QgsCoordinateReferenceSystem::proj4FromSrsId( const int theSrsId )
{

  QString myDatabaseFileName;
  QString myProjString;
  QString mySql = "select parameters from tbl_srs where srs_id = ";
  mySql += QString::number( theSrsId );

  QgsDebugMsg( "mySrsId = " + QString::number( theSrsId ) );
  QgsDebugMsg( "USER_CRS_START_ID = " + QString::number( USER_CRS_START_ID ) );
  QgsDebugMsg( "Selection sql : " + mySql );

  //
  // Determine if this is a user projection or a system on
  // user projection defs all have srs_id >= 100000
  //
  if ( theSrsId >= USER_CRS_START_ID )
  {
    myDatabaseFileName = QgsApplication::qgisUserDbFilePath();
    QFileInfo myFileInfo;
    myFileInfo.setFile( myDatabaseFileName );
    if ( !myFileInfo.exists( ) ) //its unlikely that this condition will ever be reached
    {
      QgsDebugMsg( "users qgis.db not found" );
      return NULL;
    }
  }
  else //must be  a system projection then
  {
    myDatabaseFileName = QgsApplication::srsDbFilePath();
  }
  QgsDebugMsg( "db = " + myDatabaseFileName );

  sqlite3 *db;
  int rc;
  rc = openDb( myDatabaseFileName, &db );
  if ( rc )
  {
    return QString();
  }
  // prepare the sql statement
  const char *pzTail;
  sqlite3_stmt *ppStmt;

  rc = sqlite3_prepare( db, mySql.toUtf8(), mySql.toUtf8().length(), &ppStmt, &pzTail );
  // XXX Need to free memory from the error msg if one is set

  if ( rc == SQLITE_OK )
  {
    if ( sqlite3_step( ppStmt ) == SQLITE_ROW )
    {
      myProjString = QString::fromUtf8(( char* )sqlite3_column_text( ppStmt, 0 ) );
    }
  }
  // close the statement
  sqlite3_finalize( ppStmt );
  // close the database
  sqlite3_close( db );

  //Q_ASSERT(myProjString.length() > 0);
  return myProjString;
}
示例#30
0
void CreateTorrent::run() {

    using namespace libtorrent;

    QStringList inputList;
    if(!this->isBatch)
        inputList.append(this->source);
    else {
        QDirIterator iit(this->source);
        while(iit.hasNext()) {
            QString fn = iit.next();
			if(file_filter(fn.toUtf8().constData()))
				inputList.append(fn);
        }
    }

    QStringListIterator inputListIterator(inputList);
    while(inputListIterator.hasNext()) {
        QString input = inputListIterator.next();
        QFileInfo inputInfo(input);
        if(inputInfo.isDir()) {
            QDirIterator iit(input, QDirIterator::Subdirectories);
            while(iit.hasNext()) {
                QString fn = iit.next();
                if(file_filter(fn.toUtf8().constData()))
                    emit(logStatusMessage(QString("[READ] %1").arg(fn)));
            }
        }
		else
			emit(logStatusMessage(QString("[READ] %1").arg(input)));

        QString outputFilename;
        if(!this->isBatch)
            outputFilename = this->outputLocation;
        else
            outputFilename = QDir(this->outputLocation).absoluteFilePath(QDir(input).dirName() + ".torrent");
        QFileInfo outputDir = QFileInfo(outputFilename).dir().absolutePath();
        if (!outputDir.isWritable()) {
            emit(logStatusMessage(QString("[ERROR] %1 is not writeable - aborting").arg(outputFilename)));
            return;
        }

        file_storage fs;
        add_files(fs, input.toUtf8().constData(), file_filter);
        create_torrent torrent(fs, this->pieceSize, -1, this->flags);
        this->pieceCount = torrent.num_pieces();

        foreach(const QString &webSeed, this->webSeeds) {
            if (!webSeeds.isEmpty())
                torrent.add_url_seed(webSeed.trimmed().toStdString());
        }

        int tier = 0;
        foreach(const QString &tracker, this->announceUrls) {
            if (!tracker.isEmpty()) {
                torrent.add_tracker(tracker.trimmed().toStdString(), tier);
                tier++;
            }
        }

        torrent.set_priv(this->isPrivate);
        torrent.set_comment(this->comment.toUtf8().constData());
        torrent.set_creator(this->creator.toUtf8().constData());
        QFileInfo pSource(input);
        set_piece_hashes(torrent, pSource.dir().path().toUtf8().constData(), boost::bind<void>(&doProgressUpdate, _1, torrent.num_pieces(), this));
        std::ofstream outputFile(outputFilename.toUtf8().constData(), std::ios_base::binary | std::ios_base::out);
        bencode(std::ostream_iterator<char>(outputFile), torrent.generate());
        outputFile.close();
        emit(updateProgress(100));
        emit(logStatusMessage(QString("[WRITE] %1").arg(outputFilename)));
    }

}