Esempio n. 1
0
QString copyFileToPrivateMediaLocation(const ProjectInfo& prjInfo, const QString& path)
{
    const QFileInfo originalFileInfo(path);
    const QString extension = originalFileInfo.completeSuffix();
    const QString mediaLocation = prjInfo.getInternalLocation(ProjectInfo::PrivateMultimedia);
    const QString newFilePathPattern = QString("%1/XXXXXX.%2").arg(mediaLocation).arg(extension);

    QDir().mkpath(mediaLocation);

    QFile originalFile(path);
    originalFile.open(QFile::ReadOnly);

    QTemporaryFile newFile(newFilePathPattern);
    newFile.setAutoRemove(false);
    newFile.open();

    bool work = true;
    do
    {
        const int bufferSize = 1024*1024;
        char data[bufferSize];
        const quint64 read = originalFile.read(data, bufferSize);

        if (read > 0)
            newFile.write(data, read);

        work = read == bufferSize;
    }
    while(work);

    const QString newFilePath = newFile.fileName();

    return newFilePath;
}
Esempio n. 2
0
void TarArch::createTmp()
{
    if ( compressed )
    {
        if ( !QFile::exists(tmpfile) )
        {
            QString strUncompressor = getUnCompressor();
            // at least lzop doesn't want to pipe zerosize/nonexistent files
            QFile originalFile( m_filename );
            if ( strUncompressor != "gunzip" && strUncompressor !="bunzip2" &&
                ( !originalFile.exists() || originalFile.size() == 0 ) )
            {
                QFile temp( tmpfile );
                temp.open( IO_ReadWrite );
                temp.close();
                emit createTempDone();
                return;
            }
            // the tmpfile does not yet exist, so we create it.
            createTmpInProgress = true;
            int f_desc = KDE_open(QFile::encodeName(tmpfile), O_CREAT | O_TRUNC | O_WRONLY, 0666);
            if (f_desc != -1)
                fd = fdopen( f_desc, "w" );
            else
                fd = NULL;

            KProcess *kp = m_currentProcess = new KProcess;
            kp->clearArguments();
            kdDebug(1601) << "Uncompressor is " << strUncompressor << endl;
            *kp << strUncompressor;
            KProcess::Communication flag = KProcess::AllOutput;
            if (strUncompressor == "lzop")
            {
                // setting up a pty for lzop, since it doesn't like stdin to
                // be /dev/null ( "no filename allowed when reading from stdin" )
                // - but it used to work without this ? ( Feb 13, 2003 )
                kp->setUsePty( KProcess::Stdin, false );
                flag = KProcess::Stdout;
                *kp << "-d";
            }
            *kp << "-c" << m_filename;

            connect(kp, SIGNAL(processExited(KProcess *)),
                    this, SLOT(createTmpFinished(KProcess *)));
            connect(kp, SIGNAL(receivedStdout(KProcess*, char*, int)),
                    this, SLOT(createTmpProgress( KProcess *, char *, int )));
            connect( kp, SIGNAL(receivedStderr(KProcess*, char*, int)),
                    this, SLOT(slotReceivedOutput(KProcess*, char*, int)));
            if (kp->start(KProcess::NotifyOnExit, flag ) == false)
            {
                KMessageBox::error(0, i18n("Unable to fork a decompressor"));
		emit sigOpen( this, false, QString::null, 0 );
            }
        }
        else
        {
Esempio n. 3
0
bool KNMusicGlobal::renameMusicFile(const QString &originalPath,
                                    const QString &preferName)
{
    QFileInfo originalFile(originalPath);
    //If the original file is not
    if(!originalFile.exists())
    {
        //Tell the user that original file cannot find.
        KNMessageBox::information("Error",
                                  tr("Cannot find file:\n") +
                                  originalFile.absoluteFilePath());
        return false;
    }
    //Check the prefer name's availability.
    QFileInfo destinationFile(originalFile.absolutePath()+"/"+preferName);
    if(destinationFile.exists())
    {
        if(!KNMessageBox::question("Overwrite",
                                   tr("File %1 has been exist in folder:\n%2\nOverwrite?").arg(
                                       destinationFile.fileName(), destinationFile.absolutePath())))
        {
            return false;
        }
    }

    bool restoreNowPlaying=false;
    //Check is the file playing.
    if(m_nowPlaying->currentAnalaysisItem().detailInfo.filePath
            ==originalFile.absoluteFilePath())
    {
        //Backup the current playing.
        m_nowPlaying->backupCurrentPlaying();
        //Set the flag.
        restoreNowPlaying=true;
    }

    //Rename the music file.
    bool renameResult=KNGlobal::renameFile(originalFile.absoluteFilePath(),
                                           destinationFile.absoluteFilePath());
    if(renameResult)
    {
        //Emit the file name changed signal.
        emit musicFilePathChanged(originalFile.absoluteFilePath(),
                                  destinationFile.absoluteFilePath(),
                                  destinationFile.fileName());
    }

    //Restore the now playing according to the flag.
    if(restoreNowPlaying)
    {
        m_nowPlaying->restoreCurrentPlaying();
    }
    return renameResult;
}
    void FileFixerDialog::retry()
    {
        // Clear details
        this->_ui->details->clear();

        // Reflect contents in file
        delete this->_tempFile;
        this->_tempFile = new QTemporaryFile();
        this->_tempFile->open();
        this->_tempFile->write(this->_ui->text->toPlainText().toUtf8());
        this->_tempFile->flush();

        // Try to parse again
        this->_ctx = load(this->_tempFile->fileName(), this->_fileFormat);
        this->_ui->errors->reset();
        this->_ui->errors->scrollToTop();

        // If successful, then bail.
        if (this->_ctx.model() != 0 && this->_ctx.errorCode() == Parser::None)
        {
            QString title = this->_exportPolicy & UseSameFileName ? "Overwrite data file?" : "Save changes?";
            // Save changes?
            if ((this->_exportPolicy & ForceExport) ||
                QMessageBox::question(this, title, "Would you like to save the changes you just made to disk?",
                                      QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
            {
                QFileInfo originalFile(this->_fileName);
                if (this->_exportPolicy & UseSameFileName)
                {
                    this->_exportFileName = this->_fileName;
                }
                else
                {
                    this->_exportFileName = getExportFileName(this->_fileFormat, this, "Save Changes To...", originalFile.absoluteFilePath());
                }
                if (!this->_exportFileName.isEmpty())
                {
                    QFile file(this->_exportFileName);
                    file.open(QIODevice::WriteOnly);
                    file.write(this->_ui->text->toPlainText().toUtf8());
                }
            }

            this->accept();
        }
        else
        {
            this->_ui->errors->setCurrentIndex(this->_ui->errors->model()->index(0, 0));
            this->goTo(this->_ui->errors->model()->index(0, 0));
        }
    }
Esempio n. 5
0
FetchSqlite::FetchSqlite(const QString &originalFilePath, const QString &copyTo, QObject *parent) :
    QObject(parent), m_databaseFile(copyTo)
{
    m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), originalFilePath);
    m_db.setHostName(QStringLiteral("localhost"));

    QFile originalFile(originalFilePath);
    QFile(copyTo).remove();
    bool couldCopy = originalFile.copy(copyTo);
    if(!couldCopy) {
        //qDebug() << "error copying favicon database from " << originalFile.fileName() << " to " << copyTo;
        //qDebug() << originalFile.errorString();
    }
}
Esempio n. 6
0
bool LayerSound::saveImage(int index, QString path, int layerNumber)
{
    /*QString layerNumberString = QString::number(layerNumber);
    QString frameNumberString = QString::number(framesPosition.at(index));
    while ( layerNumberString.length() < 3) layerNumberString.prepend("0");
    while ( frameNumberString.length() < 3) frameNumberString.prepend("0");*/
    //framesFilename[index] = path+"/"+layerNumberString+"."+frameNumberString+".png";
    //framesFilename[index] = layerNumberString+"."+frameNumberString+".png";
    //framesFilename[index] = layerNumberString+"."+frameNumberString+".png";
    //qDebug() << "Write " << framesFilename.at(index);
    //framesImage[index]->save(framesFilename.at(index),"PNG");
    QFile originalFile( soundFilepath.at(index) );
    originalFile.copy( path + "/" + framesFilename.at(index) );
    framesModified[index] = false;

    return true;
}
Esempio n. 7
0
int Plugin::replaceWithLink(std::string filepath)
{
    std::cout << "Replacing with link " << filepath.c_str() << std::endl;

    std::ifstream fstr(filepath.c_str());
    MD5Engine md5;
    DigestOutputStream ostr(md5);
    Poco::StreamCopier::copyStream(fstr, ostr);
    ostr.flush();
    const DigestEngine::Digest& digest = md5.digest();
    std::string sourceMd5 = DigestEngine::digestToHex(digest);
    std::cout << "File contents MD5 sum: " << sourceMd5.c_str() << std::endl;

    // Generate new file name
    UUIDGenerator gen;
    UUID tmpUuid = gen.createRandom();
    std::string uuid = tmpUuid.toString(); 
    std::string newFile(Plugin::GIT_CACHE_DIR);
    newFile.append("/");
    newFile.append(uuid);

    Process::Args args;
    args.push_back(filepath);
    args.push_back(newFile);
    Poco::ProcessHandle ph = Process::launch("mv", args, 0, 0, 0);

    // Failback with sudo
    if (ph.wait() != 0)
    {
        args.clear();
        args.push_back("mv");
        args.push_back(filepath);
        args.push_back(newFile);
        ph = Process::launch("sudo", args, 0, 0, 0);
    }

    // Check if file was moved
    File originalFile(filepath);
    if (originalFile.exists())
    {
        std::cout << "Failed to move original file" << std::endl;
        return -1;
    }

    return 1;
}
Esempio n. 8
0
void PropagateRemoteMove::start()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget;

    QString targetFile(_propagator->getFilePath(_item->_renameTarget));

    if (_item->_file == _item->_renameTarget) {
        // The parent has been renamed already so there is nothing more to do.
        finalize();
        return;
    }
    if (_item->_file == QLatin1String("Shared") ) {
        // Before owncloud 7, there was no permissions system. At the time all the shared files were
        // in a directory called "Shared" and were not supposed to be moved, otherwise bad things happened

        QString versionString = _propagator->account()->serverVersion();
        if (versionString.contains('.') && versionString.split('.')[0].toInt() < 7) {
            QString originalFile(_propagator->getFilePath(QLatin1String("Shared")));
            emit _propagator->touchedFile(originalFile);
            emit _propagator->touchedFile(targetFile);
            QString renameError;
            if( FileSystem::rename(targetFile, originalFile, &renameError) ) {
                done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name."));
            } else {
                done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared."));
            }
            return;
        }
    }

    QString destination = QDir::cleanPath(_propagator->account()->url().path() + QLatin1Char('/')
            + _propagator->account()->davPath() + _propagator->_remoteFolder + _item->_renameTarget);
    _job = new MoveJob(_propagator->account(),
                        _propagator->_remoteFolder + _item->_file,
                        destination, this);
    connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished()));
    _propagator->_activeJobList.append(this);
    _job->start();

}
Esempio n. 9
0
void MainWindow::sortFiles()
{

    // Get list of files
    QList<QFileInfo> files;
    QModelIndex parentIndex = dirModel->index(dirModel->rootPath());
    int fileRows = dirModel->rowCount(parentIndex);

    for(int row = 0; row < fileRows; ++row) {
        QModelIndex childIndex = dirModel->index(row, 0, parentIndex);
        QFileInfo info = dirModel->fileInfo(childIndex);
        files.append(info);
    }

    if(files.size() == 0) {
        return;
    }

    emit setFileCount(files.size() - 1);

    // Sort Files
    foreach(QFileInfo info, files) {
        emit setCurrentFile(info);
        QString destination = queryRules(info);
        if(!(destination == NULL)) {

            QFile originalFile(info.absoluteFilePath());
            qDebug() << rootDirPath + "/" + destination + "/" + info.fileName();
            bool copied = originalFile.copy(rootDirPath + "/" + destination + "/" + info.fileName());
            if(!copied) {
                qDebug() << "WARNING: COPIED FAILED - " << info.fileName() << " -> " << destination;
                continue;
                emit incrementProgress();
            }
            qDebug() << "FILE COPIED: " << info.fileName() << " -> " << destination;
            originalFile.remove();
        }
        emit incrementProgress();
    }
Handle<Value> TiDatabase::_install(void* userContext, TiObject* obj, const Arguments& args)
{
	if(args.Length() == 0) return Undefined();
	if(!args[0]->IsString()) return Undefined();
	QString realName = titanium::V8StringToQString(args[0]->ToString());
	QString givenName;
	if(args.Length() > 0 && args[1]->IsString())
	{
		givenName =  titanium::V8StringToQString(args[1]->ToString());
	}
	else
	{
		givenName =  titanium::V8StringToQString(args[0]->ToString());
	}

	QString dataFolder = "data";
	QString newFileName = dataFolder + "/" + givenName;
	QFile newFile(newFileName);

	if (!newFile.exists())
	{
		QString appFolder(QDir::homePath());
		appFolder.chop(4);

		QString originalFileName = appFolder + "app/native/assets/" + realName;
		QFile originalFile(originalFileName);

		if (originalFile.exists()) {
			originalFile.copy(newFileName);
		} else {
			return Undefined();
		}
	}

	return TiDatabase::_open(userContext, obj, args);
}
Esempio n. 11
0
QString TwtImageScaler::scaled(const QString& aFilePath, const qint64 aRequestedSize)
{
    QImage* originalImg = new QImage(aFilePath);
    mSuffix = aFilePath.section('.', -1);
    QString convertfile = aFilePath;
    // maybe load image failed for memory sake
    if (originalImg->isNull())
    {
        qDebug() << "TwtImageScaler::scaled img is null, open by scaled again";
        QImageReader reader(aFilePath);
        reader.setScaledSize(QSize(1024, 1024));
        bool reslt = reader.read(originalImg);
        if(!reslt)
        {
            qDebug() << "TwtImageScaler::scaled open img failed";
            return aFilePath;
        }
    }

    QSize oriImageSize = originalImg->size();
    qint64 filesize = originalImg->byteCount()/8;
    QFile originalFile(aFilePath);
    if (originalFile.open(QIODevice::ReadOnly))
    {
        filesize = originalFile.size();
        originalFile.close();
    }
    delete originalImg;

    qDebug() << "TwtImageScaler::scaled original file Size=" << filesize;
    QImage scaledImg;
    if (filesize > aRequestedSize)
    {
        qreal scaleScope = qSqrt(filesize/aRequestedSize);
        int shrinkWidth = oriImageSize.width() / scaleScope;
        int shrinkHeight = oriImageSize.height() / scaleScope;

        QImageReader scaleReader(aFilePath);
        scaleReader.setScaledSize(QSize(shrinkWidth, shrinkHeight));
        bool reslt = scaleReader.read(&scaledImg);
        if(!reslt)
        {
            qDebug() << "TwtImageScaler::scaled read img failed";
            return aFilePath;
        }
        qDebug()<< "after scale filesize" << scaledImg.size();
    }

    if (filesize > aRequestedSize)
    {
        QString fileName = qApp->applicationDirPath() + KTemporayImage + mSuffix;
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly))
        {
            qDebug() << "open file failed";
        }
        else
        {
            if (scaledImg.save(&file))
            {
                convertfile = fileName;
                qDebug() << "icon.save(&file); " << file.size();
            }
            file.close();
        }
    }
    return convertfile;
}
Esempio n. 12
0
File: main.cpp Progetto: cjpl/rome
int main()
{
   TTimeStamp timestamp;
   timestamp.Set();
   Int_t revisionNumber = 0;

   //
   // Reading XML
   //

   ROMEString xmlFileName = "$(ROMESYS)/.revision.xml";
   gSystem->ExpandPathName(xmlFileName);
   auto_ptr<ROMEXML> xmlIn(new ROMEXML());

   if(xmlIn->OpenFileForPath(xmlFileName.Data())) {
      ROMEString revisionString;
      ROMEString path;

      path = "Entry";
      Int_t nEntry = xmlIn->NumberOfOccurrenceOfPath(path.Data());

      Int_t iEntry;
      vector<ROMEString> user(nEntry + 1);
      vector<ROMEString> host(nEntry + 1);
      vector<ROMEString> directory(nEntry + 1);
      vector<ROMEString> lastcompile(nEntry + 1);
      Bool_t foundIdenticalEntry = kFALSE;

      auto_ptr<UserGroup_t> userInfo(gSystem->GetUserInfo());
      user[nEntry]        = userInfo->fUser;
      host[nEntry]        = gSystem->HostName();
      directory[nEntry]   = "$(ROMESYS)";
      gSystem->ExpandPathName(directory[nEntry]);
      lastcompile[nEntry] = timestamp.AsString();

      path.SetFormatted("Revision");
      xmlIn->GetPathValue(path,revisionString);
      for(iEntry = 0; iEntry < nEntry; iEntry++) {
         path.SetFormatted("Entry[%d]/User", iEntry + 1);
         xmlIn->GetPathValue(path,user[iEntry]);
         path.SetFormatted("Entry[%d]/Host", iEntry + 1);
         xmlIn->GetPathValue(path,host[iEntry]);
         path.SetFormatted("Entry[%d]/Directory", iEntry + 1);
         xmlIn->GetPathValue(path,directory[iEntry]);
         path.SetFormatted("Entry[%d]/LastCompile", iEntry + 1);
         xmlIn->GetPathValue(path,lastcompile[iEntry]);
         if (user[iEntry] == user[nEntry] &&
             host[iEntry] == host[nEntry] &&
             directory[iEntry] == directory[nEntry]) {
            lastcompile[iEntry] = lastcompile[nEntry];
            foundIdenticalEntry = kTRUE;
         }
      }

      //
      // Writing XML
      //

      if (
         // Ryu
         user[nEntry] == "sawada" ||
         user[nEntry] == "ryu" ||
         // Matthias
         user[nEntry] == "schneebeli_m" ||
         user[nEntry] == "egger_j" ||
         // Shuei
         user[nEntry] == "shuei" ||
         user[nEntry] == "yamada" ||
#if 0
         // Meg
         user[nEntry] == "meg" ||
         user[nEntry] == "Administrator" ||
#endif
         0) {

         ROMEXML::SuppressWritingDate();
         auto_ptr<ROMEXML> xmlOut(new ROMEXML());
         xmlOut->OpenFileForWrite(xmlFileName);
         xmlOut->SetTranslate(0);
         xmlOut->WriteElement("Revision", revisionString.Data());
         for(iEntry = 0; iEntry < nEntry; iEntry++) {
            xmlOut->StartElement("Entry");
            xmlOut->WriteElement("User", user[iEntry].Data());
            xmlOut->WriteElement("Host", host[iEntry].Data());
            xmlOut->WriteElement("Directory", directory[iEntry].Data());
            xmlOut->WriteElement("LastCompile", lastcompile[iEntry].Data());
            xmlOut->EndElement();
         }
         if (!foundIdenticalEntry) {
            xmlOut->StartElement("Entry");
            xmlOut->WriteElement("User", user[nEntry].Data());
            xmlOut->WriteElement("Host", host[nEntry].Data());
            xmlOut->WriteElement("Directory", directory[nEntry].Data());
            xmlOut->WriteElement("LastCompile", lastcompile[nEntry].Data());
            xmlOut->EndElement();
         }
         xmlOut->EndDocument();
      }
      ParseSVNKeyword(revisionString);
      revisionNumber = revisionString.ToInteger();
   }
   else {
      cerr<<"Error: Revision number in include/ROMEVersion.h will not be correct."<<endl;
      revisionNumber = 0;
   }

   ROMEString hfile = "$(ROMESYS)/include/";
   gSystem->ExpandPathName(hfile);
   hfile.AppendFormatted("ROMEVersion.h");
   //
   // Reading ROMEVersion.h
   //
   ROMEString fileBuffer;
   ifstream originalFile(hfile.Data());
   if (originalFile.good()) {
      fileBuffer.ReadFile(originalFile);
   }
   originalFile.close();

   //
   // Writing ROMEVersion.h
   //

   ROMEString buffer;
//   cout << "9" << endl;

   // current time
   UInt_t year;
   UInt_t month;
   UInt_t day;
   UInt_t hour;
   UInt_t min;
   UInt_t sec;
   timestamp.Set();
   timestamp.GetDate(kTRUE, 0, &year, &month, &day);
   timestamp.GetTime(kTRUE, 0, &hour, &min, &sec);

   // prepare new file.
   buffer.Resize(0);
   buffer.AppendFormatted("#ifndef ROMEVersion\n");
   buffer.AppendFormatted("#define ROMEVersion\n");
   buffer.AppendFormatted("\n");
   buffer.AppendFormatted("/* Version information automatically generated by installer. */\n");
   buffer.AppendFormatted("\n");
   buffer.AppendFormatted("/*\n");
   buffer.AppendFormatted(" * These macros can be used in the following way:\n");
   buffer.AppendFormatted(" *\n");
   buffer.AppendFormatted(" *    #if ROME_VERSION_CODE >= ROME_VERSION(2,5)\n");
   buffer.AppendFormatted(" *    #   include <newheader.h>\n");
   buffer.AppendFormatted(" *    #else\n");
   buffer.AppendFormatted(" *    #   include <oldheader.h>\n");
   buffer.AppendFormatted(" *    #endif\n");
   buffer.AppendFormatted(" *\n");
   buffer.AppendFormatted("*/\n");
   buffer.AppendFormatted("\n");
   buffer.AppendFormatted("#define ROME_RELEASE \"%d.%d\"\n", romeMajor, romeMinor);
   buffer.AppendFormatted("#define ROME_REVISION_CODE %d\n", revisionNumber);
   buffer.AppendFormatted("#define ROME_STABLE %d\n", isStableVersion);
/*
   buffer.AppendFormatted("#define ROME_RELEASE_DATE \"%s %2d %d\"\n", monthName[month], day, year);
   buffer.AppendFormatted("#define ROME_RELEASE_TIME \"%02d:%02d:%02d\"\n", hour, min, sec);
*/
   buffer.AppendFormatted("#define ROME_VERSION_CODE %d\n", GetROMEVersion(romeMajor, romeMinor));
   buffer.AppendFormatted("#define ROME_VERSION(a,b) (((a) << 8) + (b))\n");
   buffer.AppendFormatted("\n");
   buffer.AppendFormatted("#endif\n");

   // write file
   if (fileBuffer != buffer) {
      ofstream versionH(hfile.Data());
      if (!versionH.good()) {
         cerr<<"failed to open "<<hfile<<" for write."<<endl;
         return 1;
      }
      versionH<<buffer.Data();
      versionH.close();
   }

   return 0;
}