Exemple #1
0
void RemoteProtocol::listDir(const KUrl &url)
{
	kDebug(1220) << "RemoteProtocol::listDir: " << url;

	if ( url.path().length() <= 1 )
	{
		listRoot();
		return;
	}

	int second_slash_idx = url.path().indexOf( '/', 1 );
	const QString root_dirname = url.path().mid( 1, second_slash_idx-1 );

	KUrl target = m_impl.findBaseURL( root_dirname );
	kDebug(1220) << "possible redirection target : " << target;
	if( target.isValid() )
	{
		if ( second_slash_idx < 0 ) {
			second_slash_idx = url.path().size();
		}
		target.addPath( url.path().remove(0, second_slash_idx) );
		kDebug(1220) << "complete redirection target : " << target;
		redirection(target);
		finished();
		return;
	}

	error(KIO::ERR_MALFORMED_URL, url.prettyUrl());
}
Exemple #2
0
void TrashProtocol::restore( const KUrl& trashURL )
{
    int trashId;
    QString fileId, relativePath;
    bool ok = TrashImpl::parseURL( trashURL, trashId, fileId, relativePath );
    if ( !ok ) {
        error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1", trashURL.prettyUrl() ) );
        return;
    }
    TrashedFileInfo info;
    ok = impl.infoForFile( trashId, fileId, info );
    if ( !ok ) {
        error( impl.lastErrorCode(), impl.lastErrorMessage() );
        return;
    }
    KUrl dest;
    dest.setPath( info.origPath );
    if ( !relativePath.isEmpty() )
        dest.addPath( relativePath );

    // Check that the destination directory exists, to improve the error code in case it doesn't.
    const QString destDir = dest.directory();
    KDE_struct_stat buff;
    if ( KDE_lstat( QFile::encodeName( destDir ), &buff ) == -1 ) {
        error( KIO::ERR_SLAVE_DEFINED,
               i18n( "The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
                     "You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it.", destDir ) );
        return;
    }

    copyOrMove( trashURL, dest, false /*overwrite*/, Move );
}
void DocbookGenerator::slotDocbookGenerationFinished(const QString& tmpFileName)
{
    uDebug() << "Generation Finished" << tmpFileName;
    KUrl url = umlDoc->url();
    QString fileName = url.fileName();
    fileName.replace(QRegExp(".xmi$"),".docbook");
    url.setPath(m_destDir.path());
    url.addPath(fileName);

    KIO::Job* job = KIO::file_copy(KUrl::fromPath(tmpFileName), url, -1, KIO::Overwrite | KIO::HideProgressInfo);
    if ( KIO::NetAccess::synchronousRun( job, (QWidget*)UMLApp::app() ) ) {
        umlDoc->writeToStatusBar(i18n("Docbook Generation Complete..."));
        m_pStatus = true;
    } else {
        umlDoc->writeToStatusBar(i18n("Docbook Generation Failed..."));
        m_pStatus = false;
    }

    while ( m_pThreadFinished == false ) {
        // wait for thread to finish
        qApp->processEvents();
    }

    emit finished(m_pStatus);
}
Exemple #4
0
void ScanGallery::slotUrlsDropped(QDropEvent *ev, FileTreeViewItem *item)
{
    KUrl::List urls = ev->mimeData()->urls();
    if (urls.isEmpty()) return;

    kDebug() << "onto" << (item==NULL ? "NULL" : item->url().prettyUrl())
             << "srcs" << urls.count() << "first" << urls.first();
    
    if (item==NULL) return;
    KUrl dest = item->url();

    // Check whether the drop is on top of a directory (in which case we
    // want to move/copy into it) or a file (move/copy into its containing
    // directory).
    if (!item->isDir()) dest.setFileName(QString::null);
    dest.adjustPath(KUrl::AddTrailingSlash);
    kDebug() << "resolved destination" << dest;

    // Make the last URL to copy the one to select next
    KUrl nextSel = dest;
    nextSel.addPath(urls.back().fileName(KUrl::ObeyTrailingSlash));
    m_nextUrlToShow = nextSel;

    KIO::Job *job;
    // TODO: top level window as 3rd parameter?
    if (ev->dropAction()==Qt::MoveAction) job = KIO::move(urls, dest);
    else job = KIO::copy(urls, dest);
    connect(job, SIGNAL(result(KJob *)), SLOT(slotJobResult(KJob *)));
}
void TemplatePage::extractTemplate()
{
    QModelIndex index = ui->treeView->currentIndex();
    QString archiveName= ui->treeView->model()->data(index, KDevelop::TemplatesModel::ArchiveFileRole).toString();

    QFileInfo info(archiveName);
    if (!info.exists())
    {
        ui->extractButton->setEnabled(false);
        return;
    }

    QScopedPointer<KArchive> archive;
    if (info.suffix() == QLatin1String("zip"))
    {
        archive.reset(new KZip(archiveName));
    }
    else
    {
        archive.reset(new KTar(archiveName));
    }

    archive->open(QIODevice::ReadOnly);

    KUrl destination = KUrl::fromLocalFile(KFileDialog::getExistingDirectory());
    destination.addPath(info.baseName());
    archive->directory()->copyTo(destination.toLocalFile());
}
Exemple #6
0
KUrl LaconicaSearch::buildUrl(const SearchInfo &searchInfo,
                              ChoqokId sinceStatusId, uint count, uint page)
{
    kDebug();

    QString formattedQuery;
    switch ( searchInfo.option ) {
        case ToUser:
            formattedQuery = searchInfo.query + "/replies/rss";
            break;
        case FromUser:
            formattedQuery = searchInfo.query + "/rss";
            break;
        case ReferenceGroup:
            formattedQuery = "group/" + searchInfo.query + "/rss";
            break;
        case ReferenceHashtag:
            formattedQuery = searchInfo.query;
            break;
        default:
            formattedQuery = searchInfo.query + "/rss";
            break;
    };

    KUrl url;
    TwitterApiAccount *theAccount = qobject_cast<TwitterApiAccount*>(searchInfo.account);
    Q_ASSERT(theAccount);
    if( searchInfo.option == ReferenceHashtag ) {
        url = theAccount->apiUrl();
        url.addPath("/search.atom");
        url.addQueryItem("q", formattedQuery);
        if( !sinceStatusId.isEmpty() )
            url.addQueryItem( "since_id", sinceStatusId );
        int cntStr = Choqok::BehaviorSettings::countOfPosts();
        if( count && count <= 100 )
            cntStr =  count;
        url.addQueryItem( "rpp", QString::number(cntStr) );
        if( page > 1 )
            url.addQueryItem( "page", QString::number( page ) );
    } else {
        url = theAccount->apiUrl().url(KUrl::AddTrailingSlash).remove("api/", Qt::CaseInsensitive);
        url.addPath( formattedQuery );
    }
    return url;
}
Exemple #7
0
bool CvsProxy::isValidDirectory(KUrl dirPath) const
{
    QFileInfo fsObject( dirPath.toLocalFile() );
    if( !fsObject.isDir() )
        dirPath.setFileName( QString() );

    dirPath.addPath( "CVS" );
    fsObject.setFile( dirPath.toLocalFile() );
    return fsObject.exists();
}
Exemple #8
0
QString DirSortPlugin::processFile( BatchRenamer* b, int index, const QString &, EPluginType )
{
    QString errorMsg = QString::null;

    if( index == 0 )
    {
        // Initialize plugin
        m_dirCounter = m_widget->spinStart->value();
        m_fileCounter = 0;
        m_filesPerDir = m_widget->spinFiles->value();
        m_digits = m_widget->spinDigits->value();
        m_baseDirectory = m_widget->outputUrl->url();

        if( !KIO::NetAccess::exists( m_baseDirectory, true, m_widget->spinStart ) ) 
        {
            m_valid = false;
            return this->name() + 
                i18n(": The output directory %1 does not exist.", 
                     m_baseDirectory.prettyUrl() ); 
        }
        else 
        {
            m_valid = true;

            m_currentDirectory = createNewSubdirectory();
        }
    }
    
    if( !m_valid ) 
        return errorMsg;

    if( m_fileCounter == m_filesPerDir ) 
    {
        m_fileCounter = 0;
        m_dirCounter++;

        m_currentDirectory = createNewSubdirectory();
    }

    KUrl srcUrl = b->buildDestinationUrl( (*b->files())[index] );
    KUrl dstUrl = m_currentDirectory;
    dstUrl.addPath( srcUrl.fileName() );
    KIO::JobFlags flags = KIO::DefaultFlags | KIO::HideProgressInfo;
    KIO::Job* job = KIO::file_move( srcUrl, dstUrl, -1, flags );
    m_fileCounter++;
    if( m_valid && job && !KIO::NetAccess::synchronousRun( job, m_widget->spinStart ) ) 
    {
        errorMsg = i18n("Error renaming %2 (to %1)", 
                        dstUrl.prettyUrl(), 
                        srcUrl.prettyUrl());
    } 

    return errorMsg;
}
void KPrHtmlExport::exportImageToTmpDir()
{
    // Export slides as image into the temporary export directory
    KUrl fileUrl;
    for(int i=0; i < m_parameters.slides.size(); ++i){
        fileUrl = m_tmpDirPath;
        fileUrl.addPath(QString("slide%1.png").arg(i));
        KoPAPageBase *slide = m_parameters.slides.at(i);
        m_parameters.kprView->exportPageThumbnail(slide,fileUrl, slide->size().toSize(), "PNG", -1);
    }
}
Exemple #10
0
bool CvsProxy::isVersionControlled(KUrl filePath) const
{
    QFileInfo fsObject( filePath.toLocalFile() );
    if( !fsObject.isDir() )
        filePath.setFileName( QString() );

    filePath.addPath( "CVS" );
    QFileInfo cvsObject( filePath.toLocalFile() );
    if( !cvsObject.exists() )
        return false;

    if( fsObject.isDir() )
        return true;

    filePath.addPath( "Entries" );
    QFile cvsEntries( filePath.toLocalFile() );
    cvsEntries.open( QIODevice::ReadOnly );
    QString cvsEntriesData = cvsEntries.readAll();
    cvsEntries.close();
    return ( cvsEntriesData.indexOf( fsObject.fileName() ) != -1 );
}
Exemple #11
0
// only used for the queries
bool Nepomuk2::TimelineProtocol::rewriteUrl( const KUrl& url, KUrl& newURL )
{
    if ( parseTimelineUrl( url, &m_date, &m_filename ) == DayFolder ) {
        newURL = buildTimelineQuery( m_date ).toSearchUrl();
        newURL.addPath( m_filename );
        kDebug() << url << newURL;
        return true;
    }
    else {
        return false;
    }
}
/**
 * Triggered when the copying of the HTML result file is finished.
 * Emits the signal finished().
 * @param tmpFileName   temporary file name
 */
void XhtmlGenerator::slotHtmlGenerated(const QString& tmpFileName)
{
    uDebug() << "HTML Generated " << tmpFileName;
    KUrl url = m_umlDoc->url();
    QString fileName = url.fileName();
    fileName.replace(QRegExp(".xmi$"),".html");
    url.setPath(m_destDir.path());
    url.addPath(fileName);

    KIO::Job* htmlCopyJob = KIO::file_copy( KUrl::fromPath( tmpFileName ), url, -1, KIO::Overwrite | KIO::HideProgressInfo );
    if ( KIO::NetAccess::synchronousRun( htmlCopyJob, (QWidget*)UMLApp::app() ) ) {
        m_umlDoc->writeToStatusBar(i18n("XHTML Generation Complete..."));
    } else {
        m_pStatus = false;
        return;
    }

    m_umlDoc->writeToStatusBar(i18n("Copying CSS..."));

    QString cssFileName(KGlobal::dirs()->findResource("appdata","xmi.css"));
    KUrl cssUrl = m_destDir;
    cssUrl.addPath("xmi.css");
    KIO::Job* cssJob = KIO::file_copy(cssFileName,cssUrl,-1, KIO::Overwrite | KIO::HideProgressInfo );

    if ( KIO::NetAccess::synchronousRun( cssJob, (QWidget*)UMLApp::app() ) ) {
        m_umlDoc->writeToStatusBar(i18n("Finished Copying CSS..."));
        m_pStatus = true;
    } else {
        m_umlDoc->writeToStatusBar(i18n("Failed Copying CSS..."));
        m_pStatus = false;
    }

    while ( m_pThreadFinished == false ) {
        // wait for thread to finish
        qApp->processEvents();
    }

    emit finished( m_pStatus );
}
Exemple #13
0
bool HgConfig::getConfigFilePath()
{
    switch (m_configType) {
    case RepoConfig:
        {
            KUrl repoBase = KUrl(HgWrapper::instance()->getBaseDir());
            repoBase.addPath(QLatin1String(".hg/hgrc"));
            m_configFilePath = repoBase.path();
            break;
        }
    case GlobalConfig:
        {
            KUrl homeUrl = KUrl(QDir::homePath());
            homeUrl.addPath(QLatin1String(".hgrc"));
            m_configFilePath = homeUrl.path();
            break;
        }
    case TempConfig:
        break;
    }
    return true;
}
void KonqPopupMenuPrivate::slotShowOriginalFile()
{
    const KFileItem item = m_popupItemProperties.items().first();
    const QString dest = item.linkDest();
    KUrl destUrl = m_sViewURL;
    if (dest.startsWith('/')) {
        destUrl.setPath(dest);
    } else {
        destUrl.addPath(dest);
    }
    // Now destUrl points to the target file, let's go up to parent dir
    destUrl.setPath(destUrl.directory());
    KRun::runUrl(destUrl, "inode/directory", m_parentWidget);
}
Exemple #15
0
KUrl DirSortPlugin::createNewSubdirectory() const
{
    KUrl url = m_baseDirectory;

    QString dir;
    dir.sprintf("%0*i", m_digits, m_dirCounter );
    url.addPath( dir );

    if( !KIO::NetAccess::mkdir( url, m_widget->spinStart ) ) {
        KMessageBox::error( m_widget->spinStart, 
                            i18n("Cannot create directory %1", url.prettyUrl()) );
    }
    
    return url;    
}
Exemple #16
0
bool
ScriptImporter::include( const QString& relativeFilename )
{
    KUrl includeUrl = m_scriptUrl.upUrl();
    includeUrl.addPath( relativeFilename );
    QFile file( includeUrl.toLocalFile() );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        warning() << "cannot open the include file!";
        return false;
    }
    m_scriptEngine->currentContext()->setActivationObject(
                            m_scriptEngine->currentContext()->parentContext()->activationObject() );
    m_scriptEngine->evaluate( file.readAll(), relativeFilename );
    return true;
}
KUrl KPrHtmlExport::exportPreview(const Parameter &parameters)
{
    m_parameters = parameters;

    // Create a temporary dir
    KTempDir tmpDir;
    tmpDir.setAutoRemove(false);
    m_tmpDirPath = tmpDir.name();
    extractStyle();
    exportImageToTmpDir();
    generateHtml();

    KUrl previewUrl;
    previewUrl.setPath(tmpDir.name());
    previewUrl.addPath("slide0.html");
    return previewUrl;
}
Exemple #18
0
 void importNext()
 {
     if (mUrlList.empty()) {
         q->finalizeImport();
         return;
     }
     mCurrentUrl = mUrlList.takeFirst();
     KUrl dst = mTempImportDir;
     dst.addPath(mCurrentUrl.fileName());
     KIO::Job* job = KIO::copy(mCurrentUrl, dst, KIO::HideProgressInfo);
     if (job->ui()) {
         job->ui()->setWindow(mAuthWindow);
     }
     QObject::connect(job, SIGNAL(result(KJob*)),
                      q, SLOT(slotCopyDone(KJob*)));
     QObject::connect(job, SIGNAL(percent(KJob*,ulong)),
                      q, SLOT(slotPercent(KJob*,ulong)));
 }
Exemple #19
0
/* ----------------------------------------------------------------------- */
void ScanGallery::slotCreateFolder( )
{
   bool ok;
   QString folder = KInputDialog::getText( i18n( "New Folder" ),
         i18n( "Name for the new folder:" ), QString::null,
         &ok, this );

   if( ok )
   {
	 /* KIO create folder goes here */

	 FileTreeViewItem *it = highlightedFileTreeViewItem();
	 if( it )
	 {
	    KUrl url = it->url();

	    /* If a directory is selected, the filename needs not to be deleted */
	    if( ! it->isDir())
	       url.setFileName( "" );
	    /* add the folder name from user input */
	    url.addPath( folder );
	    kDebug() << "Creating folder" << url;

	    /* Since the new directory arrives in the packager in the newItems-slot, we set a
	     * variable urlToSelectOnArrive here. The newItems-slot will honor it and select
	     * the treeviewitem with that url.
	     */
	    slotSetNextUrlToSelect( url );

	    if( ! KIO::NetAccess::mkdir( url, 0, -1 ))
	    {
	       kDebug() << "Error: creation of" << url << "failed!";
	    }
	    else
	    {
	       /* created successfully */
	       /* open the branch if necessary and select the new folder */

	    }
	 }
   }
}
Exemple #20
0
KUrl ProjectModel::potToPo(const KUrl& potPath) const
{
    if (!m_potUrl.isParentOf(potPath))
    {
        kWarning()<<"POT path not in project: " << potPath.url();
        return KUrl();
    }

    QString pathToAdd = KUrl::relativeUrl(m_potUrl, potPath);

    //change ".pot" into ".po"
    if (pathToAdd.endsWith(".pot")) //TODO: what about folders ??
        pathToAdd = pathToAdd.left(pathToAdd.length() - 1);

    KUrl poPath = m_poUrl;
    poPath.addPath(pathToAdd);

    //kDebug() << "ProjectModel::potToPo("<< potPath.pathOrUrl() << +") = " << poPath.pathOrUrl();
    return poPath;
}
bool ImgurTalker::imageRemove(const QString& delete_hash)
{
    // @TODO : make sure it works
    MPForm form;

    KUrl removeUrl = KUrl("http://api.imgur.com/2/delete/");
    removeUrl.addPath(delete_hash + ".json");

    form.finish();

    KIO::TransferJob* job = KIO::http_post(removeUrl, form.formData(), KIO::HideProgressInfo);
    job->addMetaData("content-type", form.contentType());
    job->addMetaData("UserAgent", m_userAgent);

    m_state = IE_REMOVEPHOTO;

    emit signalBusy(true);

    return true;
}
KUrl MakeOutputModel::urlForFile( const QString& filename ) const
{
    QFileInfo fi(filename);
    KUrl u;
    if( fi.isRelative() )
    {
        if( currentDir.isEmpty() ) 
        {
            u = buildDir;
        } else
        {
            u = KUrl( currentDir );
        }
        u.addPath( filename );
    } else 
    {
        u = KUrl( filename );
    }
    return u;
}
Exemple #23
0
void ScanGallery::slotImportFile()
{
    FileTreeViewItem *curr = highlightedFileTreeViewItem();
    if( ! curr ) return;

    KUrl impTarget = curr->url();

    if( ! curr->isDir() )
    {
        FileTreeViewItem *pa = static_cast<FileTreeViewItem*>(curr->parent());
        impTarget = pa->url();
    }
    kDebug() << "Importing to" << impTarget;

    KUrl impUrl = KFileDialog::getImageOpenUrl(KUrl("kfiledialog:///importImage"), this, i18n("Import Image File to Gallery"));
    if (impUrl.isEmpty()) return;

    impTarget.addPath(impUrl.fileName());		// append the name of the sourcefile to the path
    m_nextUrlToShow = impTarget;
    ImgSaver::copyImage(impUrl, impTarget);
}
Exemple #24
0
void KFileItemPrivate::readUDSEntry( bool _urlIsDirectory )
{
    // extract fields from the KIO::UDS Entry

    m_fileMode = m_entry.numberValue( KIO::UDSEntry::UDS_FILE_TYPE );
    m_permissions = m_entry.numberValue( KIO::UDSEntry::UDS_ACCESS );
    m_strName = m_entry.stringValue( KIO::UDSEntry::UDS_NAME );

    const QString displayName = m_entry.stringValue( KIO::UDSEntry::UDS_DISPLAY_NAME );
    if (!displayName.isEmpty())
      m_strText = displayName;
    else
      m_strText = KIO::decodeFileName( m_strName );

    const QString urlStr = m_entry.stringValue( KIO::UDSEntry::UDS_URL );
    const bool UDS_URL_seen = !urlStr.isEmpty();
    if ( UDS_URL_seen ) {
        m_url = KUrl( urlStr );
        if ( m_url.isLocalFile() )
            m_bIsLocalUrl = true;
    }
    const QString mimeTypeStr = m_entry.stringValue( KIO::UDSEntry::UDS_MIME_TYPE );
    m_bMimeTypeKnown = !mimeTypeStr.isEmpty();
    if ( m_bMimeTypeKnown )
        m_pMimeType = KMimeType::mimeType( mimeTypeStr );

    m_guessedMimeType = m_entry.stringValue( KIO::UDSEntry::UDS_GUESSED_MIME_TYPE );
    m_bLink = !m_entry.stringValue( KIO::UDSEntry::UDS_LINK_DEST ).isEmpty(); // we don't store the link dest

    const int hiddenVal = m_entry.numberValue( KIO::UDSEntry::UDS_HIDDEN, -1 );
    m_hidden = hiddenVal == 1 ? Hidden : ( hiddenVal == 0 ? Shown : Auto );

    // avoid creating these QStrings again and again
    static const QString& dot = KGlobal::staticQString(".");
    if ( _urlIsDirectory && !UDS_URL_seen && !m_strName.isEmpty() && m_strName != dot )
        m_url.addPath( m_strName );

    m_iconName.clear();
}
void BatchProcessImagesDialog::processAborted(bool removeFlag)
{
    kDebug() << "BatchProcessImagesDialog::processAborted";

    BatchProcessImagesItem *item = static_cast<BatchProcessImagesItem*>(**m_listFile2Process_iterator);
    m_listFiles->scrollToItem(m_listFiles->currentItem());

    item->changeResult(i18n("Aborted."));
    item->changeError(i18n("process aborted by user"));

    if (removeFlag == true)
    { // Try to delete de destination !
        KUrl deleteImage = m_ui->m_destinationUrl->url();
        deleteImage.addPath(item->nameDest());

        if (KIO::NetAccess::exists(deleteImage, KIO::NetAccess::DestinationSide, kapp->activeWindow())
                == true)
            KIO::NetAccess::del(deleteImage, kapp->activeWindow());
    }

    endProcess();
}
void FileManager::createNewFile()
{
    KParts::MainWindow *activeMainWindow = KDevelop::ICore::self()->uiController()->activeMainWindow();

    //TODO: adymo: use KNameAndUrlInputDialog here once we depend on KDE 4.5
    bool ok = false;
    QString fileName = KInputDialog::getText(i18n("Create New File"),
        i18n("Filename:"), "", &ok, activeMainWindow);
    if (!ok) return;

    KTemporaryFile tmpFile;
    if (!tmpFile.open()) {
        kError() << "Couldn't create temp file!";
        return;
    }

    KUrl destUrl = dirop->url();
    destUrl.addPath(fileName);

    if (KIO::NetAccess::file_copy(KUrl(tmpFile.fileName()), destUrl))
        KDevelop::ICore::self()->documentController()->openDocument( destUrl );
    else
        KMessageBox::error(activeMainWindow, i18n("Unable to create file '%1'").arg(fileName));
}
/**
 * This slot is triggerd when the first part, xmi to docbook, is finished
 * @param status   status to continue with converting
 */
void XhtmlGenerator::slotDocbookToXhtml(bool status)
{
    uDebug() << "Now convert docbook to html...";
    if ( !status ) {
        uDebug() << "Error in converting to docbook";
        m_pStatus = false;
        return;
    }
    else {
        KUrl url = m_umlDoc->url();
        QString fileName = url.fileName();
        fileName.replace(QRegExp(".xmi$"),".docbook");
        url.setPath(m_destDir.path());
        url.addPath(fileName);

        m_umlDoc->writeToStatusBar( i18n( "Generating XHTML..." ) );
        m_d2xg  = new Docbook2XhtmlGeneratorJob( url, this );
        connect(m_d2xg, SIGNAL(xhtmlGenerated(QString)),
                this, SLOT(slotHtmlGenerated(QString)));
        connect(m_d2xg, SIGNAL(finished()), this, SLOT(threadFinished()));
        uDebug() << "Threading";
        m_d2xg->start();
    }
}
void RenameImagesWidget::slotNext()
{
    QTreeWidgetItem* it = ui->m_listView->selectedItems().first();
    if (!it)
    {
        slotAbort();
        return;
    }

    BatchProcessImagesItem* item = static_cast<BatchProcessImagesItem*>(it);
    KUrl src;
    src.setPath(item->pathSrc());
    KUrl dst = src.upUrl();
    dst.addPath(item->text(2));

    bool skip      = false;
    bool overwrite = false;

    if (!m_overwriteAll)
    {
        KDE_struct_stat info;
        while (KDE_stat(QFile::encodeName(dst.toLocalFile()), &info) == 0)
        {
            if (m_autoSkip)
            {
                skip = true;
                break;
            }

            QPointer<KIO::RenameDialog> dlg = new KIO::RenameDialog(this, i18n("Rename File"),
                                              src.path(), dst.path(),
                                              KIO::RenameDialog_Mode(KIO::M_MULTI | KIO::M_OVERWRITE | KIO::M_SKIP));
            int result = dlg->exec();
            dst        = dlg->newDestUrl();

            delete dlg;

            switch (result)
            {
                case KIO::R_CANCEL:
                {
                    slotAbort();
                    return;
                }
                case KIO::R_SKIP:
                {
                    skip = true;
                    break;
                }
                case KIO::R_AUTO_SKIP:
                {
                    m_autoSkip = true;
                    skip       = true;
                    break;
                }
                case KIO::R_OVERWRITE:
                {
                    overwrite       = true;
                    break;
                }
                case KIO::R_OVERWRITE_ALL:
                {
                    m_overwriteAll = true;
                    overwrite      = true;
                    break;
                }
                default:
                    break;
            }

            if (skip || overwrite)
                break;
        }
    }

    if (skip)
    {
        item->changeResult(i18nc("batch process result", "Skipped"));
    }
    else
    {
        // Get the src info
        KIPIPlugins::KPImageInfo srcInfo(src);

        if (KDE_rename(QFile::encodeName(src.toLocalFile()),
                       QFile::encodeName(dst.toLocalFile())) == 0)
        {
            // Rename XMP sidecar file
            KIPIPlugins::KPMetadata::moveSidecar(src, dst);

            srcInfo.setName(dst.fileName());

            item->changeResult(i18nc("batch process result", "OK"));
        }
        else
        {
            item->changeResult(i18nc("batch process result", "Failed"));
        }
    }

    m_progress->progressBar()->setValue(m_progress->progressBar()->value() + 1);

    it = ui->m_listView->itemBelow(it);
    if (it)
    {
        ui->m_listView->setCurrentItem(it);
        ui->m_listView->scrollToItem(it);
        m_timer->setSingleShot(true);
        m_timer->start(0);
    }
}
void TestRegressionWindow::initTestsDirectory()
{
	bool okay = !m_testsUrl.isEmpty();
	if(okay)
	{
		const char *subdirs[] = { "tests", "baseline", "output", "resources" };
		for(int i = 0; i <= 3; i++)
		{
			QFileInfo sourceDir(m_testsUrl.path() + "/" + subdirs[i]);	//krazy:exclude=duoblequote_chars DOM demands chars
			if(!sourceDir.exists() || !sourceDir.isDir())
			{
				KMessageBox::error(0, i18n("Please choose a valid 'khtmltests/regression/' directory."));

				okay = false;
				m_testsUrl = KUrl();
				break;
			}
		}
	}

	if(okay)
	{
		// Clean up...
		m_itemMap.clear();
		m_ignoreMap.clear();
		m_failureMap.clear();
		m_directoryMap.clear();

		m_ui.treeWidget->clear();

		if(!m_khtmlUrl.isEmpty())
			m_ui.actionRun_tests->setEnabled(true);

		// Initialize map (to prevent assert below)...
		m_directoryMap.insert(QString(), QStringList());

		// Setup root tree widget item...
		(void) new QTreeWidgetItem(m_ui.treeWidget, QStringList(m_testsUrl.path() + "/tests"));

		// Check for ignore & failure file in root directory...
		QString ignoreFile = m_testsUrl.path() + "/tests/ignore";
		QString failureFile = m_testsUrl.path() + "/tests/KNOWN_FAILURES";

		QStringList ignoreFileList = readListFile(ignoreFile);
		QStringList failureFileList = readListFile(failureFile);

		if(!ignoreFileList.isEmpty())
			m_ignoreMap.insert(QString(), ignoreFileList);

		if(!failureFileList.isEmpty())
			m_failureMap.insert(QString(), failureFileList);

		// Remember directory...
		KConfig config("testregressiongui", KConfig::SimpleConfig);
		KConfigGroup grp = config.group("<default>");
		grp.writePathEntry("TestsDirectory", m_testsUrl.path());

		// Start listing directory...
		KUrl listUrl = m_testsUrl; listUrl.addPath("tests");
		KIO::ListJob *job = KIO::listRecursive(listUrl, KIO::HideProgressInfo, false /* no hidden files */);

		connect(job, SIGNAL(result(KJob *)), SLOT(directoryListingFinished(KJob *)));

		connect(job, SIGNAL(entries(KIO::Job *, const KIO::UDSEntryList &)),
				this, SLOT(directoryListingResult(KIO::Job *, const KIO::UDSEntryList &)));
	}
}
Exemple #30
0
bool MetalinkXml::metalinkInit(const KUrl &src, const QByteArray &data)
{
    kDebug(5001);

    if (!src.isEmpty()) {
        m_localMetalinkLocation = src;
    }

    //use the downloaded metalink-file data directly if possible
    if (!data.isEmpty()) {
        KGetMetalink::HandleMetalink::load(data, &m_metalink);
    }

    //try to parse the locally stored metalink-file
    if (!m_metalink.isValid() && m_localMetalinkLocation.isValid()) {
        KGetMetalink::HandleMetalink::load(m_localMetalinkLocation.toLocalFile(), &m_metalink);
    }

    if (!m_metalink.isValid()) {
        kError(5001) << "Unknown error when trying to load the .metalink-file. Metalink is not valid.";
        setStatus(Job::Aborted);
        setTransferChange(Tc_Status, true);
        return false;
    }

    //offers a dialog to download the newest version of a dynamic metalink
     if ((m_source.isLocalFile() || !m_metalinkJustDownloaded) &&
         m_metalink.dynamic && (UrlChecker::checkSource(m_metalink.origin) == UrlChecker::NoError)) {
        if (KMessageBox::questionYesNo(0, i18n("A newer version of this Metalink might exist, do you want to download it?"),
                                       i18n("Redownload Metalink")) == KMessageBox::Yes) {
            m_localMetalinkLocation.clear();
            m_source = m_metalink.origin;
            downloadMetalink();
            return false;
        }
    }

    QList<KGetMetalink::File>::const_iterator it;
    QList<KGetMetalink::File>::const_iterator itEnd = m_metalink.files.files.constEnd();
    m_totalSize = 0;
    KIO::fileoffset_t segSize = 500 * 1024;//TODO use config here!
    const KUrl tempDest = KUrl(m_dest.directory());
    KUrl dest;
    for (it = m_metalink.files.files.constBegin(); it != itEnd ; ++it)
    {
        dest = tempDest;
        dest.addPath((*it).name);

        QList<KGetMetalink::Url> urlList = (*it).resources.urls;
        //sort the urls according to their priority (highest first)
        qSort(urlList.begin(), urlList.end(), qGreater<KGetMetalink::Url>());

        KIO::filesize_t fileSize = (*it).size;
        m_totalSize += fileSize;

        //create a DataSourceFactory for each separate file
        DataSourceFactory *dataFactory = new DataSourceFactory(this, dest, fileSize, segSize);
        dataFactory->setMaxMirrorsUsed(MetalinkSettings::mirrorsPerFile());

#ifdef HAVE_NEPOMUK
        nepomukHandler()->setProperties((*it).properties(), QList<KUrl>() << dest);
#endif //HAVE_NEPOMUK

//TODO compare available file size (<size>) with the sizes of the server while downloading?

        connect(dataFactory, SIGNAL(capabilitiesChanged()), this, SLOT(slotUpdateCapabilities()));
        connect(dataFactory, SIGNAL(dataSourceFactoryChange(Transfer::ChangesFlags)), this, SLOT(slotDataSourceFactoryChange(Transfer::ChangesFlags)));
        connect(dataFactory->verifier(), SIGNAL(verified(bool)), this, SLOT(slotVerified(bool)));
        connect(dataFactory->signature(), SIGNAL(verified(int)), this, SLOT(slotSignatureVerified()));
        connect(dataFactory, SIGNAL(log(QString,Transfer::LogLevel)), this, SLOT(setLog(QString,Transfer::LogLevel)));

        //add the DataSources
        for (int i = 0; i < urlList.size(); ++i)
        {
            const KUrl url = urlList[i].url;
            if (url.isValid())
            {
                dataFactory->addMirror(url, MetalinkSettings::connectionsPerUrl());
            }
        }
        //no datasource has been created, so remove the datasource factory
        if (dataFactory->mirrors().isEmpty())
        {
            delete dataFactory;
        }
        else
        {
            dataFactory->verifier()->addChecksums((*it).verification.hashes);

            foreach (const KGetMetalink::Pieces &pieces, (*it).verification.pieces) {
                dataFactory->verifier()->addPartialChecksums(pieces.type, pieces.length, pieces.hashes);
            }

            const QHash <QString, QString> signatures = (*it).verification.signatures;
            QHash<QString, QString>::const_iterator it;
            QHash<QString, QString>::const_iterator itEnd = signatures.constEnd();
            for (it = signatures.constBegin(); it != itEnd; ++it) {
                if (it.key().toLower() == "pgp") {
                    dataFactory->signature()->setAsciiDetatchedSignature(*it);
                }
            }

            m_dataSourceFactory[dataFactory->dest()] = dataFactory;
        }
    }

    if ((m_metalink.files.files.size() == 1) &&   m_dataSourceFactory.size())
    {
        m_dest = dest;
    }

    if (!m_dataSourceFactory.size()) {
        //TODO make this via log in the future + do not display the KMessageBox
        kWarning(5001) << "Download of" << m_source << "failed, no working URLs were found.";
        KMessageBox::error(0, i18n("Download failed, no working URLs were found."), i18n("Error"));
        setStatus(Job::Aborted);
        setTransferChange(Tc_Status, true);
        return false;
    }

    m_ready = !m_dataSourceFactory.isEmpty();
    slotUpdateCapabilities();

    //the metalink-file has just been downloaded, so ask the user to choose the files that
    // should be downloaded
    /* TODO this portion seems not to be working. Need to ask boom1992 */
    if (m_metalinkJustDownloaded) {
        KDialog *dialog = new FileSelectionDlg(fileModel());
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(dialog, SIGNAL(finished(int)), this, SLOT(fileDlgFinished(int)));

        dialog->show();
    }

    return true;
}