• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.8.5 API Reference
  • KDE Home
  • Contact Us
 

KIO

copyjob.cpp
Go to the documentation of this file.
00001 /* This file is part of the KDE libraries
00002     Copyright 2000       Stephan Kulow <coolo@kde.org>
00003     Copyright 2000-2006  David Faure <faure@kde.org>
00004     Copyright 2000       Waldo Bastian <bastian@kde.org>
00005 
00006     This library is free software; you can redistribute it and/or
00007     modify it under the terms of the GNU Library General Public
00008     License as published by the Free Software Foundation; either
00009     version 2 of the License, or (at your option) any later version.
00010 
00011     This library is distributed in the hope that it will be useful,
00012     but WITHOUT ANY WARRANTY; without even the implied warranty of
00013     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014     Library General Public License for more details.
00015 
00016     You should have received a copy of the GNU Library General Public License
00017     along with this library; see the file COPYING.LIB.  If not, write to
00018     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00019     Boston, MA 02110-1301, USA.
00020 */
00021 
00022 #include "copyjob.h"
00023 #include <errno.h>
00024 #include "kdirlister.h"
00025 #include "kfileitem.h"
00026 #include "deletejob.h"
00027 
00028 #include <klocale.h>
00029 #include <kdesktopfile.h>
00030 #include <kdebug.h>
00031 #include <kde_file.h>
00032 
00033 #include "slave.h"
00034 #include "scheduler.h"
00035 #include "kdirwatch.h"
00036 #include "kprotocolmanager.h"
00037 
00038 #include "jobuidelegate.h"
00039 
00040 #include <kdirnotify.h>
00041 #include <ktemporaryfile.h>
00042 
00043 #ifdef Q_OS_UNIX
00044 #include <utime.h>
00045 #endif
00046 #include <assert.h>
00047 
00048 #include <QtCore/QTimer>
00049 #include <QtCore/QFile>
00050 #include <sys/stat.h> // mode_t
00051 #include <QPointer>
00052 
00053 #include "job_p.h"
00054 #include <kdiskfreespaceinfo.h>
00055 #include <kfilesystemtype_p.h>
00056 
00057 using namespace KIO;
00058 
00059 //this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
00060 #define REPORT_TIMEOUT 200
00061 
00062 enum DestinationState {
00063     DEST_NOT_STATED,
00064     DEST_IS_DIR,
00065     DEST_IS_FILE,
00066     DEST_DOESNT_EXIST
00067 };
00068 
00085 enum CopyJobState {
00086     STATE_STATING,
00087     STATE_RENAMING,
00088     STATE_LISTING,
00089     STATE_CREATING_DIRS,
00090     STATE_CONFLICT_CREATING_DIRS,
00091     STATE_COPYING_FILES,
00092     STATE_CONFLICT_COPYING_FILES,
00093     STATE_DELETING_DIRS,
00094     STATE_SETTING_DIR_ATTRIBUTES
00095 };
00096 
00098 class KIO::CopyJobPrivate: public KIO::JobPrivate
00099 {
00100 public:
00101     CopyJobPrivate(const KUrl::List& src, const KUrl& dest,
00102                    CopyJob::CopyMode mode, bool asMethod)
00103         : m_globalDest(dest)
00104         , m_globalDestinationState(DEST_NOT_STATED)
00105         , m_defaultPermissions(false)
00106         , m_bURLDirty(false)
00107         , m_mode(mode)
00108         , m_asMethod(asMethod)
00109         , destinationState(DEST_NOT_STATED)
00110         , state(STATE_STATING)
00111         , m_freeSpace(-1)
00112         , m_totalSize(0)
00113         , m_processedSize(0)
00114         , m_fileProcessedSize(0)
00115         , m_processedFiles(0)
00116         , m_processedDirs(0)
00117         , m_srcList(src)
00118         , m_currentStatSrc(m_srcList.constBegin())
00119         , m_bCurrentOperationIsLink(false)
00120         , m_bSingleFileCopy(false)
00121         , m_bOnlyRenames(mode==CopyJob::Move)
00122         , m_dest(dest)
00123         , m_bAutoRenameFiles(false)
00124         , m_bAutoRenameDirs(false)
00125         , m_bAutoSkipFiles( false )
00126         , m_bAutoSkipDirs( false )
00127         , m_bOverwriteAllFiles( false )
00128         , m_bOverwriteAllDirs( false )
00129         , m_conflictError(0)
00130         , m_reportTimer(0)
00131     {
00132     }
00133 
00134     // This is the dest URL that was initially given to CopyJob
00135     // It is copied into m_dest, which can be changed for a given src URL
00136     // (when using the RENAME dialog in slotResult),
00137     // and which will be reset for the next src URL.
00138     KUrl m_globalDest;
00139     // The state info about that global dest
00140     DestinationState m_globalDestinationState;
00141     // See setDefaultPermissions
00142     bool m_defaultPermissions;
00143     // Whether URLs changed (and need to be emitted by the next slotReport call)
00144     bool m_bURLDirty;
00145     // Used after copying all the files into the dirs, to set mtime (TODO: and permissions?)
00146     // after the copy is done
00147     QLinkedList<CopyInfo> m_directoriesCopied;
00148     QLinkedList<CopyInfo>::const_iterator m_directoriesCopiedIterator;
00149 
00150     CopyJob::CopyMode m_mode;
00151     bool m_asMethod;
00152     DestinationState destinationState;
00153     CopyJobState state;
00154 
00155     KIO::filesize_t m_freeSpace;
00156 
00157     KIO::filesize_t m_totalSize;
00158     KIO::filesize_t m_processedSize;
00159     KIO::filesize_t m_fileProcessedSize;
00160     int m_processedFiles;
00161     int m_processedDirs;
00162     QList<CopyInfo> files;
00163     QList<CopyInfo> dirs;
00164     KUrl::List dirsToRemove;
00165     KUrl::List m_srcList;
00166     KUrl::List m_successSrcList; // Entries in m_srcList that have successfully been moved
00167     KUrl::List::const_iterator m_currentStatSrc;
00168     bool m_bCurrentSrcIsDir;
00169     bool m_bCurrentOperationIsLink;
00170     bool m_bSingleFileCopy;
00171     bool m_bOnlyRenames;
00172     KUrl m_dest;
00173     KUrl m_currentDest; // set during listing, used by slotEntries
00174     //
00175     QStringList m_skipList;
00176     QSet<QString> m_overwriteList;
00177     bool m_bAutoRenameFiles;
00178     bool m_bAutoRenameDirs;
00179     bool m_bAutoSkipFiles;
00180     bool m_bAutoSkipDirs;
00181     bool m_bOverwriteAllFiles;
00182     bool m_bOverwriteAllDirs;
00183     int m_conflictError;
00184 
00185     QTimer *m_reportTimer;
00186 
00187     // The current src url being stat'ed or copied
00188     // During the stat phase, this is initially equal to *m_currentStatSrc but it can be resolved to a local file equivalent (#188903).
00189     KUrl m_currentSrcURL;
00190     KUrl m_currentDestURL;
00191 
00192     QSet<QString> m_parentDirs;
00193 
00194     void statCurrentSrc();
00195     void statNextSrc();
00196 
00197     // Those aren't slots but submethods for slotResult.
00198     void slotResultStating( KJob * job );
00199     void startListing( const KUrl & src );
00200     void slotResultCreatingDirs( KJob * job );
00201     void slotResultConflictCreatingDirs( KJob * job );
00202     void createNextDir();
00203     void slotResultCopyingFiles( KJob * job );
00204     void slotResultConflictCopyingFiles( KJob * job );
00205 //     KIO::Job* linkNextFile( const KUrl& uSource, const KUrl& uDest, bool overwrite );
00206     KIO::Job* linkNextFile( const KUrl& uSource, const KUrl& uDest, JobFlags flags );
00207     void copyNextFile();
00208     void slotResultDeletingDirs( KJob * job );
00209     void deleteNextDir();
00210     void sourceStated(const UDSEntry& entry, const KUrl& sourceUrl);
00211     void skip(const KUrl & sourceURL, bool isDir);
00212     void slotResultRenaming( KJob * job );
00213     void slotResultSettingDirAttributes( KJob * job );
00214     void setNextDirAttribute();
00215 
00216     void startRenameJob(const KUrl &slave_url);
00217     bool shouldOverwriteDir( const QString& path ) const;
00218     bool shouldOverwriteFile( const QString& path ) const;
00219     bool shouldSkip( const QString& path ) const;
00220     void skipSrc(bool isDir);
00221 
00222     void slotStart();
00223     void slotEntries( KIO::Job*, const KIO::UDSEntryList& list );
00224     void addCopyInfoFromUDSEntry(const UDSEntry& entry, const KUrl& srcUrl, bool srcIsDir, const KUrl& currentDest);
00228     void slotProcessedSize( KJob*, qulonglong data_size );
00233     void slotTotalSize( KJob*, qulonglong size );
00234 
00235     void slotReport();
00236 
00237     Q_DECLARE_PUBLIC(CopyJob)
00238 
00239     static inline CopyJob *newJob(const KUrl::List& src, const KUrl& dest,
00240                                   CopyJob::CopyMode mode, bool asMethod, JobFlags flags)
00241     {
00242         CopyJob *job = new CopyJob(*new CopyJobPrivate(src,dest,mode,asMethod));
00243         job->setUiDelegate(new JobUiDelegate);
00244         if (!(flags & HideProgressInfo))
00245             KIO::getJobTracker()->registerJob(job);
00246         if (flags & KIO::Overwrite) {
00247             job->d_func()->m_bOverwriteAllDirs = true;
00248             job->d_func()->m_bOverwriteAllFiles = true;
00249         }
00250         return job;
00251     }
00252 };
00253 
00254 CopyJob::CopyJob(CopyJobPrivate &dd)
00255     : Job(dd)
00256 {
00257     setProperty("destUrl", d_func()->m_dest.url());
00258     QTimer::singleShot(0, this, SLOT(slotStart()));
00259 }
00260 
00261 CopyJob::~CopyJob()
00262 {
00263 }
00264 
00265 KUrl::List CopyJob::srcUrls() const
00266 {
00267     return d_func()->m_srcList;
00268 }
00269 
00270 KUrl CopyJob::destUrl() const
00271 {
00272     return d_func()->m_dest;
00273 }
00274 
00275 void CopyJobPrivate::slotStart()
00276 {
00277     Q_Q(CopyJob);
00283     m_reportTimer = new QTimer(q);
00284 
00285     q->connect(m_reportTimer,SIGNAL(timeout()),q,SLOT(slotReport()));
00286     m_reportTimer->start(REPORT_TIMEOUT);
00287 
00288     // Stat the dest
00289     KIO::Job * job = KIO::stat( m_dest, StatJob::DestinationSide, 2, KIO::HideProgressInfo );
00290     //kDebug(7007) << "CopyJob:stating the dest " << m_dest;
00291     q->addSubjob(job);
00292 }
00293 
00294 // For unit test purposes
00295 KIO_EXPORT bool kio_resolve_local_urls = true;
00296 
00297 void CopyJobPrivate::slotResultStating( KJob *job )
00298 {
00299     Q_Q(CopyJob);
00300     //kDebug(7007);
00301     // Was there an error while stating the src ?
00302     if (job->error() && destinationState != DEST_NOT_STATED )
00303     {
00304         const KUrl srcurl = static_cast<SimpleJob*>(job)->url();
00305         if ( !srcurl.isLocalFile() )
00306         {
00307             // Probably : src doesn't exist. Well, over some protocols (e.g. FTP)
00308             // this info isn't really reliable (thanks to MS FTP servers).
00309             // We'll assume a file, and try to download anyway.
00310             kDebug(7007) << "Error while stating source. Activating hack";
00311             q->removeSubjob( job );
00312             assert ( !q->hasSubjobs() ); // We should have only one job at a time ...
00313             struct CopyInfo info;
00314             info.permissions = (mode_t) -1;
00315             info.mtime = (time_t) -1;
00316             info.ctime = (time_t) -1;
00317             info.size = (KIO::filesize_t)-1;
00318             info.uSource = srcurl;
00319             info.uDest = m_dest;
00320             // Append filename or dirname to destination URL, if allowed
00321             if ( destinationState == DEST_IS_DIR && !m_asMethod )
00322                 info.uDest.addPath( srcurl.fileName() );
00323 
00324             files.append( info );
00325             statNextSrc();
00326             return;
00327         }
00328         // Local file. If stat fails, the file definitely doesn't exist.
00329         // yes, q->Job::, because we don't want to call our override
00330         q->Job::slotResult( job ); // will set the error and emit result(this)
00331         return;
00332     }
00333 
00334     // Keep copy of the stat result
00335     const UDSEntry entry = static_cast<StatJob*>(job)->statResult();
00336 
00337     if ( destinationState == DEST_NOT_STATED ) {
00338         if ( m_dest.isLocalFile() ) { //works for dirs as well
00339             QString path = m_dest.toLocalFile();
00340             if (m_asMethod) {
00341                 // In copy-as mode, we want to check the directory to which we're
00342                 // copying. The target file or directory does not exist yet, which
00343                 // might confuse KDiskFreeSpaceInfo.
00344                 path = QFileInfo(path).absolutePath();
00345             }
00346             KFileSystemType::Type fsType = KFileSystemType::fileSystemType( path );
00347             if ( fsType != KFileSystemType::Nfs && fsType != KFileSystemType::Smb ) {
00348                 m_freeSpace = KDiskFreeSpaceInfo::freeSpaceInfo( path ).available();
00349             }
00350             //TODO actually preliminary check is even more valuable for slow NFS/SMB mounts,
00351             //but we need to find a way to report connection errors to user
00352         }
00353 
00354         const bool isGlobalDest = m_dest == m_globalDest;
00355         const bool isDir = entry.isDir();
00356         // we were stating the dest
00357         if (job->error()) {
00358             destinationState = DEST_DOESNT_EXIST;
00359             //kDebug(7007) << "dest does not exist";
00360         } else {
00361             // Treat symlinks to dirs as dirs here, so no test on isLink
00362             destinationState = isDir ? DEST_IS_DIR : DEST_IS_FILE;
00363             //kDebug(7007) << "dest is dir:" << isDir;
00364 
00365             const QString sLocalPath = entry.stringValue( KIO::UDSEntry::UDS_LOCAL_PATH );
00366             if ( !sLocalPath.isEmpty() && kio_resolve_local_urls && destinationState != DEST_DOESNT_EXIST ) {
00367                 m_dest = KUrl();
00368                 m_dest.setPath(sLocalPath);
00369                 if ( isGlobalDest )
00370                     m_globalDest = m_dest;
00371             }
00372         }
00373         if ( isGlobalDest )
00374             m_globalDestinationState = destinationState;
00375 
00376         q->removeSubjob( job );
00377         assert ( !q->hasSubjobs() );
00378 
00379         // After knowing what the dest is, we can start stat'ing the first src.
00380         statCurrentSrc();
00381     } else {
00382         sourceStated(entry, static_cast<SimpleJob*>(job)->url());
00383         q->removeSubjob( job );
00384     }
00385 }
00386 
00387 void CopyJobPrivate::sourceStated(const UDSEntry& entry, const KUrl& sourceUrl)
00388 {
00389     const QString sLocalPath = entry.stringValue( KIO::UDSEntry::UDS_LOCAL_PATH );
00390     const bool isDir = entry.isDir();
00391 
00392     // We were stating the current source URL
00393     // Is it a file or a dir ?
00394 
00395     // There 6 cases, and all end up calling addCopyInfoFromUDSEntry first :
00396     // 1 - src is a dir, destination is a directory,
00397     // slotEntries will append the source-dir-name to the destination
00398     // 2 - src is a dir, destination is a file -- will offer to overwrite, later on.
00399     // 3 - src is a dir, destination doesn't exist, then it's the destination dirname,
00400     // so slotEntries will use it as destination.
00401 
00402     // 4 - src is a file, destination is a directory,
00403     // slotEntries will append the filename to the destination.
00404     // 5 - src is a file, destination is a file, m_dest is the exact destination name
00405     // 6 - src is a file, destination doesn't exist, m_dest is the exact destination name
00406 
00407     KUrl srcurl;
00408     if (!sLocalPath.isEmpty() && destinationState != DEST_DOESNT_EXIST) {
00409         kDebug() << "Using sLocalPath. destinationState=" << destinationState;
00410         // Prefer the local path -- but only if we were able to stat() the dest.
00411         // Otherwise, renaming a desktop:/ url would copy from src=file to dest=desktop (#218719)
00412         srcurl.setPath(sLocalPath);
00413     } else {
00414         srcurl = sourceUrl;
00415     }
00416     addCopyInfoFromUDSEntry(entry, srcurl, false, m_dest);
00417 
00418     m_currentDest = m_dest;
00419     m_bCurrentSrcIsDir = false;
00420 
00421     if ( isDir
00422          // treat symlinks as files (no recursion)
00423          && !entry.isLink()
00424          && m_mode != CopyJob::Link ) // No recursion in Link mode either.
00425     {
00426         //kDebug(7007) << "Source is a directory";
00427 
00428         if (srcurl.isLocalFile()) {
00429             const QString parentDir = srcurl.toLocalFile(KUrl::RemoveTrailingSlash);
00430             m_parentDirs.insert(parentDir);
00431         }
00432 
00433         m_bCurrentSrcIsDir = true; // used by slotEntries
00434         if ( destinationState == DEST_IS_DIR ) // (case 1)
00435         {
00436             if ( !m_asMethod )
00437             {
00438                 // Use <desturl>/<directory_copied> as destination, from now on
00439                 QString directory = srcurl.fileName();
00440                 const QString sName = entry.stringValue( KIO::UDSEntry::UDS_NAME );
00441                 KProtocolInfo::FileNameUsedForCopying fnu = KProtocolManager::fileNameUsedForCopying(srcurl);
00442                 if (fnu == KProtocolInfo::Name) {
00443                     if (!sName.isEmpty())
00444                         directory = sName;
00445                 } else if (fnu == KProtocolInfo::DisplayName) {
00446                     const QString dispName = entry.stringValue( KIO::UDSEntry::UDS_DISPLAY_NAME );
00447                     if (!dispName.isEmpty())
00448                         directory = dispName;
00449                     else if (!sName.isEmpty())
00450                         directory = sName;
00451                 }
00452                 m_currentDest.addPath( directory );
00453             }
00454         }
00455         else // (case 3)
00456         {
00457             // otherwise dest is new name for toplevel dir
00458             // so the destination exists, in fact, from now on.
00459             // (This even works with other src urls in the list, since the
00460             //  dir has effectively been created)
00461             destinationState = DEST_IS_DIR;
00462             if ( m_dest == m_globalDest )
00463                 m_globalDestinationState = destinationState;
00464         }
00465 
00466         startListing( srcurl );
00467     }
00468     else
00469     {
00470         //kDebug(7007) << "Source is a file (or a symlink), or we are linking -> no recursive listing";
00471 
00472         if (srcurl.isLocalFile()) {
00473             const QString parentDir = srcurl.directory(KUrl::ObeyTrailingSlash);
00474             m_parentDirs.insert(parentDir);
00475         }
00476 
00477         statNextSrc();
00478     }
00479 }
00480 
00481 bool CopyJob::doSuspend()
00482 {
00483     Q_D(CopyJob);
00484     d->slotReport();
00485     return Job::doSuspend();
00486 }
00487 
00488 void CopyJobPrivate::slotReport()
00489 {
00490     Q_Q(CopyJob);
00491     if ( q->isSuspended() )
00492         return;
00493     // If showProgressInfo was set, progressId() is > 0.
00494     switch (state) {
00495         case STATE_RENAMING:
00496             q->setTotalAmount(KJob::Files, m_srcList.count());
00497             // fall-through intended
00498         case STATE_COPYING_FILES:
00499             q->setProcessedAmount( KJob::Files, m_processedFiles );
00500             if (m_bURLDirty)
00501             {
00502                 // Only emit urls when they changed. This saves time, and fixes #66281
00503                 m_bURLDirty = false;
00504                 if (m_mode==CopyJob::Move)
00505                 {
00506                     emitMoving(q, m_currentSrcURL, m_currentDestURL);
00507                     emit q->moving( q, m_currentSrcURL, m_currentDestURL);
00508                 }
00509                 else if (m_mode==CopyJob::Link)
00510                 {
00511                     emitCopying( q, m_currentSrcURL, m_currentDestURL ); // we don't have a delegate->linking
00512                     emit q->linking( q, m_currentSrcURL.path(), m_currentDestURL );
00513                 }
00514                 else
00515                 {
00516                     emitCopying( q, m_currentSrcURL, m_currentDestURL );
00517                     emit q->copying( q, m_currentSrcURL, m_currentDestURL );
00518                 }
00519             }
00520             break;
00521 
00522         case STATE_CREATING_DIRS:
00523             q->setProcessedAmount( KJob::Directories, m_processedDirs );
00524             if (m_bURLDirty)
00525             {
00526                 m_bURLDirty = false;
00527                 emit q->creatingDir( q, m_currentDestURL );
00528                 emitCreatingDir( q, m_currentDestURL );
00529             }
00530             break;
00531 
00532         case STATE_STATING:
00533         case STATE_LISTING:
00534             if (m_bURLDirty)
00535             {
00536                 m_bURLDirty = false;
00537                 if (m_mode==CopyJob::Move)
00538                 {
00539                     emitMoving( q, m_currentSrcURL, m_currentDestURL );
00540                 }
00541                 else
00542                 {
00543                     emitCopying( q, m_currentSrcURL, m_currentDestURL );
00544                 }
00545             }
00546             q->setTotalAmount(KJob::Bytes, m_totalSize);
00547             q->setTotalAmount(KJob::Files, files.count());
00548             q->setTotalAmount(KJob::Directories, dirs.count());
00549             break;
00550 
00551         default:
00552             break;
00553     }
00554 }
00555 
00556 void CopyJobPrivate::slotEntries(KIO::Job* job, const UDSEntryList& list)
00557 {
00558     //Q_Q(CopyJob);
00559     UDSEntryList::ConstIterator it = list.constBegin();
00560     UDSEntryList::ConstIterator end = list.constEnd();
00561     for (; it != end; ++it) {
00562         const UDSEntry& entry = *it;
00563         addCopyInfoFromUDSEntry(entry, static_cast<SimpleJob *>(job)->url(), m_bCurrentSrcIsDir, m_currentDest);
00564     }
00565 }
00566 
00567 void CopyJobPrivate::addCopyInfoFromUDSEntry(const UDSEntry& entry, const KUrl& srcUrl, bool srcIsDir, const KUrl& currentDest)
00568 {
00569     struct CopyInfo info;
00570     info.permissions = entry.numberValue(KIO::UDSEntry::UDS_ACCESS, -1);
00571     info.mtime = (time_t) entry.numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
00572     info.ctime = (time_t) entry.numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
00573     info.size = (KIO::filesize_t) entry.numberValue(KIO::UDSEntry::UDS_SIZE, -1);
00574     if (info.size != (KIO::filesize_t) -1)
00575         m_totalSize += info.size;
00576 
00577     // recursive listing, displayName can be a/b/c/d
00578     const QString fileName = entry.stringValue(KIO::UDSEntry::UDS_NAME);
00579     const QString urlStr = entry.stringValue(KIO::UDSEntry::UDS_URL);
00580     KUrl url;
00581     if (!urlStr.isEmpty())
00582         url = urlStr;
00583     QString localPath = entry.stringValue(KIO::UDSEntry::UDS_LOCAL_PATH);
00584     const bool isDir = entry.isDir();
00585     info.linkDest = entry.stringValue(KIO::UDSEntry::UDS_LINK_DEST);
00586 
00587     if (fileName != QLatin1String("..") && fileName != QLatin1String(".")) {
00588         const bool hasCustomURL = !url.isEmpty() || !localPath.isEmpty();
00589         if (!hasCustomURL) {
00590             // Make URL from displayName
00591             url = srcUrl;
00592             if (srcIsDir) { // Only if src is a directory. Otherwise uSource is fine as is
00593                 //kDebug(7007) << "adding path" << displayName;
00594                 url.addPath(fileName);
00595             }
00596         }
00597         //kDebug(7007) << "displayName=" << displayName << "url=" << url;
00598         if (!localPath.isEmpty() && kio_resolve_local_urls && destinationState != DEST_DOESNT_EXIST) {
00599             url = KUrl(localPath);
00600         }
00601 
00602         info.uSource = url;
00603         info.uDest = currentDest;
00604         //kDebug(7007) << "uSource=" << info.uSource << "uDest(1)=" << info.uDest;
00605         // Append filename or dirname to destination URL, if allowed
00606         if (destinationState == DEST_IS_DIR &&
00607              // "copy/move as <foo>" means 'foo' is the dest for the base srcurl
00608              // (passed here during stating) but not its children (during listing)
00609              (! (m_asMethod && state == STATE_STATING)))
00610         {
00611             QString destFileName;
00612         KProtocolInfo::FileNameUsedForCopying fnu = KProtocolManager::fileNameUsedForCopying(url);
00613             if (hasCustomURL &&
00614                  fnu == KProtocolInfo::FromUrl) {
00615                 //destFileName = url.fileName(); // Doesn't work for recursive listing
00616                 // Count the number of prefixes used by the recursive listjob
00617                 int numberOfSlashes = fileName.count('/'); // don't make this a find()!
00618                 QString path = url.path();
00619                 int pos = 0;
00620                 for (int n = 0; n < numberOfSlashes + 1; ++n) {
00621                     pos = path.lastIndexOf('/', pos - 1);
00622                     if (pos == -1) { // error
00623                         kWarning(7007) << "kioslave bug: not enough slashes in UDS_URL" << path << "- looking for" << numberOfSlashes << "slashes";
00624                         break;
00625                     }
00626                 }
00627                 if (pos >= 0) {
00628                     destFileName = path.mid(pos + 1);
00629                 }
00630 
00631             } else if ( fnu == KProtocolInfo::Name ) { // destination filename taken from UDS_NAME
00632                 destFileName = fileName;
00633             } else { // from display name (with fallback to name)
00634                 const QString displayName = entry.stringValue(KIO::UDSEntry::UDS_DISPLAY_NAME);
00635                 destFileName = displayName.isEmpty() ? fileName : displayName;
00636             }
00637 
00638             // Here we _really_ have to add some filename to the dest.
00639             // Otherwise, we end up with e.g. dest=..../Desktop/ itself.
00640             // (This can happen when dropping a link to a webpage with no path)
00641             if (destFileName.isEmpty()) {
00642                 destFileName = KIO::encodeFileName(info.uSource.prettyUrl());
00643             }
00644 
00645             //kDebug(7007) << " adding destFileName=" << destFileName;
00646             info.uDest.addPath(destFileName);
00647         }
00648         //kDebug(7007) << " uDest(2)=" << info.uDest;
00649         //kDebug(7007) << " " << info.uSource << "->" << info.uDest;
00650         if (info.linkDest.isEmpty() && isDir && m_mode != CopyJob::Link) { // Dir
00651             dirs.append(info); // Directories
00652             if (m_mode == CopyJob::Move) {
00653                 dirsToRemove.append(info.uSource);
00654             }
00655         } else {
00656             files.append(info); // Files and any symlinks
00657         }
00658     }
00659 }
00660 
00661 void CopyJobPrivate::skipSrc(bool isDir)
00662 {
00663     m_dest = m_globalDest;
00664     destinationState = m_globalDestinationState;
00665     skip(*m_currentStatSrc, isDir);
00666     ++m_currentStatSrc;
00667     statCurrentSrc();
00668 }
00669 
00670 void CopyJobPrivate::statNextSrc()
00671 {
00672     /* Revert to the global destination, the one that applies to all source urls.
00673      * Imagine you copy the items a b and c into /d, but /d/b exists so the user uses "Rename" to put it in /foo/b instead.
00674      * d->m_dest is /foo/b for b, but we have to revert to /d for item c and following.
00675      */
00676     m_dest = m_globalDest;
00677     destinationState = m_globalDestinationState;
00678     ++m_currentStatSrc;
00679     statCurrentSrc();
00680 }
00681 
00682 void CopyJobPrivate::statCurrentSrc()
00683 {
00684     Q_Q(CopyJob);
00685     if (m_currentStatSrc != m_srcList.constEnd()) {
00686         m_currentSrcURL = (*m_currentStatSrc);
00687         m_bURLDirty = true;
00688         if (m_mode == CopyJob::Link) {
00689             // Skip the "stating the source" stage, we don't need it for linking
00690             m_currentDest = m_dest;
00691             struct CopyInfo info;
00692             info.permissions = -1;
00693             info.mtime = (time_t) -1;
00694             info.ctime = (time_t) -1;
00695             info.size = (KIO::filesize_t)-1;
00696             info.uSource = m_currentSrcURL;
00697             info.uDest = m_currentDest;
00698             // Append filename or dirname to destination URL, if allowed
00699             if (destinationState == DEST_IS_DIR && !m_asMethod) {
00700                 if (
00701                     (m_currentSrcURL.protocol() == info.uDest.protocol()) &&
00702                     (m_currentSrcURL.host() == info.uDest.host()) &&
00703                     (m_currentSrcURL.port() == info.uDest.port()) &&
00704                     (m_currentSrcURL.user() == info.uDest.user()) &&
00705                     (m_currentSrcURL.pass() == info.uDest.pass()) ) {
00706                     // This is the case of creating a real symlink
00707                     info.uDest.addPath( m_currentSrcURL.fileName() );
00708                 } else {
00709                     // Different protocols, we'll create a .desktop file
00710                     // We have to change the extension anyway, so while we're at it,
00711                     // name the file like the URL
00712                     info.uDest.addPath(KIO::encodeFileName(m_currentSrcURL.prettyUrl()) + ".desktop");
00713                 }
00714             }
00715             files.append( info ); // Files and any symlinks
00716             statNextSrc(); // we could use a loop instead of a recursive call :)
00717             return;
00718         }
00719 
00720         // Let's see if we can skip stat'ing, for the case where a directory view has the info already
00721         const KFileItem cachedItem = KDirLister::cachedItemForUrl(m_currentSrcURL);
00722         KIO::UDSEntry entry;
00723         if (!cachedItem.isNull()) {
00724             entry = cachedItem.entry();
00725             if (destinationState != DEST_DOESNT_EXIST) { // only resolve src if we could resolve dest (#218719)
00726                 bool dummyIsLocal;
00727                 m_currentSrcURL = cachedItem.mostLocalUrl(dummyIsLocal); // #183585
00728             }
00729         }
00730 
00731         if (m_mode == CopyJob::Move && (
00732                 // Don't go renaming right away if we need a stat() to find out the destination filename
00733                 KProtocolManager::fileNameUsedForCopying(m_currentSrcURL) == KProtocolInfo::FromUrl ||
00734                 destinationState != DEST_IS_DIR || m_asMethod)
00735             ) {
00736            // If moving, before going for the full stat+[list+]copy+del thing, try to rename
00737            // The logic is pretty similar to FileCopyJobPrivate::slotStart()
00738            if ( (m_currentSrcURL.protocol() == m_dest.protocol()) &&
00739               (m_currentSrcURL.host() == m_dest.host()) &&
00740               (m_currentSrcURL.port() == m_dest.port()) &&
00741               (m_currentSrcURL.user() == m_dest.user()) &&
00742               (m_currentSrcURL.pass() == m_dest.pass()) )
00743            {
00744               startRenameJob( m_currentSrcURL );
00745               return;
00746            }
00747            else if ( m_currentSrcURL.isLocalFile() && KProtocolManager::canRenameFromFile( m_dest ) )
00748            {
00749               startRenameJob( m_dest );
00750               return;
00751            }
00752            else if ( m_dest.isLocalFile() && KProtocolManager::canRenameToFile( m_currentSrcURL ) )
00753            {
00754               startRenameJob( m_currentSrcURL );
00755               return;
00756            }
00757         }
00758 
00759         // if the file system doesn't support deleting, we do not even stat
00760         if (m_mode == CopyJob::Move && !KProtocolManager::supportsDeleting(m_currentSrcURL)) {
00761             QPointer<CopyJob> that = q;
00762             emit q->warning( q, buildErrorString(ERR_CANNOT_DELETE, m_currentSrcURL.prettyUrl()) );
00763             if (that)
00764                 statNextSrc(); // we could use a loop instead of a recursive call :)
00765             return;
00766         }
00767 
00768         m_bOnlyRenames = false;
00769 
00770         // Testing for entry.count()>0 here is not good enough; KFileItem inserts
00771         // entries for UDS_USER and UDS_GROUP even on initially empty UDSEntries (#192185)
00772         if (entry.contains(KIO::UDSEntry::UDS_NAME)) {
00773             kDebug(7007) << "fast path! found info about" << m_currentSrcURL << "in KDirLister";
00774             sourceStated(entry, m_currentSrcURL);
00775             return;
00776         }
00777 
00778         // Stat the next src url
00779         Job * job = KIO::stat( m_currentSrcURL, StatJob::SourceSide, 2, KIO::HideProgressInfo );
00780         //kDebug(7007) << "KIO::stat on" << m_currentSrcURL;
00781         state = STATE_STATING;
00782         q->addSubjob(job);
00783         m_currentDestURL = m_dest;
00784         m_bURLDirty = true;
00785     }
00786     else
00787     {
00788         // Finished the stat'ing phase
00789         // First make sure that the totals were correctly emitted
00790         state = STATE_STATING;
00791         m_bURLDirty = true;
00792         slotReport();
00793 
00794         kDebug(7007)<<"Stating finished. To copy:"<<m_totalSize<<", available:"<<m_freeSpace;
00795     //TODO warn user beforehand if space is not enough
00796 
00797         if (!dirs.isEmpty())
00798            emit q->aboutToCreate( q, dirs );
00799         if (!files.isEmpty())
00800            emit q->aboutToCreate( q, files );
00801         // Check if we are copying a single file
00802         m_bSingleFileCopy = ( files.count() == 1 && dirs.isEmpty() );
00803         // Then start copying things
00804         state = STATE_CREATING_DIRS;
00805         createNextDir();
00806     }
00807 }
00808 
00809 void CopyJobPrivate::startRenameJob( const KUrl& slave_url )
00810 {
00811     Q_Q(CopyJob);
00812 
00813     // Silence KDirWatch notifications, otherwise performance is horrible
00814     if (m_currentSrcURL.isLocalFile()) {
00815         const QString parentDir = m_currentSrcURL.directory(KUrl::ObeyTrailingSlash);
00816         if (!m_parentDirs.contains(parentDir)) {
00817             KDirWatch::self()->stopDirScan(parentDir);
00818             m_parentDirs.insert(parentDir);
00819         }
00820     }
00821 
00822     KUrl dest = m_dest;
00823     // Append filename or dirname to destination URL, if allowed
00824     if ( destinationState == DEST_IS_DIR && !m_asMethod )
00825         dest.addPath( m_currentSrcURL.fileName() );
00826     m_currentDestURL = dest;
00827     kDebug(7007) << m_currentSrcURL << "->" << dest << "trying direct rename first";
00828     state = STATE_RENAMING;
00829 
00830     struct CopyInfo info;
00831     info.permissions = -1;
00832     info.mtime = (time_t) -1;
00833     info.ctime = (time_t) -1;
00834     info.size = (KIO::filesize_t)-1;
00835     info.uSource = m_currentSrcURL;
00836     info.uDest = dest;
00837     QList<CopyInfo> files;
00838     files.append(info);
00839     emit q->aboutToCreate( q, files );
00840 
00841     KIO_ARGS << m_currentSrcURL << dest << (qint8) false /*no overwrite*/;
00842     SimpleJob * newJob = SimpleJobPrivate::newJobNoUi(slave_url, CMD_RENAME, packedArgs);
00843     Scheduler::setJobPriority(newJob, 1);
00844     q->addSubjob( newJob );
00845     if ( m_currentSrcURL.directory() != dest.directory() ) // For the user, moving isn't renaming. Only renaming is.
00846         m_bOnlyRenames = false;
00847 }
00848 
00849 void CopyJobPrivate::startListing( const KUrl & src )
00850 {
00851     Q_Q(CopyJob);
00852     state = STATE_LISTING;
00853     m_bURLDirty = true;
00854     ListJob * newjob = listRecursive(src, KIO::HideProgressInfo);
00855     newjob->setUnrestricted(true);
00856     q->connect(newjob, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)),
00857                SLOT(slotEntries(KIO::Job*,KIO::UDSEntryList)));
00858     q->addSubjob( newjob );
00859 }
00860 
00861 void CopyJobPrivate::skip(const KUrl & sourceUrl, bool isDir)
00862 {
00863     KUrl dir = sourceUrl;
00864     if (!isDir) {
00865         // Skipping a file: make sure not to delete the parent dir (#208418)
00866         dir.setPath(dir.directory());
00867     }
00868     while (dirsToRemove.removeAll(dir) > 0) {
00869         // Do not rely on rmdir() on the parent directories aborting.
00870         // Exclude the parent dirs explicitly.
00871         dir.setPath(dir.directory());
00872     }
00873 }
00874 
00875 bool CopyJobPrivate::shouldOverwriteDir( const QString& path ) const
00876 {
00877     if ( m_bOverwriteAllDirs )
00878         return true;
00879     return m_overwriteList.contains(path);
00880 }
00881 
00882 bool CopyJobPrivate::shouldOverwriteFile( const QString& path ) const
00883 {
00884     if ( m_bOverwriteAllFiles )
00885         return true;
00886     return m_overwriteList.contains(path);
00887 }
00888 
00889 bool CopyJobPrivate::shouldSkip( const QString& path ) const
00890 {
00891     Q_FOREACH(const QString& skipPath, m_skipList) {
00892         if ( path.startsWith(skipPath) )
00893             return true;
00894     }
00895     return false;
00896 }
00897 
00898 void CopyJobPrivate::slotResultCreatingDirs( KJob * job )
00899 {
00900     Q_Q(CopyJob);
00901     // The dir we are trying to create:
00902     QList<CopyInfo>::Iterator it = dirs.begin();
00903     // Was there an error creating a dir ?
00904     if ( job->error() )
00905     {
00906         m_conflictError = job->error();
00907         if ( (m_conflictError == ERR_DIR_ALREADY_EXIST)
00908              || (m_conflictError == ERR_FILE_ALREADY_EXIST) ) // can't happen?
00909         {
00910             KUrl oldURL = ((SimpleJob*)job)->url();
00911             // Should we skip automatically ?
00912             if ( m_bAutoSkipDirs ) {
00913                 // We don't want to copy files in this directory, so we put it on the skip list
00914                 m_skipList.append( oldURL.path( KUrl::AddTrailingSlash ) );
00915                 skip(oldURL, true);
00916                 dirs.erase( it ); // Move on to next dir
00917             } else {
00918                 // Did the user choose to overwrite already?
00919                 const QString destDir = (*it).uDest.path();
00920                 if ( shouldOverwriteDir( destDir ) ) { // overwrite => just skip
00921                     emit q->copyingDone( q, (*it).uSource, (*it).uDest, (*it).mtime, true /* directory */, false /* renamed */ );
00922                     dirs.erase( it ); // Move on to next dir
00923                 } else {
00924                     if (m_bAutoRenameDirs) {
00925                         QString oldPath = (*it).uDest.path(KUrl::AddTrailingSlash);
00926 
00927                         KUrl destDirectory((*it).uDest);
00928                         destDirectory.setPath(destDirectory.directory());
00929                         QString newName = KIO::RenameDialog::suggestName(destDirectory, (*it).uDest.fileName());
00930 
00931                         KUrl newUrl((*it).uDest);
00932                         newUrl.setFileName(newName);
00933 
00934                         emit q->renamed(q, (*it).uDest, newUrl); // for e.g. kpropsdlg
00935 
00936                         // Change the current one and strip the trailing '/'
00937                         (*it).uDest.setPath(newUrl.path(KUrl::RemoveTrailingSlash));
00938 
00939                         QString newPath = newUrl.path(KUrl::AddTrailingSlash); // With trailing slash
00940                         QList<CopyInfo>::Iterator renamedirit = it;
00941                         ++renamedirit;
00942                         // Change the name of subdirectories inside the directory
00943                         for(; renamedirit != dirs.end() ; ++renamedirit) {
00944                             QString path = (*renamedirit).uDest.path();
00945                             if (path.startsWith(oldPath)) {
00946                                 QString n = path;
00947                                 n.replace(0, oldPath.length(), newPath);
00948                                 kDebug(7007) << "dirs list:" << (*renamedirit).uSource.path()
00949                                               << "was going to be" << path
00950                                               << ", changed into" << n;
00951                                 (*renamedirit).uDest.setPath(n);
00952                             }
00953                         }
00954                         // Change filenames inside the directory
00955                         QList<CopyInfo>::Iterator renamefileit = files.begin();
00956                         for(; renamefileit != files.end() ; ++renamefileit) {
00957                             QString path = (*renamefileit).uDest.path();
00958                             if (path.startsWith(oldPath)) {
00959                                 QString n = path;
00960                                 n.replace(0, oldPath.length(), newPath);
00961                                 kDebug(7007) << "files list:" << (*renamefileit).uSource.path()
00962                                               << "was going to be" << path
00963                                               << ", changed into" << n;
00964                                 (*renamefileit).uDest.setPath(n);
00965                             }
00966                         }
00967                         if (!dirs.isEmpty()) {
00968                             emit q->aboutToCreate(q, dirs);
00969                         }
00970                         if (!files.isEmpty()) {
00971                             emit q->aboutToCreate(q, files);
00972                         }
00973 
00974                     }
00975                     else {
00976                         if (!q->isInteractive()) {
00977                             q->Job::slotResult(job); // will set the error and emit result(this)
00978                             return;
00979                         }
00980 
00981                         assert(((SimpleJob*)job)->url().url() == (*it).uDest.url());
00982                         q->removeSubjob(job);
00983                         assert (!q->hasSubjobs()); // We should have only one job at a time ...
00984 
00985                         // We need to stat the existing dir, to get its last-modification time
00986                         KUrl existingDest((*it).uDest);
00987                         SimpleJob * newJob = KIO::stat(existingDest, StatJob::DestinationSide, 2, KIO::HideProgressInfo);
00988                         Scheduler::setJobPriority(newJob, 1);
00989                         kDebug(7007) << "KIO::stat for resolving conflict on " << existingDest;
00990                         state = STATE_CONFLICT_CREATING_DIRS;
00991                         q->addSubjob(newJob);
00992                         return; // Don't move to next dir yet !
00993                     }
00994                 }
00995             }
00996         }
00997         else
00998         {
00999             // Severe error, abort
01000             q->Job::slotResult( job ); // will set the error and emit result(this)
01001             return;
01002         }
01003     }
01004     else // no error : remove from list, to move on to next dir
01005     {
01006         //this is required for the undo feature
01007         emit q->copyingDone( q, (*it).uSource, (*it).uDest, (*it).mtime, true, false );
01008         m_directoriesCopied.append( *it );
01009         dirs.erase( it );
01010     }
01011 
01012     m_processedDirs++;
01013     //emit processedAmount( this, KJob::Directories, m_processedDirs );
01014     q->removeSubjob( job );
01015     assert( !q->hasSubjobs() ); // We should have only one job at a time ...
01016     createNextDir();
01017 }
01018 
01019 void CopyJobPrivate::slotResultConflictCreatingDirs( KJob * job )
01020 {
01021     Q_Q(CopyJob);
01022     // We come here after a conflict has been detected and we've stated the existing dir
01023 
01024     // The dir we were trying to create:
01025     QList<CopyInfo>::Iterator it = dirs.begin();
01026 
01027     const UDSEntry entry = ((KIO::StatJob*)job)->statResult();
01028 
01029     // Its modification time:
01030     const time_t destmtime = (time_t) entry.numberValue( KIO::UDSEntry::UDS_MODIFICATION_TIME, -1 );
01031     const time_t destctime = (time_t) entry.numberValue( KIO::UDSEntry::UDS_CREATION_TIME, -1 );
01032 
01033     const KIO::filesize_t destsize = entry.numberValue( KIO::UDSEntry::UDS_SIZE );
01034     const QString linkDest = entry.stringValue( KIO::UDSEntry::UDS_LINK_DEST );
01035 
01036     q->removeSubjob( job );
01037     assert ( !q->hasSubjobs() ); // We should have only one job at a time ...
01038 
01039     // Always multi and skip (since there are files after that)
01040     RenameDialog_Mode mode = (RenameDialog_Mode)( M_MULTI | M_SKIP | M_ISDIR );
01041     // Overwrite only if the existing thing is a dir (no chance with a file)
01042     if ( m_conflictError == ERR_DIR_ALREADY_EXIST )
01043     {
01044         if( (*it).uSource == (*it).uDest ||
01045             ((*it).uSource.protocol() == (*it).uDest.protocol() &&
01046               (*it).uSource.path( KUrl::RemoveTrailingSlash ) == linkDest) )
01047           mode = (RenameDialog_Mode)( mode | M_OVERWRITE_ITSELF);
01048         else
01049           mode = (RenameDialog_Mode)( mode | M_OVERWRITE );
01050     }
01051 
01052     QString existingDest = (*it).uDest.path();
01053     QString newPath;
01054     if (m_reportTimer)
01055         m_reportTimer->stop();
01056     RenameDialog_Result r = q->ui()->askFileRename( q, i18n("Folder Already Exists"),
01057                                          (*it).uSource.url(),
01058                                          (*it).uDest.url(),
01059                                          mode, newPath,
01060                                          (*it).size, destsize,
01061                                          (*it).ctime, destctime,
01062                                          (*it).mtime, destmtime );
01063     if (m_reportTimer)
01064         m_reportTimer->start(REPORT_TIMEOUT);
01065     switch ( r ) {
01066         case R_CANCEL:
01067             q->setError( ERR_USER_CANCELED );
01068             q->emitResult();
01069             return;
01070         case R_AUTO_RENAME:
01071             m_bAutoRenameDirs = true;
01072             // fall through
01073         case R_RENAME:
01074         {
01075             QString oldPath = (*it).uDest.path( KUrl::AddTrailingSlash );
01076             KUrl newUrl( (*it).uDest );
01077             newUrl.setPath( newPath );
01078             emit q->renamed( q, (*it).uDest, newUrl ); // for e.g. kpropsdlg
01079 
01080             // Change the current one and strip the trailing '/'
01081             (*it).uDest.setPath( newUrl.path( KUrl::RemoveTrailingSlash ) );
01082             newPath = newUrl.path( KUrl::AddTrailingSlash ); // With trailing slash
01083             QList<CopyInfo>::Iterator renamedirit = it;
01084             ++renamedirit;
01085             // Change the name of subdirectories inside the directory
01086             for( ; renamedirit != dirs.end() ; ++renamedirit )
01087             {
01088                 QString path = (*renamedirit).uDest.path();
01089                 if ( path.startsWith( oldPath ) ) {
01090                     QString n = path;
01091                     n.replace( 0, oldPath.length(), newPath );
01092                     kDebug(7007) << "dirs list:" << (*renamedirit).uSource.path()
01093                                   << "was going to be" << path
01094                                   << ", changed into" << n;
01095                     (*renamedirit).uDest.setPath( n );
01096                 }
01097             }
01098             // Change filenames inside the directory
01099             QList<CopyInfo>::Iterator renamefileit = files.begin();
01100             for( ; renamefileit != files.end() ; ++renamefileit )
01101             {
01102                 QString path = (*renamefileit).uDest.path();
01103                 if ( path.startsWith( oldPath ) ) {
01104                     QString n = path;
01105                     n.replace( 0, oldPath.length(), newPath );
01106                     kDebug(7007) << "files list:" << (*renamefileit).uSource.path()
01107                                   << "was going to be" << path
01108                                   << ", changed into" << n;
01109                     (*renamefileit).uDest.setPath( n );
01110                 }
01111             }
01112             if (!dirs.isEmpty())
01113                 emit q->aboutToCreate( q, dirs );
01114             if (!files.isEmpty())
01115                 emit q->aboutToCreate( q, files );
01116         }
01117         break;
01118         case R_AUTO_SKIP:
01119             m_bAutoSkipDirs = true;
01120             // fall through
01121         case R_SKIP:
01122             m_skipList.append( existingDest );
01123             skip((*it).uSource, true);
01124             // Move on to next dir
01125             dirs.erase( it );
01126             m_processedDirs++;
01127             break;
01128         case R_OVERWRITE:
01129             m_overwriteList.insert( existingDest );
01130             emit q->copyingDone( q, (*it).uSource, (*it).uDest, (*it).mtime, true /* directory */, false /* renamed */ );
01131             // Move on to next dir
01132             dirs.erase( it );
01133             m_processedDirs++;
01134             break;
01135         case R_OVERWRITE_ALL:
01136             m_bOverwriteAllDirs = true;
01137             emit q->copyingDone( q, (*it).uSource, (*it).uDest, (*it).mtime, true /* directory */, false /* renamed */ );
01138             // Move on to next dir
01139             dirs.erase( it );
01140             m_processedDirs++;
01141             break;
01142         default:
01143             assert( 0 );
01144     }
01145     state = STATE_CREATING_DIRS;
01146     //emit processedAmount( this, KJob::Directories, m_processedDirs );
01147     createNextDir();
01148 }
01149 
01150 void CopyJobPrivate::createNextDir()
01151 {
01152     Q_Q(CopyJob);
01153     KUrl udir;
01154     if ( !dirs.isEmpty() )
01155     {
01156         // Take first dir to create out of list
01157         QList<CopyInfo>::Iterator it = dirs.begin();
01158         // Is this URL on the skip list or the overwrite list ?
01159         while( it != dirs.end() && udir.isEmpty() )
01160         {
01161             const QString dir = (*it).uDest.path();
01162             if ( shouldSkip( dir ) ) {
01163                 dirs.erase( it );
01164                 it = dirs.begin();
01165             } else
01166                 udir = (*it).uDest;
01167         }
01168     }
01169     if ( !udir.isEmpty() ) // any dir to create, finally ?
01170     {
01171         // Create the directory - with default permissions so that we can put files into it
01172         // TODO : change permissions once all is finished; but for stuff coming from CDROM it sucks...
01173         KIO::SimpleJob *newjob = KIO::mkdir( udir, -1 );
01174         Scheduler::setJobPriority(newjob, 1);
01175         if (shouldOverwriteFile(udir.path())) { // if we are overwriting an existing file or symlink
01176             newjob->addMetaData("overwrite", "true");
01177         }
01178 
01179         m_currentDestURL = udir;
01180         m_bURLDirty = true;
01181 
01182         q->addSubjob(newjob);
01183         return;
01184     }
01185     else // we have finished creating dirs
01186     {
01187         q->setProcessedAmount( KJob::Directories, m_processedDirs ); // make sure final number appears
01188 
01189         if (m_mode == CopyJob::Move) {
01190             // Now we know which dirs hold the files we're going to delete.
01191             // To speed things up and prevent double-notification, we disable KDirWatch
01192             // on those dirs temporarily (using KDirWatch::self, that's the instanced
01193             // used by e.g. kdirlister).
01194             for ( QSet<QString>::const_iterator it = m_parentDirs.constBegin() ; it != m_parentDirs.constEnd() ; ++it )
01195                 KDirWatch::self()->stopDirScan( *it );
01196         }
01197 
01198         state = STATE_COPYING_FILES;
01199         m_processedFiles++; // Ralf wants it to start at 1, not 0
01200         copyNextFile();
01201     }
01202 }
01203 
01204 void CopyJobPrivate::slotResultCopyingFiles( KJob * job )
01205 {
01206     Q_Q(CopyJob);
01207     // The file we were trying to copy:
01208     QList<CopyInfo>::Iterator it = files.begin();
01209     if ( job->error() )
01210     {
01211         // Should we skip automatically ?
01212         if ( m_bAutoSkipFiles )
01213         {
01214             skip((*it).uSource, false);
01215             m_fileProcessedSize = (*it).size;
01216             files.erase( it ); // Move on to next file
01217         }
01218         else
01219         {
01220             m_conflictError = job->error(); // save for later
01221             // Existing dest ?
01222             if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
01223                  || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
01224                  || ( m_conflictError == ERR_IDENTICAL_FILES ) )
01225             {
01226                 if (m_bAutoRenameFiles) {
01227                     KUrl destDirectory((*it).uDest);
01228                     destDirectory.setPath(destDirectory.directory());
01229                     const QString newName = KIO::RenameDialog::suggestName(destDirectory, (*it).uDest.fileName());
01230 
01231                     KUrl newUrl((*it).uDest);
01232                     newUrl.setFileName(newName);
01233 
01234                     emit q->renamed(q, (*it).uDest, newUrl); // for e.g. kpropsdlg
01235                     (*it).uDest = newUrl;
01236 
01237                     QList<CopyInfo> files;
01238                     files.append(*it);
01239                     emit q->aboutToCreate(q, files);
01240                 }
01241                 else {
01242                     if ( !q->isInteractive() ) {
01243                         q->Job::slotResult( job ); // will set the error and emit result(this)
01244                         return;
01245                     }
01246 
01247                     q->removeSubjob(job);
01248                     assert (!q->hasSubjobs());
01249                     // We need to stat the existing file, to get its last-modification time
01250                     KUrl existingFile((*it).uDest);
01251                     SimpleJob * newJob = KIO::stat(existingFile, StatJob::DestinationSide, 2, KIO::HideProgressInfo);
01252                     Scheduler::setJobPriority(newJob, 1);
01253                     kDebug(7007) << "KIO::stat for resolving conflict on " << existingFile;
01254                     state = STATE_CONFLICT_COPYING_FILES;
01255                     q->addSubjob(newJob);
01256                     return; // Don't move to next file yet !
01257                 }
01258             }
01259             else
01260             {
01261                 if ( m_bCurrentOperationIsLink && qobject_cast<KIO::DeleteJob*>( job ) )
01262                 {
01263                     // Very special case, see a few lines below
01264                     // We are deleting the source of a symlink we successfully moved... ignore error
01265                     m_fileProcessedSize = (*it).size;
01266                     files.erase( it );
01267                 } else {
01268                     if ( !q->isInteractive() ) {
01269                         q->Job::slotResult( job ); // will set the error and emit result(this)
01270                         return;
01271                     }
01272 
01273                     // Go directly to the conflict resolution, there is nothing to stat
01274                     slotResultConflictCopyingFiles( job );
01275                     return;
01276                 }
01277             }
01278         }
01279     } else // no error
01280     {
01281         // Special case for moving links. That operation needs two jobs, unlike others.
01282         if ( m_bCurrentOperationIsLink && m_mode == CopyJob::Move
01283              && !qobject_cast<KIO::DeleteJob *>( job ) // Deleting source not already done
01284              )
01285         {
01286             q->removeSubjob( job );
01287             assert ( !q->hasSubjobs() );
01288             // The only problem with this trick is that the error handling for this del operation
01289             // is not going to be right... see 'Very special case' above.
01290             KIO::Job * newjob = KIO::del( (*it).uSource, HideProgressInfo );
01291             q->addSubjob( newjob );
01292             return; // Don't move to next file yet !
01293         }
01294 
01295         if ( m_bCurrentOperationIsLink )
01296         {
01297             QString target = ( m_mode == CopyJob::Link ? (*it).uSource.path() : (*it).linkDest );
01298             //required for the undo feature
01299             emit q->copyingLinkDone( q, (*it).uSource, target, (*it).uDest );
01300         }
01301         else {
01302             //required for the undo feature
01303             emit q->copyingDone( q, (*it).uSource, (*it).uDest, (*it).mtime, false, false );
01304             if (m_mode == CopyJob::Move)
01305             {
01306                 org::kde::KDirNotify::emitFileMoved( (*it).uSource.url(), (*it).uDest.url() );
01307             }
01308             m_successSrcList.append((*it).uSource);
01309             if (m_freeSpace != (KIO::filesize_t)-1 && (*it).size != (KIO::filesize_t)-1) {
01310                 m_freeSpace -= (*it).size;
01311             }
01312 
01313         }
01314         // remove from list, to move on to next file
01315         files.erase( it );
01316     }
01317     m_processedFiles++;
01318 
01319     // clear processed size for last file and add it to overall processed size
01320     m_processedSize += m_fileProcessedSize;
01321     m_fileProcessedSize = 0;
01322 
01323     //kDebug(7007) << files.count() << "files remaining";
01324 
01325     // Merge metadata from subjob
01326     KIO::Job* kiojob = dynamic_cast<KIO::Job*>(job);
01327     Q_ASSERT(kiojob);
01328     m_incomingMetaData += kiojob->metaData();
01329     q->removeSubjob( job );
01330     assert( !q->hasSubjobs() ); // We should have only one job at a time ...
01331     copyNextFile();
01332 }
01333 
01334 void CopyJobPrivate::slotResultConflictCopyingFiles( KJob * job )
01335 {
01336     Q_Q(CopyJob);
01337     // We come here after a conflict has been detected and we've stated the existing file
01338     // The file we were trying to create:
01339     QList<CopyInfo>::Iterator it = files.begin();
01340 
01341     RenameDialog_Result res;
01342     QString newPath;
01343 
01344     if (m_reportTimer)
01345         m_reportTimer->stop();
01346 
01347     if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
01348          || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
01349          || ( m_conflictError == ERR_IDENTICAL_FILES ) )
01350     {
01351         // Its modification time:
01352         const UDSEntry entry = ((KIO::StatJob*)job)->statResult();
01353 
01354         const time_t destmtime = (time_t) entry.numberValue( KIO::UDSEntry::UDS_MODIFICATION_TIME, -1 );
01355         const time_t destctime = (time_t) entry.numberValue( KIO::UDSEntry::UDS_CREATION_TIME, -1 );
01356         const KIO::filesize_t destsize = entry.numberValue( KIO::UDSEntry::UDS_SIZE );
01357         const QString linkDest = entry.stringValue( KIO::UDSEntry::UDS_LINK_DEST );
01358 
01359         // Offer overwrite only if the existing thing is a file
01360         // If src==dest, use "overwrite-itself"
01361         RenameDialog_Mode mode;
01362         bool isDir = true;
01363 
01364         if( m_conflictError == ERR_DIR_ALREADY_EXIST )
01365             mode = M_ISDIR;
01366         else
01367         {
01368             if ( (*it).uSource == (*it).uDest  ||
01369                  ((*it).uSource.protocol() == (*it).uDest.protocol() &&
01370                    (*it).uSource.path( KUrl::RemoveTrailingSlash ) == linkDest) )
01371                 mode = M_OVERWRITE_ITSELF;
01372             else
01373                 mode = M_OVERWRITE;
01374             isDir = false;
01375         }
01376 
01377         if ( !m_bSingleFileCopy )
01378             mode = (RenameDialog_Mode) ( mode | M_MULTI | M_SKIP );
01379 
01380         res = q->ui()->askFileRename( q, !isDir ?
01381                                    i18n("File Already Exists") : i18n("Already Exists as Folder"),
01382                                    (*it).uSource.url(),
01383                                    (*it).uDest.url(),
01384                                    mode, newPath,
01385                                    (*it).size, destsize,
01386                                    (*it).ctime, destctime,
01387                                    (*it).mtime, destmtime );
01388 
01389     }
01390     else
01391     {
01392         if ( job->error() == ERR_USER_CANCELED )
01393             res = R_CANCEL;
01394         else if ( !q->isInteractive() ) {
01395             q->Job::slotResult( job ); // will set the error and emit result(this)
01396             return;
01397         }
01398         else
01399         {
01400             SkipDialog_Result skipResult = q->ui()->askSkip( q, files.count() > 1,
01401                                                           job->errorString() );
01402 
01403             // Convert the return code from SkipDialog into a RenameDialog code
01404             res = ( skipResult == S_SKIP ) ? R_SKIP :
01405                          ( skipResult == S_AUTO_SKIP ) ? R_AUTO_SKIP :
01406                                         R_CANCEL;
01407         }
01408     }
01409 
01410     if (m_reportTimer)
01411         m_reportTimer->start(REPORT_TIMEOUT);
01412 
01413     q->removeSubjob( job );
01414     assert ( !q->hasSubjobs() );
01415     switch ( res ) {
01416         case R_CANCEL:
01417             q->setError( ERR_USER_CANCELED );
01418             q->emitResult();
01419             return;
01420         case R_AUTO_RENAME:
01421             m_bAutoRenameFiles = true;
01422             // fall through
01423         case R_RENAME:
01424         {
01425             KUrl newUrl( (*it).uDest );
01426             newUrl.setPath( newPath );
01427             emit q->renamed( q, (*it).uDest, newUrl ); // for e.g. kpropsdlg
01428             (*it).uDest = newUrl;
01429 
01430             QList<CopyInfo> files;
01431             files.append(*it);
01432             emit q->aboutToCreate( q, files );
01433         }
01434         break;
01435         case R_AUTO_SKIP:
01436             m_bAutoSkipFiles = true;
01437             // fall through
01438         case R_SKIP:
01439             // Move on to next file
01440             skip((*it).uSource, false);
01441             m_processedSize += (*it).size;
01442             files.erase( it );
01443             m_processedFiles++;
01444             break;
01445        case R_OVERWRITE_ALL:
01446             m_bOverwriteAllFiles = true;
01447             break;
01448         case R_OVERWRITE:
01449             // Add to overwrite list, so that copyNextFile knows to overwrite
01450             m_overwriteList.insert( (*it).uDest.path() );
01451             break;
01452         default:
01453             assert( 0 );
01454     }
01455     state = STATE_COPYING_FILES;
01456     copyNextFile();
01457 }
01458 
01459 KIO::Job* CopyJobPrivate::linkNextFile( const KUrl& uSource, const KUrl& uDest, JobFlags flags )
01460 {
01461     //kDebug(7007) << "Linking";
01462     if (
01463         (uSource.protocol() == uDest.protocol()) &&
01464         (uSource.host() == uDest.host()) &&
01465         (uSource.port() == uDest.port()) &&
01466         (uSource.user() == uDest.user()) &&
01467         (uSource.pass() == uDest.pass()) )
01468     {
01469         // This is the case of creating a real symlink
01470         KIO::SimpleJob *newJob = KIO::symlink( uSource.path(), uDest, flags|HideProgressInfo /*no GUI*/ );
01471         Scheduler::setJobPriority(newJob, 1);
01472         //kDebug(7007) << "Linking target=" << uSource.path() << "link=" << uDest;
01473         //emit linking( this, uSource.path(), uDest );
01474         m_bCurrentOperationIsLink = true;
01475         m_currentSrcURL=uSource;
01476         m_currentDestURL=uDest;
01477         m_bURLDirty = true;
01478         //Observer::self()->slotCopying( this, uSource, uDest ); // should be slotLinking perhaps
01479         return newJob;
01480     } else {
01481         Q_Q(CopyJob);
01482         //kDebug(7007) << "Linking URL=" << uSource << "link=" << uDest;
01483         if ( uDest.isLocalFile() ) {
01484             // if the source is a devices url, handle it a littlebit special
01485 
01486             QString path = uDest.toLocalFile();
01487             //kDebug(7007) << "path=" << path;
01488             QFile f( path );
01489             if ( f.open( QIODevice::ReadWrite ) )
01490             {
01491                 f.close();
01492                 KDesktopFile desktopFile( path );
01493                 KConfigGroup config = desktopFile.desktopGroup();
01494                 KUrl url = uSource;
01495                 url.setPass( "" );
01496                 config.writePathEntry( "URL", url.url() );
01497                 config.writeEntry( "Name", url.url() );
01498                 config.writeEntry( "Type", QString::fromLatin1("Link") );
01499                 QString protocol = uSource.protocol();
01500                 if ( protocol == QLatin1String("ftp") )
01501                     config.writeEntry( "Icon", QString::fromLatin1("folder-remote") );
01502                 else if ( protocol == QLatin1String("http") )
01503                     config.writeEntry( "Icon", QString::fromLatin1("text-html") );
01504                 else if ( protocol == QLatin1String("info") )
01505                     config.writeEntry( "Icon", QString::fromLatin1("text-x-texinfo") );
01506                 else if ( protocol == QLatin1String("mailto") )   // sven:
01507                     config.writeEntry( "Icon", QString::fromLatin1("internet-mail") ); // added mailto: support
01508                 else
01509                     config.writeEntry( "Icon", QString::fromLatin1("unknown") );
01510                 config.sync();
01511                 files.erase( files.begin() ); // done with this one, move on
01512                 m_processedFiles++;
01513                 //emit processedAmount( this, KJob::Files, m_processedFiles );
01514                 copyNextFile();
01515                 return 0;
01516             }
01517             else
01518             {
01519                 kDebug(7007) << "ERR_CANNOT_OPEN_FOR_WRITING";
01520                 q->setError( ERR_CANNOT_OPEN_FOR_WRITING );
01521                 q->setErrorText( uDest.toLocalFile() );
01522                 q->emitResult();
01523                 return 0;
01524             }
01525         } else {
01526             // Todo: not show "link" on remote dirs if the src urls are not from the same protocol+host+...
01527             q->setError( ERR_CANNOT_SYMLINK );
01528             q->setErrorText( uDest.prettyUrl() );
01529             q->emitResult();
01530             return 0;
01531         }
01532     }
01533 }
01534 
01535 void CopyJobPrivate::copyNextFile()
01536 {
01537     Q_Q(CopyJob);
01538     bool bCopyFile = false;
01539     //kDebug(7007);
01540     // Take the first file in the list
01541     QList<CopyInfo>::Iterator it = files.begin();
01542     // Is this URL on the skip list ?
01543     while (it != files.end() && !bCopyFile)
01544     {
01545         const QString destFile = (*it).uDest.path();
01546         bCopyFile = !shouldSkip( destFile );
01547         if ( !bCopyFile ) {
01548             files.erase( it );
01549             it = files.begin();
01550         }
01551     }
01552 
01553     if (bCopyFile) // any file to create, finally ?
01554     {
01555         //kDebug()<<"preparing to copy"<<(*it).uSource<<(*it).size<<m_freeSpace;
01556         if (m_freeSpace != (KIO::filesize_t)-1 && (*it).size != (KIO::filesize_t)-1) {
01557             if (m_freeSpace < (*it).size) {
01558                 q->setError( ERR_DISK_FULL );
01559                 q->emitResult();
01560                 return;
01561             }
01562             //TODO check if dst mount is msdos and (*it).size exceeds it's limits
01563         }
01564 
01565         const KUrl& uSource = (*it).uSource;
01566         const KUrl& uDest = (*it).uDest;
01567         // Do we set overwrite ?
01568         bool bOverwrite;
01569         const QString destFile = uDest.path();
01570         // kDebug(7007) << "copying" << destFile;
01571         if ( uDest == uSource )
01572             bOverwrite = false;
01573         else
01574             bOverwrite = shouldOverwriteFile( destFile );
01575 
01576         m_bCurrentOperationIsLink = false;
01577         KIO::Job * newjob = 0;
01578         if ( m_mode == CopyJob::Link ) {
01579             // User requested that a symlink be made
01580             const JobFlags flags = bOverwrite ? Overwrite : DefaultFlags;
01581             newjob = linkNextFile(uSource, uDest, flags);
01582             if (!newjob)
01583                 return;
01584         } else if ( !(*it).linkDest.isEmpty() &&
01585                   (uSource.protocol() == uDest.protocol()) &&
01586                   (uSource.host() == uDest.host()) &&
01587                   (uSource.port() == uDest.port()) &&
01588                   (uSource.user() == uDest.user()) &&
01589                   (uSource.pass() == uDest.pass()))
01590             // Copying a symlink - only on the same protocol/host/etc. (#5601, downloading an FTP file through its link),
01591         {
01592             const JobFlags flags = bOverwrite ? Overwrite : DefaultFlags;
01593             KIO::SimpleJob *newJob = KIO::symlink( (*it).linkDest, uDest, flags | HideProgressInfo /*no GUI*/ );
01594             Scheduler::setJobPriority(newJob, 1);
01595             newjob = newJob;
01596             //kDebug(7007) << "Linking target=" << (*it).linkDest << "link=" << uDest;
01597             m_currentSrcURL = KUrl( (*it).linkDest );
01598             m_currentDestURL = uDest;
01599             m_bURLDirty = true;
01600             //emit linking( this, (*it).linkDest, uDest );
01601             //Observer::self()->slotCopying( this, m_currentSrcURL, uDest ); // should be slotLinking perhaps
01602             m_bCurrentOperationIsLink = true;
01603             // NOTE: if we are moving stuff, the deletion of the source will be done in slotResultCopyingFiles
01604         } else if (m_mode == CopyJob::Move) // Moving a file
01605         {
01606             JobFlags flags = bOverwrite ? Overwrite : DefaultFlags;
01607             KIO::FileCopyJob * moveJob = KIO::file_move( uSource, uDest, (*it).permissions, flags | HideProgressInfo/*no GUI*/ );
01608             moveJob->setSourceSize( (*it).size );
01609             if ((*it).mtime != -1) {
01610                 moveJob->setModificationTime( QDateTime::fromTime_t( (*it).mtime ) ); // #55804
01611             }
01612             newjob = moveJob;
01613             //kDebug(7007) << "Moving" << uSource << "to" << uDest;
01614             //emit moving( this, uSource, uDest );
01615             m_currentSrcURL=uSource;
01616             m_currentDestURL=uDest;
01617             m_bURLDirty = true;
01618             //Observer::self()->slotMoving( this, uSource, uDest );
01619         }
01620         else // Copying a file
01621         {
01622             // If source isn't local and target is local, we ignore the original permissions
01623             // Otherwise, files downloaded from HTTP end up with -r--r--r--
01624             bool remoteSource = !KProtocolManager::supportsListing(uSource);
01625             int permissions = (*it).permissions;
01626             if ( m_defaultPermissions || ( remoteSource && uDest.isLocalFile() ) )
01627                 permissions = -1;
01628             JobFlags flags = bOverwrite ? Overwrite : DefaultFlags;
01629             KIO::FileCopyJob * copyJob = KIO::file_copy( uSource, uDest, permissions, flags | HideProgressInfo/*no GUI*/ );
01630             copyJob->setParentJob( q ); // in case of rename dialog
01631             copyJob->setSourceSize( (*it).size );
01632             if ((*it).mtime != -1) {
01633                 copyJob->setModificationTime( QDateTime::fromTime_t( (*it).mtime ) );
01634             }
01635             newjob = copyJob;
01636             //kDebug(7007) << "Copying" << uSource << "to" << uDest;
01637             m_currentSrcURL=uSource;
01638             m_currentDestURL=uDest;
01639             m_bURLDirty = true;
01640         }
01641         q->addSubjob(newjob);
01642         q->connect( newjob, SIGNAL(processedSize(KJob*,qulonglong)),
01643                     SLOT(slotProcessedSize(KJob*,qulonglong)) );
01644         q->connect( newjob, SIGNAL(totalSize(KJob*,qulonglong)),
01645                     SLOT(slotTotalSize(KJob*,qulonglong)) );
01646     }
01647     else
01648     {
01649         // We're done
01650         //kDebug(7007) << "copyNextFile finished";
01651         deleteNextDir();
01652     }
01653 }
01654 
01655 void CopyJobPrivate::deleteNextDir()
01656 {
01657     Q_Q(CopyJob);
01658     if ( m_mode == CopyJob::Move && !dirsToRemove.isEmpty() ) // some dirs to delete ?
01659     {
01660         state = STATE_DELETING_DIRS;
01661         m_bURLDirty = true;
01662         // Take first dir to delete out of list - last ones first !
01663         KUrl::List::Iterator it = --dirsToRemove.end();
01664         SimpleJob *job = KIO::rmdir( *it );
01665         Scheduler::setJobPriority(job, 1);
01666         dirsToRemove.erase(it);
01667         q->addSubjob( job );
01668     }
01669     else
01670     {
01671         // This step is done, move on
01672         state = STATE_SETTING_DIR_ATTRIBUTES;
01673         m_directoriesCopiedIterator = m_directoriesCopied.constBegin();
01674         setNextDirAttribute();
01675     }
01676 }
01677 
01678 void CopyJobPrivate::setNextDirAttribute()
01679 {
01680     Q_Q(CopyJob);
01681     while (m_directoriesCopiedIterator != m_directoriesCopied.constEnd() &&
01682            (*m_directoriesCopiedIterator).mtime == -1) {
01683         ++m_directoriesCopiedIterator;
01684     }
01685     if ( m_directoriesCopiedIterator != m_directoriesCopied.constEnd() ) {
01686         const KUrl url = (*m_directoriesCopiedIterator).uDest;
01687         const time_t mtime = (*m_directoriesCopiedIterator).mtime;
01688         const QDateTime dt = QDateTime::fromTime_t(mtime);
01689         ++m_directoriesCopiedIterator;
01690 
01691         KIO::SimpleJob *job = KIO::setModificationTime( url, dt );
01692         Scheduler::setJobPriority(job, 1);
01693         q->addSubjob( job );
01694 
01695 
01696 #if 0 // ifdef Q_OS_UNIX
01697         // TODO: can be removed now. Or reintroduced as a fast path for local files
01698         // if launching even more jobs as done above is a performance problem.
01699         //
01700         QLinkedList<CopyInfo>::const_iterator it = m_directoriesCopied.constBegin();
01701         for ( ; it != m_directoriesCopied.constEnd() ; ++it ) {
01702             const KUrl& url = (*it).uDest;
01703             if ( url.isLocalFile() && (*it).mtime != (time_t)-1 ) {
01704                 KDE_struct_stat statbuf;
01705                 if (KDE::lstat(url.path(), &statbuf) == 0) {
01706                     struct utimbuf utbuf;
01707                     utbuf.actime = statbuf.st_atime; // access time, unchanged
01708                     utbuf.modtime = (*it).mtime; // modification time
01709                     utime( path, &utbuf );
01710                 }
01711 
01712             }
01713         }
01714         m_directoriesCopied.clear();
01715         // but then we need to jump to the else part below. Maybe with a recursive call?
01716 #endif
01717     } else {
01718         if (m_reportTimer)
01719             m_reportTimer->stop();
01720         --m_processedFiles; // undo the "start at 1" hack
01721         slotReport(); // display final numbers, important if progress dialog stays up
01722 
01723         q->emitResult();
01724     }
01725 }
01726 
01727 void CopyJob::emitResult()
01728 {
01729     Q_D(CopyJob);
01730     // Before we go, tell the world about the changes that were made.
01731     // Even if some error made us abort midway, we might still have done
01732     // part of the job so we better update the views! (#118583)
01733     if (!d->m_bOnlyRenames) {
01734         KUrl url(d->m_globalDest);
01735         if (d->m_globalDestinationState != DEST_IS_DIR || d->m_asMethod)
01736             url.setPath(url.directory());
01737         //kDebug(7007) << "KDirNotify'ing FilesAdded" << url;
01738         org::kde::KDirNotify::emitFilesAdded( url.url() );
01739 
01740         if (d->m_mode == CopyJob::Move && !d->m_successSrcList.isEmpty()) {
01741             kDebug(7007) << "KDirNotify'ing FilesRemoved" << d->m_successSrcList.toStringList();
01742             org::kde::KDirNotify::emitFilesRemoved(d->m_successSrcList.toStringList());
01743         }
01744 
01745         // Re-enable watching on the dirs that held the deleted files
01746         if (d->m_mode == CopyJob::Move) {
01747             for (QSet<QString>::const_iterator it = d->m_parentDirs.constBegin() ; it != d->m_parentDirs.constEnd() ; ++it)
01748                 KDirWatch::self()->restartDirScan( *it );
01749         }
01750     }
01751     Job::emitResult();
01752 }
01753 
01754 void CopyJobPrivate::slotProcessedSize( KJob*, qulonglong data_size )
01755 {
01756   Q_Q(CopyJob);
01757   //kDebug(7007) << data_size;
01758   m_fileProcessedSize = data_size;
01759   q->setProcessedAmount(KJob::Bytes, m_processedSize + m_fileProcessedSize);
01760 
01761   if ( m_processedSize + m_fileProcessedSize > m_totalSize )
01762   {
01763     // Example: download any attachment from bugs.kde.org
01764     m_totalSize = m_processedSize + m_fileProcessedSize;
01765     //kDebug(7007) << "Adjusting m_totalSize to" << m_totalSize;
01766     q->setTotalAmount(KJob::Bytes, m_totalSize); // safety
01767   }
01768   //kDebug(7007) << "emit processedSize" << (unsigned long) (m_processedSize + m_fileProcessedSize);
01769   q->setProcessedAmount(KJob::Bytes, m_processedSize + m_fileProcessedSize);
01770 }
01771 
01772 void CopyJobPrivate::slotTotalSize( KJob*, qulonglong size )
01773 {
01774   Q_Q(CopyJob);
01775   //kDebug(7007) << size;
01776   // Special case for copying a single file
01777   // This is because some protocols don't implement stat properly
01778   // (e.g. HTTP), and don't give us a size in some cases (redirection)
01779   // so we'd rather rely on the size given for the transfer
01780   if ( m_bSingleFileCopy && size != m_totalSize)
01781   {
01782     //kDebug(7007) << "slotTotalSize: updating totalsize to" << size;
01783     m_totalSize = size;
01784     q->setTotalAmount(KJob::Bytes, size);
01785   }
01786 }
01787 
01788 void CopyJobPrivate::slotResultDeletingDirs( KJob * job )
01789 {
01790     Q_Q(CopyJob);
01791     if (job->error()) {
01792         // Couldn't remove directory. Well, perhaps it's not empty
01793         // because the user pressed Skip for a given file in it.
01794         // Let's not display "Could not remove dir ..." for each of those dir !
01795     } else {
01796         m_successSrcList.append(static_cast<KIO::SimpleJob*>(job)->url());
01797     }
01798     q->removeSubjob( job );
01799     assert( !q->hasSubjobs() );
01800     deleteNextDir();
01801 }
01802 
01803 void CopyJobPrivate::slotResultSettingDirAttributes( KJob * job )
01804 {
01805     Q_Q(CopyJob);
01806     if (job->error())
01807     {
01808         // Couldn't set directory attributes. Ignore the error, it can happen
01809         // with inferior file systems like VFAT.
01810         // Let's not display warnings for each dir like "cp -a" does.
01811     }
01812     q->removeSubjob( job );
01813     assert( !q->hasSubjobs() );
01814     setNextDirAttribute();
01815 }
01816 
01817 // We were trying to do a direct renaming, before even stat'ing
01818 void CopyJobPrivate::slotResultRenaming( KJob* job )
01819 {
01820     Q_Q(CopyJob);
01821     int err = job->error();
01822     const QString errText = job->errorText();
01823     // Merge metadata from subjob
01824     KIO::Job* kiojob = dynamic_cast<KIO::Job*>(job);
01825     Q_ASSERT(kiojob);
01826     m_incomingMetaData += kiojob->metaData();
01827     q->removeSubjob( job );
01828     assert ( !q->hasSubjobs() );
01829     // Determine dest again
01830     KUrl dest = m_dest;
01831     if ( destinationState == DEST_IS_DIR && !m_asMethod )
01832         dest.addPath( m_currentSrcURL.fileName() );
01833     if ( err )
01834     {
01835         // Direct renaming didn't work. Try renaming to a temp name,
01836         // this can help e.g. when renaming 'a' to 'A' on a VFAT partition.
01837         // In that case it's the _same_ dir, we don't want to copy+del (data loss!)
01838       if ( m_currentSrcURL.isLocalFile() && m_currentSrcURL.url(KUrl::RemoveTrailingSlash) != dest.url(KUrl::RemoveTrailingSlash) &&
01839            m_currentSrcURL.url(KUrl::RemoveTrailingSlash).toLower() == dest.url(KUrl::RemoveTrailingSlash).toLower() &&
01840              ( err == ERR_FILE_ALREADY_EXIST ||
01841                err == ERR_DIR_ALREADY_EXIST ||
01842                err == ERR_IDENTICAL_FILES ) )
01843         {
01844             kDebug(7007) << "Couldn't rename directly, dest already exists. Detected special case of lower/uppercase renaming in same dir, try with 2 rename calls";
01845             const QString _src( m_currentSrcURL.toLocalFile() );
01846             const QString _dest( dest.toLocalFile() );
01847             const QString _tmpPrefix = m_currentSrcURL.directory(KUrl::ObeyTrailingSlash|KUrl::AppendTrailingSlash);
01848             KTemporaryFile tmpFile;
01849             tmpFile.setPrefix(_tmpPrefix);
01850             const bool openOk = tmpFile.open();
01851             if (!openOk) {
01852                 kWarning(7007) << "Couldn't open temp file in" << _tmpPrefix;
01853             } else {
01854                 const QString _tmp( tmpFile.fileName() );
01855                 tmpFile.close();
01856                 tmpFile.remove();
01857                 kDebug(7007) << "KTemporaryFile using" << _tmp << "as intermediary";
01858                 if (KDE::rename( _src, _tmp ) == 0) {
01859                     //kDebug(7007) << "Renaming" << _src << "to" << _tmp << "succeeded";
01860                     if (!QFile::exists( _dest ) && KDE::rename(_tmp, _dest) == 0) {
01861                         err = 0;
01862                         org::kde::KDirNotify::emitFileRenamed(m_currentSrcURL.url(), dest.url());
01863                     } else {
01864                         kDebug(7007) << "Didn't manage to rename" << _tmp << "to" << _dest << ", reverting";
01865                         // Revert back to original name!
01866                         if (KDE::rename( _tmp, _src ) != 0) {
01867                             kError(7007) << "Couldn't rename" << _tmp << "back to" << _src << '!';
01868                             // Severe error, abort
01869                             q->Job::slotResult(job); // will set the error and emit result(this)
01870                             return;
01871                         }
01872                     }
01873                 } else {
01874                     kDebug(7007) << "mv" << _src << _tmp << "failed:" << strerror(errno);
01875                 }
01876             }
01877         }
01878     }
01879     if ( err )
01880     {
01881         // This code is similar to CopyJobPrivate::slotResultConflictCopyingFiles
01882         // but here it's about the base src url being moved/renamed
01883         // (m_currentSrcURL) and its dest (m_dest), not about a single file.
01884         // It also means we already stated the dest, here.
01885         // On the other hand we haven't stated the src yet (we skipped doing it
01886         // to save time, since it's not necessary to rename directly!)...
01887 
01888         // Existing dest?
01889         if ( err == ERR_DIR_ALREADY_EXIST ||
01890                err == ERR_FILE_ALREADY_EXIST ||
01891                err == ERR_IDENTICAL_FILES )
01892         {
01893             // Should we skip automatically ?
01894             bool isDir = (err == ERR_DIR_ALREADY_EXIST); // ## technically, isDir means "source is dir", not "dest is dir" #######
01895             if ((isDir && m_bAutoSkipDirs) || (!isDir && m_bAutoSkipFiles)) {
01896                 // Move on to next source url
01897                 skipSrc(isDir);
01898                 return;
01899             } else if ((isDir && m_bOverwriteAllDirs) || (!isDir && m_bOverwriteAllFiles)) {
01900                 ; // nothing to do, stat+copy+del will overwrite
01901             } else if ((isDir && m_bAutoRenameDirs) || (!isDir && m_bAutoRenameFiles)) {
01902                 KUrl destDirectory(m_currentDestURL); // dest including filename
01903                 destDirectory.setPath(destDirectory.directory());
01904                 const QString newName = KIO::RenameDialog::suggestName(destDirectory, m_currentDestURL.fileName());
01905 
01906                 m_dest.setPath(m_currentDestURL.path());
01907                 m_dest.setFileName(newName);
01908                 KIO::Job* job = KIO::stat(m_dest, StatJob::DestinationSide, 2, KIO::HideProgressInfo);
01909                 state = STATE_STATING;
01910                 destinationState = DEST_NOT_STATED;
01911                 q->addSubjob(job);
01912                 return;
01913             } else if ( q->isInteractive() ) {
01914                 QString newPath;
01915                 // we lack mtime info for both the src (not stated)
01916                 // and the dest (stated but this info wasn't stored)
01917                 // Let's do it for local files, at least
01918                 KIO::filesize_t sizeSrc = (KIO::filesize_t) -1;
01919                 KIO::filesize_t sizeDest = (KIO::filesize_t) -1;
01920                 time_t ctimeSrc = (time_t) -1;
01921                 time_t ctimeDest = (time_t) -1;
01922                 time_t mtimeSrc = (time_t) -1;
01923                 time_t mtimeDest = (time_t) -1;
01924 
01925                 bool destIsDir = err == ERR_DIR_ALREADY_EXIST;
01926 
01927                 // ## TODO we need to stat the source using KIO::stat
01928                 // so that this code is properly network-transparent.
01929 
01930                 KDE_struct_stat stat_buf;
01931                 if ( m_currentSrcURL.isLocalFile() &&
01932                     KDE::stat(m_currentSrcURL.toLocalFile(), &stat_buf) == 0 ) {
01933                     sizeSrc = stat_buf.st_size;
01934                     ctimeSrc = stat_buf.st_ctime;
01935                     mtimeSrc = stat_buf.st_mtime;
01936                     isDir = S_ISDIR(stat_buf.st_mode);
01937                 }
01938                 if ( dest.isLocalFile() &&
01939                     KDE::stat(dest.toLocalFile(), &stat_buf) == 0 ) {
01940                     sizeDest = stat_buf.st_size;
01941                     ctimeDest = stat_buf.st_ctime;
01942                     mtimeDest = stat_buf.st_mtime;
01943                     destIsDir = S_ISDIR(stat_buf.st_mode);
01944                 }
01945 
01946                 // If src==dest, use "overwrite-itself"
01947                 RenameDialog_Mode mode = ( m_currentSrcURL == dest ) ? M_OVERWRITE_ITSELF : M_OVERWRITE;
01948                 if (!isDir && destIsDir) {
01949                     // We can't overwrite a dir with a file.
01950                     mode = (RenameDialog_Mode) 0;
01951                 }
01952 
01953                 if ( m_srcList.count() > 1 )
01954                     mode = (RenameDialog_Mode) ( mode | M_MULTI | M_SKIP );
01955                 if (destIsDir)
01956                     mode = (RenameDialog_Mode) ( mode | M_ISDIR );
01957 
01958                 if (m_reportTimer)
01959                     m_reportTimer->stop();
01960 
01961                 RenameDialog_Result r = q->ui()->askFileRename(
01962                     q,
01963                     err != ERR_DIR_ALREADY_EXIST ? i18n("File Already Exists") : i18n("Already Exists as Folder"),
01964                     m_currentSrcURL.url(),
01965                     dest.url(),
01966                     mode, newPath,
01967                     sizeSrc, sizeDest,
01968                     ctimeSrc, ctimeDest,
01969                     mtimeSrc, mtimeDest );
01970 
01971                 if (m_reportTimer)
01972                     m_reportTimer->start(REPORT_TIMEOUT);
01973 
01974                 switch ( r )
01975                 {
01976                 case R_CANCEL:
01977                 {
01978                     q->setError( ERR_USER_CANCELED );
01979                     q->emitResult();
01980                     return;
01981                 }
01982                 case R_AUTO_RENAME:
01983                     if (isDir) {
01984                         m_bAutoRenameDirs = true;
01985                     }
01986                     else {
01987                         m_bAutoRenameFiles = true;
01988                     }
01989                     // fall through
01990                 case R_RENAME:
01991                 {
01992                     // Set m_dest to the chosen destination
01993                     // This is only for this src url; the next one will revert to m_globalDest
01994                     m_dest.setPath( newPath );
01995                     KIO::Job* job = KIO::stat( m_dest, StatJob::DestinationSide, 2, KIO::HideProgressInfo );
01996                     state = STATE_STATING;
01997                     destinationState = DEST_NOT_STATED;
01998                     q->addSubjob(job);
01999                     return;
02000                 }
02001                 case R_AUTO_SKIP:
02002                     if (isDir)
02003                         m_bAutoSkipDirs = true;
02004                     else
02005                         m_bAutoSkipFiles = true;
02006                     // fall through
02007                 case R_SKIP:
02008                     // Move on to next url
02009                     skipSrc(isDir);
02010                     return;
02011                 case R_OVERWRITE_ALL:
02012                     if (destIsDir)
02013                         m_bOverwriteAllDirs = true;
02014                     else
02015                         m_bOverwriteAllFiles = true;
02016                     break;
02017                 case R_OVERWRITE:
02018                     // Add to overwrite list
02019                     // Note that we add dest, not m_dest.
02020                     // This ensures that when moving several urls into a dir (m_dest),
02021                     // we only overwrite for the current one, not for all.
02022                     // When renaming a single file (m_asMethod), it makes no difference.
02023                     kDebug(7007) << "adding to overwrite list: " << dest.path();
02024                     m_overwriteList.insert( dest.path() );
02025                     break;
02026                 default:
02027                     //assert( 0 );
02028                     break;
02029                 }
02030             } else if ( err != KIO::ERR_UNSUPPORTED_ACTION ) {
02031                 // Dest already exists, and job is not interactive -> abort with error
02032                 q->setError( err );
02033                 q->setErrorText( errText );
02034                 q->emitResult();
02035                 return;
02036             }
02037         } else if ( err != KIO::ERR_UNSUPPORTED_ACTION ) {
02038             kDebug(7007) << "Couldn't rename" << m_currentSrcURL << "to" << dest << ", aborting";
02039             q->setError( err );
02040             q->setErrorText( errText );
02041             q->emitResult();
02042             return;
02043         }
02044         kDebug(7007) << "Couldn't rename" << m_currentSrcURL << "to" << dest << ", reverting to normal way, starting with stat";
02045         //kDebug(7007) << "KIO::stat on" << m_currentSrcURL;
02046         KIO::Job* job = KIO::stat( m_currentSrcURL, StatJob::SourceSide, 2, KIO::HideProgressInfo );
02047         state = STATE_STATING;
02048         q->addSubjob(job);
02049         m_bOnlyRenames = false;
02050     }
02051     else
02052     {
02053         kDebug(7007) << "Renaming succeeded, move on";
02054         ++m_processedFiles;
02055         emit q->copyingDone( q, *m_currentStatSrc, dest, -1 /*mtime unknown, and not needed*/, true, true );
02056         m_successSrcList.append(*m_currentStatSrc);
02057         statNextSrc();
02058     }
02059 }
02060 
02061 void CopyJob::slotResult( KJob *job )
02062 {
02063     Q_D(CopyJob);
02064     //kDebug(7007) << "d->state=" << (int) d->state;
02065     // In each case, what we have to do is :
02066     // 1 - check for errors and treat them
02067     // 2 - removeSubjob(job);
02068     // 3 - decide what to do next
02069 
02070     switch ( d->state ) {
02071         case STATE_STATING: // We were trying to stat a src url or the dest
02072             d->slotResultStating( job );
02073             break;
02074         case STATE_RENAMING: // We were trying to do a direct renaming, before even stat'ing
02075         {
02076             d->slotResultRenaming( job );
02077             break;
02078         }
02079         case STATE_LISTING: // recursive listing finished
02080             //kDebug(7007) << "totalSize:" << (unsigned int) d->m_totalSize << "files:" << d->files.count() << "d->dirs:" << d->dirs.count();
02081             // Was there an error ?
02082             if (job->error())
02083             {
02084                 Job::slotResult( job ); // will set the error and emit result(this)
02085                 return;
02086             }
02087 
02088             removeSubjob( job );
02089             assert ( !hasSubjobs() );
02090 
02091             d->statNextSrc();
02092             break;
02093         case STATE_CREATING_DIRS:
02094             d->slotResultCreatingDirs( job );
02095             break;
02096         case STATE_CONFLICT_CREATING_DIRS:
02097             d->slotResultConflictCreatingDirs( job );
02098             break;
02099         case STATE_COPYING_FILES:
02100             d->slotResultCopyingFiles( job );
02101             break;
02102         case STATE_CONFLICT_COPYING_FILES:
02103             d->slotResultConflictCopyingFiles( job );
02104             break;
02105         case STATE_DELETING_DIRS:
02106             d->slotResultDeletingDirs( job );
02107             break;
02108         case STATE_SETTING_DIR_ATTRIBUTES:
02109             d->slotResultSettingDirAttributes( job );
02110             break;
02111         default:
02112             assert( 0 );
02113     }
02114 }
02115 
02116 void KIO::CopyJob::setDefaultPermissions( bool b )
02117 {
02118     d_func()->m_defaultPermissions = b;
02119 }
02120 
02121 KIO::CopyJob::CopyMode KIO::CopyJob::operationMode() const
02122 {
02123     return d_func()->m_mode;
02124 }
02125 
02126 void KIO::CopyJob::setAutoSkip(bool autoSkip)
02127 {
02128     d_func()->m_bAutoSkipFiles = autoSkip;
02129     d_func()->m_bAutoSkipDirs = autoSkip;
02130 }
02131 
02132 void KIO::CopyJob::setAutoRename(bool autoRename)
02133 {
02134     d_func()->m_bAutoRenameFiles = autoRename;
02135     d_func()->m_bAutoRenameDirs = autoRename;
02136 }
02137 
02138 void KIO::CopyJob::setWriteIntoExistingDirectories(bool overwriteAll) // #65926
02139 {
02140     d_func()->m_bOverwriteAllDirs = overwriteAll;
02141 }
02142 
02143 CopyJob *KIO::copy(const KUrl& src, const KUrl& dest, JobFlags flags)
02144 {
02145     //kDebug(7007) << "src=" << src << "dest=" << dest;
02146     KUrl::List srcList;
02147     srcList.append( src );
02148     return CopyJobPrivate::newJob(srcList, dest, CopyJob::Copy, false, flags);
02149 }
02150 
02151 CopyJob *KIO::copyAs(const KUrl& src, const KUrl& dest, JobFlags flags)
02152 {
02153     //kDebug(7007) << "src=" << src << "dest=" << dest;
02154     KUrl::List srcList;
02155     srcList.append( src );
02156     return CopyJobPrivate::newJob(srcList, dest, CopyJob::Copy, true, flags);
02157 }
02158 
02159 CopyJob *KIO::copy( const KUrl::List& src, const KUrl& dest, JobFlags flags )
02160 {
02161     //kDebug(7007) << src << dest;
02162     return CopyJobPrivate::newJob(src, dest, CopyJob::Copy, false, flags);
02163 }
02164 
02165 CopyJob *KIO::move(const KUrl& src, const KUrl& dest, JobFlags flags)
02166 {
02167     //kDebug(7007) << src << dest;
02168     KUrl::List srcList;
02169     srcList.append( src );
02170     return CopyJobPrivate::newJob(srcList, dest, CopyJob::Move, false, flags);
02171 }
02172 
02173 CopyJob *KIO::moveAs(const KUrl& src, const KUrl& dest, JobFlags flags)
02174 {
02175     //kDebug(7007) << src << dest;
02176     KUrl::List srcList;
02177     srcList.append( src );
02178     return CopyJobPrivate::newJob(srcList, dest, CopyJob::Move, true, flags);
02179 }
02180 
02181 CopyJob *KIO::move( const KUrl::List& src, const KUrl& dest, JobFlags flags)
02182 {
02183     //kDebug(7007) << src << dest;
02184     return CopyJobPrivate::newJob(src, dest, CopyJob::Move, false, flags);
02185 }
02186 
02187 CopyJob *KIO::link(const KUrl& src, const KUrl& destDir, JobFlags flags)
02188 {
02189     KUrl::List srcList;
02190     srcList.append( src );
02191     return CopyJobPrivate::newJob(srcList, destDir, CopyJob::Link, false, flags);
02192 }
02193 
02194 CopyJob *KIO::link(const KUrl::List& srcList, const KUrl& destDir, JobFlags flags)
02195 {
02196     return CopyJobPrivate::newJob(srcList, destDir, CopyJob::Link, false, flags);
02197 }
02198 
02199 CopyJob *KIO::linkAs(const KUrl& src, const KUrl& destDir, JobFlags flags )
02200 {
02201     KUrl::List srcList;
02202     srcList.append( src );
02203     return CopyJobPrivate::newJob(srcList, destDir, CopyJob::Link, false, flags);
02204 }
02205 
02206 CopyJob *KIO::trash(const KUrl& src, JobFlags flags)
02207 {
02208     KUrl::List srcList;
02209     srcList.append( src );
02210     return CopyJobPrivate::newJob(srcList, KUrl( "trash:/" ), CopyJob::Move, false, flags);
02211 }
02212 
02213 CopyJob *KIO::trash(const KUrl::List& srcList, JobFlags flags)
02214 {
02215     return CopyJobPrivate::newJob(srcList, KUrl( "trash:/" ), CopyJob::Move, false, flags);
02216 }
02217 
02218 #include "copyjob.moc"
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Wed Nov 28 2012 09:50:32 by doxygen 1.7.5 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KIO

Skip menu "KIO"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • File Members
  • Related Pages

kdelibs-4.8.5 API Reference

Skip menu "kdelibs-4.8.5 API Reference"
  • DNSSD
  • Interfaces
  •   KHexEdit
  •   KMediaPlayer
  •   KSpeech
  •   KTextEditor
  • kconf_update
  • KDE3Support
  •   KUnitTest
  • KDECore
  • KDED
  • KDEsu
  • KDEUI
  • KDEWebKit
  • KDocTools
  • KFile
  • KHTML
  • KImgIO
  • KInit
  • kio
  • KIOSlave
  • KJS
  •   KJS-API
  •   WTF
  • kjsembed
  • KNewStuff
  • KParts
  • KPty
  • Kross
  • KUnitConversion
  • KUtils
  • Nepomuk
  • Plasma
  • Solid
  • Sonnet
  • ThreadWeaver
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal