Example #1
0
bool Manager::copyAppData(const QUrl &src, const QString& subdir, const QString& fileName)
{
	//let saveLocation find and create the appropriate place to
	//store the templates (usually $HOME/.kde/share/apps/kile/templates)
	QString dir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '/' + subdir;

	QUrl targetURL = QUrl::fromUserInput(dir);
	targetURL = targetURL.adjusted(QUrl::StripTrailingSlash);
	targetURL.setPath(targetURL.path() + '/' + fileName);

	//if a directory is found
	if (!dir.isNull()) {
		// create dir if not existing, needed for copyjob
		QDir testDir(dir);
		if (!testDir.exists()){
			testDir.mkpath(dir);
		}
		// copy file
		KIO::FileCopyJob* copyJob = KIO::file_copy(src, targetURL);
		KJobWidgets::setWindow(copyJob, m_kileInfo->mainWindow());
		return copyJob->exec();
	}
	else {
		KMessageBox::error(Q_NULLPTR, i18n("Could not find a folder to save %1 to.\nCheck whether you have a .kde folder with write permissions in your home folder.", fileName));
		return false;
	}
}
Example #2
0
 void _k_copyResultToTempFile(KJob* job)
 {
     KIO::FileCopyJob* cJob = qobject_cast<KIO::FileCopyJob *>(job);
     if (cJob && !cJob->error() ) {
         // Same as KRun::foundMimeType but with a different URL
         (void)KRun::runUrl(cJob->destUrl(), mimeType, window);
     }
 }
Example #3
0
void ImportGrammarWorkingPage::initializePage()
{
  completed=false;
  emit completeChanged();

  grammarImporter = new ImportGrammar(this);
  connect(grammarImporter, SIGNAL(status(QString)), this, SLOT(printStatus(QString)));
  connect(grammarImporter, SIGNAL(fileProgress(int,int)), this, SLOT(displayFileProgress(int,int)));
  connect(grammarImporter, SIGNAL(allProgress(int,int)), this, SLOT(displayWholeProgress(int,int)));
  connect(grammarImporter, SIGNAL(grammarCreated()), this, SIGNAL(grammarCreated()));
  connect(grammarImporter, SIGNAL(terminated()), this, SLOT(processCompletion()));

  bool isText = field("inputIsText").toBool();
  if (isText) {
    //bla
    QString tempFileName = KStandardDirs::locateLocal("tmp", "grammarImport/importText");

    QFile f(tempFileName);
    if (!f.open(QIODevice::WriteOnly)) {
      KMessageBox::sorry(this, i18n("Could not open temporary file."));
      return;
    }

    QByteArray textByte = field("grammarInputText").toString().toUtf8();
    f.write(textByte);
    f.close();

    grammarImporter->setFiles(QStringList() << tempFileName);
    grammarImporter->setEncoding("UTF-8");
  }
  else {

    QStringList files = field("files").toStringList();

    int index=0;
    QStringList tempFiles;
    foreach (const QString& file, files) {
      KUrl srcUrl(file);
      QString targetPath = KStandardDirs::locateLocal("tmp", "grammarImport/"+
        QString::number(index)+'_'+srcUrl.fileName());
      KIO::FileCopyJob *job = KIO::file_copy(srcUrl, targetPath, -1, KIO::Overwrite);
      if (!job->exec()) {
        job->ui()->showErrorMessage();
        continue;
      } else
      tempFiles << targetPath;
      index++;
      delete job;
    }
    grammarImporter->setFiles(tempFiles);
    grammarImporter->setEncoding(field("encoding").toString());
  }
void KAResourceRemote::slotLoadJobResult(KJob* job)
{
	bool err = false;
	if (job)
	{
		emit invalidate(this);
		calendar()->close();
		setWrongAlarmType(false, false);
		clearChanges();
		if (job->error())
		{
			if (hasGui())
			{
				KIO::FileCopyJob* j = qobject_cast<KIO::FileCopyJob*>(job);
				if (j)
					j->ui()->showErrorMessage();
			}
			kError(KARES_DEBUG) << "Resource" << identifier() << " download error:" << job->errorString();
			setEnabled(false);
			err = true;
		}
		else
		{
			kDebug(KARES_DEBUG) << mDownloadUrl.prettyUrl() << ": success";
			setReloaded(true);    // the resource has now been downloaded at least once
			emit cacheDownloaded(this);
			disableChangeNotification();
			loadFromCache();
			enableChangeNotification();
		}

#if 0
		emit downloading(this, (unsigned long)-1);
#endif
	}
	mDownloadJob = 0;

	if (!err)
	{
		checkCompatibility(cacheFile());
		mLoaded = true;
	}
	mLoading = false;
	lock()->unlock();
	updateCustomEvents();
	emit loaded(this);
	if (job  &&  !err)
		emit resourceChanged(this);
}
Example #5
0
QUrl setUpRemoteTestDir(const QString& testFile)
{
    QWidget* authWindow = 0;
    if (qgetenv("GV_REMOTE_TESTS_BASE_URL").isEmpty()) {
        qWarning() << "Environment variable GV_REMOTE_TESTS_BASE_URL not set: remote tests disabled";
        return QUrl();
    }

    QUrl baseUrl(QString::fromLocal8Bit(qgetenv("GV_REMOTE_TESTS_BASE_URL")));
    baseUrl = baseUrl.adjusted(QUrl::StripTrailingSlash);
    baseUrl.setPath(baseUrl.path() + "/gwenview-remote-tests");

    KIO::StatJob *statJob = KIO::stat(baseUrl, KIO::StatJob::DestinationSide, 0);
    KJobWidgets::setWindow(statJob, authWindow);

    if (statJob->exec()) {
        KIO::DeleteJob *deleteJob = KIO::del(baseUrl);
        KJobWidgets::setWindow(deleteJob, authWindow);
        deleteJob->exec();
    }

    KIO::MkdirJob *mkdirJob = KIO::mkdir(baseUrl);
    KJobWidgets::setWindow(mkdirJob, authWindow);
    if (!mkdirJob->exec()) {
        qCritical() << "Could not create dir" << baseUrl << ":" << mkdirJob->errorString();
        return QUrl();
    }

    if (!testFile.isEmpty()) {
        QUrl dstUrl = baseUrl;
        dstUrl = dstUrl.adjusted(QUrl::StripTrailingSlash);
        dstUrl.setPath(dstUrl.path() + '/' + testFile);
        KIO::FileCopyJob *copyJob = KIO::file_copy(urlForTestFile(testFile), dstUrl);
        KJobWidgets::setWindow(copyJob, authWindow);
        if (!copyJob->exec()) {
            qCritical() << "Could not copy" << testFile << "to" << dstUrl << ":" << copyJob->errorString();
            return QUrl();
        }
    }

    return baseUrl;
}
Example #6
0
// ### when user cancels download, we crash :(
void MrmlPart::slotDownloadResult( KIO::Job *job )
{
    assert( job->inherits( "KIO::FileCopyJob" ) );
    KIO::FileCopyJob *copyJob = static_cast<KIO::FileCopyJob*>( job );

    if ( !copyJob->error() )
        m_queryList.append( copyJob->destURL() );

    m_downloadJobs.removeRef( copyJob );

    if ( m_downloadJobs.isEmpty() ) // finally, we can start the query!
    {
        if ( m_queryList.isEmpty() ) // rather unlikely, but could happen ;)
        {
            kdWarning() << "Couldn't download the reference files. Will start a random search now" << endl;
        }

        contactServer( m_url );
    }
}
void ChecksumSearchController::registerSearch(ChecksumSearchTransferDataSource *search, const KUrl &baseUrl)
{
    if (m_finished.contains(baseUrl)) {
        kDebug(5001) << "Already downloaded" << baseUrl;
        const KUrl urlToFile = m_finished[baseUrl];
        if (!urlToFile.isEmpty()) {
            search->gotBaseUrl(m_finished[baseUrl]);
        }
    } else {
        const bool alreadySearchedFor = m_searches.contains(baseUrl);
        if (!m_searches.contains(baseUrl, search)) {
            m_searches.insert(baseUrl, search);

            if (alreadySearchedFor) {
                kDebug(5001) << "Search already started for" << baseUrl;
                return;
            }
            kDebug(5001) << "Creating download for" << baseUrl;
            static int files = 0;

            const KUrl dest = KUrl(KStandardDirs::locateLocal("appdata", "checksumsearch/") + QString::number(files++));
            if (QFile::exists(dest.toLocalFile())) {
                KIO::Job *del = KIO::del(dest, KIO::HideProgressInfo);
                KIO::NetAccess::synchronousRun(del, 0);
            }

            if (baseUrl.protocol() != "ftp" && baseUrl.protocol() != "sftp") {
                kDebug(5001) << "Downloading" << baseUrl;
                KIO::FileCopyJob *job = KIO::file_copy(baseUrl, dest, -1, KIO::HideProgressInfo);
                job->addMetaData("errorPage", "false");
                connect(job, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)));
                m_jobs[job] = qMakePair(baseUrl, dest);
            } else {
                kDebug(5001) << "ftp, doing a listjob";
                KIO::ListJob *job = KIO::listDir(baseUrl, KIO::HideProgressInfo);
                connect(job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)), this, SLOT(slotEntries(KIO::Job*,KIO::UDSEntryList)));
                connect(job, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)));
                m_jobs[job] = qMakePair(baseUrl, dest);
            }
        }
    }
Example #8
0
bool ExportManager::remoteSave(const QUrl &url, const QString &mimetype)
{
    QTemporaryFile tmpFile;

    if (tmpFile.open()) {
        if(!writeImage(&tmpFile, mimetype.toLatin1())) {
            emit errorMessage(i18n("Cannot save screenshot. Error while writing temporary local file."));
            return false;
        }

        KIO::FileCopyJob *uploadJob = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url);
        uploadJob->exec();

        if (uploadJob->error() != KJob::NoError) {
            emit errorMessage(i18n("Unable to save image. Could not upload file to remote location."));
            return false;
        }
        return true;
    }

    return false;
}
void KAResourceRemote::slotSaveJobResult(KJob* job)
{
	if (job->error())
	{
		if (hasGui())
		{
			KIO::FileCopyJob* j = qobject_cast<KIO::FileCopyJob*>(job);
			if (j)
				j->ui()->showErrorMessage();
		}
		kError(KARES_DEBUG) << "Resource" << identifier() << " upload error:" << job->errorString();
	}
	else
	{
		kDebug(KARES_DEBUG) << mUploadUrl.prettyUrl() << ": success";
		clearChanges();
	}

	mUploadJob = 0;
	emit resourceSaved(this);
	if (closeAfterSave())
		close();
}
Example #10
0
bool SambaFile::slotApply()
{
  if (readonly) {
      kdDebug(FILESHARE_DEBUG) << "SambaFile::slotApply: readonly=true" << endl;
      return false;
  }      

  // If we have write access to the smb.conf
  // we simply save the values to it
  // if not we have to save the results in
  // a temporary file and copy it afterwards
  // over the smb.conf file with kdesu.
  if (QFileInfo(path).isWritable())
  {
    saveTo(path);
    changed = false;
    return true;
  }

  // Create a temporary smb.conf file
   delete _tempFile;
  _tempFile = new KTempFile();
  _tempFile->setAutoDelete(true);

  if (!saveTo(_tempFile->name())) {
    kdDebug(5009) << "SambaFile::slotApply: Could not save to temporary file" << endl; 
    delete _tempFile;
    _tempFile = 0;
    return false;
  }

  QFileInfo fi(path);
  KURL url(path);

  if (KURL(path).isLocalFile()) {
    KProcess proc;
    kdDebug(5009) << "SambaFile::slotApply: is local file!" << endl;
    
    QString suCommand=QString("cp %1 %2; rm %3")
              .arg(_tempFile->name())
              .arg(path)
              .arg(_tempFile->name());
    proc << "kdesu" << "-d" << suCommand;

    if (! proc.start(KProcess::Block)) {
        kdDebug(5009) << "SambaFile::slotApply: saving to " << path << " failed!" << endl;
        //KMessageBox::sorry(0,i18n("Saving the results to %1 failed.").arg(path));
        delete _tempFile;
        _tempFile = 0;
        return false;
    }        
    else {
        changed = false;
        delete _tempFile;
        _tempFile = 0;
        kdDebug(5009) << "SambaFile::slotApply: changes successfully saved!" << endl;
        return true;
    }        
  } else {
    kdDebug(5009) << "SambaFile::slotApply: is remote file!" << endl;
    _tempFile->setAutoDelete(true);
    KURL srcURL;
    srcURL.setPath( _tempFile->name() );

    KIO::FileCopyJob * job =  KIO::file_copy( srcURL, url, -1, true  );
    connect( job, SIGNAL( result( KIO::Job * ) ), 
             this, SLOT( slotSaveJobFinished ( KIO::Job * ) ) );
    return (job->error()==0);
  }

  return true;
}
int main(int argc, char **argv)
{
    KLocalizedString::setApplicationDomain( "koconverter" );

    K4AboutData aboutData("calligraconverter", 0, ki18n("CalligraConverter"), CalligraVersionWrapper::versionString().toLatin1(),
                         ki18n("Calligra Document Converter"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 2001-2011 Calligra developers"));
    aboutData.addAuthor(ki18n("David Faure"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Nicolas Goutte"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Dan Leinir Turthra Jensen"), KLocalizedString(), "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+in", ki18n("Input file"));
    options.add("+out", ki18n("Output file"));
    options.add("backup", ki18n("Make a backup of the destination file"));
    options.add("batch", ki18n("Batch mode: do not show dialogs"));
    options.add("interactive", ki18n("Interactive mode: show dialogs (default)"));
    options.add("mimetype <mime>", ki18n("Mimetype of the output file"));

    // PDF related options.
    options.add("print-orientation <name>", ki18n("The print orientation. This could be either Portrait or Landscape."));
    options.add("print-papersize <name>", ki18n("The paper size. A4, Legal, Letter, ..."));
    options.add("print-margin <size>", ki18n("The size of the paper margin. By default this is 0.2."));

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->count() != 2) {
        KCmdLineArgs::usageError(i18n("Two arguments required"));
        return 3;
    }

    const QUrl urlIn = args->url(0);
    const QUrl urlOut = args->url(1);

    // Are we in batch mode or in interactive mode.
    bool batch = args->isSet("batch");
    if (args->isSet("interactive")) {
        batch = false;
    }

    if (args->isSet("backup")) {
        // Code form koDocument.cc
        KIO::UDSEntry entry;
        if (KIO::NetAccess::stat(urlOut, entry, 0L)) {   // this file exists => backup
            kDebug() << "Making backup...";
            QUrl backup(urlOut);
            backup.setPath(urlOut.path() + '~');
            KIO::FileCopyJob *job = KIO::file_copy(urlOut, backup, -1, KIO::Overwrite | KIO::HideProgressInfo);
            job->exec();
        }
    }

    QMimeDatabase db;
    QMimeType inputMimetype = db.mimeTypeForUrl(urlIn);
    if (!inputMimetype.isValid() || inputMimetype.isDefault()) {
        kError() << i18n("Mimetype for input file %1 not found!", urlIn.toDisplayString()) << endl;
        return 1;
    }

    QMimeType outputMimetype;
    if (args->isSet("mimetype")) {
        QString mime = args->getOption("mimetype");
        outputMimetype = db.mimeTypeForName(mime);
        if (! outputMimetype.isValid()) {
            kError() << i18n("Mimetype not found %1", mime) << endl;
            return 1;
        }
    } else {
        outputMimetype = db.mimeTypeForUrl(urlOut);
        if (!outputMimetype.isValid() || outputMimetype.isDefault()) {
            kError() << i18n("Mimetype not found, try using the -mimetype option") << endl;
            return 1;
        }
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    QString outputFormat = outputMimetype.name();
    bool ok = false;
    if (outputFormat == "application/pdf") {
        QString orientation = args->getOption("print-orientation");
        QString papersize = args->getOption("print-papersize");
        QString margin = args->getOption("print-margin");
        ok = convertPdf(urlIn, inputMimetype.name(), urlOut, outputFormat, orientation, papersize, margin);
    } else {
        ok = convert(urlIn, inputMimetype.name(), urlOut, outputFormat, batch);
    }

    QTimer::singleShot(0, &app, SLOT(quit()));
    app.exec();

    QApplication::restoreOverrideCursor();

    if (!ok) {
        kError() << i18n("*** The conversion failed! ***") << endl;
        return 2;
    }

    return 0;
}
Example #12
0
bool Manager::replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon) {
	KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL);

	//start by copying the files that belong to the new template to a safe place
	QString templateTempFile, iconTempFile;

	if( newTemplateSourceURL.isLocalFile() ) {
		// file protocol. We do not need the network
		templateTempFile = newTemplateSourceURL.toLocalFile();
	}
	else {
		QTemporaryFile tmpFile;
		tmpFile.setAutoRemove( false );
		tmpFile.open();

		templateTempFile = tmpFile.fileName();
		m_TempFilePath = tmpFile.fileName();
		KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newTemplateSourceURL, QUrl::fromLocalFile(templateTempFile), -1, KIO::Overwrite );
		KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() );

		if( ! fileCopyJob->exec() ) {
			return false;
		}
	}

	if( newIcon.isLocalFile() ) {
		// file protocol. We do not need the network
		iconTempFile = newIcon.toLocalFile();
	}
	else {
		QTemporaryFile tmpFile;
		tmpFile.setAutoRemove( false );
		tmpFile.open();

		iconTempFile = tmpFile.fileName();
		m_TempFilePath = tmpFile.fileName();
		KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newIcon, QUrl::fromLocalFile(iconTempFile), -1, KIO::Overwrite );
		KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() );

		if( ! fileCopyJob->exec() ) {
			if( ! templateTempFile.isEmpty() )
				QFile::remove( templateTempFile );
			return false;
		}
	}

	//now delete the template that should be replaced
	if(!remove(toBeReplaced)) {
		if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
		if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );
	}

	//finally, create the new template
	if(!add(QUrl::fromUserInput(templateTempFile), type, newName, QUrl::fromUserInput(iconTempFile))) {
		if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
		if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );
		return false;
	}

	if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
	if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );

	return true;
}