diff --git a/krusader/FileSystem/CMakeLists.txt b/krusader/FileSystem/CMakeLists.txt --- a/krusader/FileSystem/CMakeLists.txt +++ b/krusader/FileSystem/CMakeLists.txt @@ -4,6 +4,7 @@ defaultfilesystem.cpp dirlisterinterface.cpp fileitem.cpp + filesearcher.cpp filesystem.cpp filesystemprovider.cpp krpermhandler.cpp diff --git a/krusader/FileSystem/fileitem.h b/krusader/FileSystem/fileitem.h --- a/krusader/FileSystem/fileitem.h +++ b/krusader/FileSystem/fileitem.h @@ -76,6 +76,11 @@ bool isLink = false, const QString &linkDest = QString(), bool isBrokenLink = false, const QString &acl = QString(), const QString &defaultAcl = QString()); + /** + * Create a dummy file item for a non-existing file. + */ + FileItem(); + /** Create a new ".." dummy file item. */ static FileItem *createDummy(); /** Create a file item for a broken file which metadata could not be read. */ diff --git a/krusader/FileSystem/fileitem.cpp b/krusader/FileSystem/fileitem.cpp --- a/krusader/FileSystem/fileitem.cpp +++ b/krusader/FileSystem/fileitem.cpp @@ -71,6 +71,17 @@ } } +FileItem::FileItem() + : m_name(), m_url(), m_isDir(false), + m_size(0), m_mode(0), m_mtime(0), + m_uid(), m_gid(), m_owner(), m_group(), + m_isLink(false), m_linkDest(), m_isBrokenLink(false), + m_permissions(), + m_acl(), m_defaulfAcl(), m_AclLoaded(false), + m_mimeType(), m_iconName() +{ +} + FileItem *FileItem::createDummy() { FileItem *file = new FileItem("..", QUrl(), true, diff --git a/krusader/Search/krsearchmod.h b/krusader/FileSystem/filesearcher.h rename from krusader/Search/krsearchmod.h rename to krusader/FileSystem/filesearcher.h --- a/krusader/Search/krsearchmod.h +++ b/krusader/FileSystem/filesearcher.h @@ -19,8 +19,8 @@ * along with Krusader. If not, see [http://www.gnu.org/licenses/]. * *****************************************************************************/ -#ifndef KRSEARCHMOD_H -#define KRSEARCHMOD_H +#ifndef FILESEARCHER_H +#define FILESEARCHER_H // QtCore #include @@ -31,7 +31,8 @@ #include -class KRQuery; +#include "krquery.h" + class FileItem; class FileSystem; class DefaultFileSystem; @@ -42,15 +43,26 @@ * * Subdirectories are included if query->isRecursive() is true. */ -class KRSearchMod : public QObject +class FileSearcher: public QObject { Q_OBJECT public: - explicit KRSearchMod(const KRQuery *query); - ~KRSearchMod(); + explicit FileSearcher(const KRQuery &query); + ~FileSearcher(); - void start(); + /** + * Start the search. + * + * @param url if given, this single URL is searched - ignoring query->searchInDirs() + */ + void start(const QUrl &url = QUrl()); + /** Stop the ongoing search. */ void stop(); + /** + * Return the found files. + * Owner is this file searcher, they are deleted when re-starting the search. + */ + QList files() const { return m_foundFiles; } private: void scanUrl(const QUrl &url); @@ -60,20 +72,21 @@ signals: void searching(const QString &url); void found(const FileItem &file, const QString &foundText); - // NOTE: unused void error(const QUrl &url); void finished(); private slots: void slotProcessEvents(bool &stopped); private: - KRQuery *m_query; + const KRQuery m_query; + DefaultFileSystem *m_defaultFileSystem; VirtualFileSystem *m_virtualFileSystem; bool m_stopSearch; + QList m_foundFiles; QStack m_scannedUrls; QStack m_unScannedUrls; QTime m_timer; diff --git a/krusader/Search/krsearchmod.cpp b/krusader/FileSystem/filesearcher.cpp rename from krusader/Search/krsearchmod.cpp rename to krusader/FileSystem/filesearcher.cpp --- a/krusader/Search/krsearchmod.cpp +++ b/krusader/FileSystem/filesearcher.cpp @@ -19,7 +19,7 @@ * along with Krusader. If not, see [http://www.gnu.org/licenses/]. * *****************************************************************************/ -#include "krsearchmod.h" +#include "filesearcher.h" // QtCore #include @@ -45,54 +45,55 @@ extern KRarcHandler arcHandler; -KRSearchMod::KRSearchMod(const KRQuery *query) - : m_defaultFileSystem(nullptr), m_virtualFileSystem(nullptr), m_stopSearch(false) +FileSearcher::FileSearcher(const KRQuery &query) + : m_query(query), m_defaultFileSystem(nullptr), m_virtualFileSystem(nullptr) { - m_query = new KRQuery(*query); - connect(m_query, &KRQuery::status, this, &KRSearchMod::searching); - connect(m_query, &KRQuery::processEvents, this, &KRSearchMod::slotProcessEvents); + connect(&m_query, &KRQuery::status, this, &FileSearcher::searching); + connect(&m_query, &KRQuery::processEvents, this, &FileSearcher::slotProcessEvents); } -KRSearchMod::~KRSearchMod() +FileSearcher::~FileSearcher() { - delete m_query; if (m_defaultFileSystem) delete m_defaultFileSystem; if (m_virtualFileSystem) delete m_virtualFileSystem; } -void KRSearchMod::start() +void FileSearcher::start(const QUrl &url) { + m_foundFiles.clear(); m_unScannedUrls.clear(); m_scannedUrls.clear(); m_timer.start(); - - const QList whereToSearch = m_query->searchInDirs(); + m_stopSearch = false; // search every dir that needs to be searched - for (int i = 0; i < whereToSearch.count(); ++i) - scanUrl(whereToSearch[i]); + const QList urls = url.isEmpty() ? m_query.searchInDirs() : QList() << url; + for (const QUrl url : urls) { + if (m_stopSearch) + break; + + scanUrl(url); + } emit finished(); } -void KRSearchMod::stop() { m_stopSearch = true; } +void FileSearcher::stop() { m_stopSearch = true; } -void KRSearchMod::scanUrl(const QUrl &url) +void FileSearcher::scanUrl(const QUrl &url) { - if (m_stopSearch) - return; m_unScannedUrls.push(url); while (!m_unScannedUrls.isEmpty()) { - const QUrl url = m_unScannedUrls.pop(); - if (m_stopSearch) return; - if (m_query->isExcluded(url)) { - if (!m_query->searchInDirs().contains(url)) + const QUrl url = m_unScannedUrls.pop(); + + if (m_query.isExcluded(url)) { + if (!m_query.searchInDirs().contains(url)) continue; } @@ -108,11 +109,11 @@ } } -void KRSearchMod::scanDirectory(const QUrl &url) +void FileSearcher::scanDirectory(const QUrl &url) { FileSystem *fileSystem = getFileSystem(url); - // create file items + // create file items, deletes old ones const bool refreshed = fileSystem->scanDir(url); if (!refreshed) { emit error(url); @@ -122,13 +123,17 @@ for (FileItem *fileItem : fileSystem->fileItems()) { const QUrl fileUrl = fileItem->getUrl(); - if (m_query->isRecursive() && - (fileItem->isDir() || (fileItem->isSymLink() && m_query->followLinks()))) { + if (m_query.ignoreHidden() && fileUrl.fileName().startsWith('.')) + // ignore hidden files and directories + continue; + + if (m_query.isRecursive() && + (fileItem->isDir() || (fileItem->isSymLink() && m_query.followLinks()))) { // query search in subdirectory m_unScannedUrls.push(fileUrl); } - if (m_query->searchInArchives() && fileUrl.isLocalFile() && + if (m_query.searchInArchives() && fileUrl.isLocalFile() && KRarcHandler::arcSupported(fileItem->getMime())) { // query search in archive; NOTE: only supported for local files QUrl archiveURL = fileUrl; @@ -141,9 +146,10 @@ } } - if (m_query->match(fileItem)) { + if (m_query.match(fileItem)) { // found! - emit found(*fileItem, m_query->foundText()); // emitting copy of file item + m_foundFiles.append(fileItem); + emit found(*fileItem, m_query.foundText()); // emitting copy of file item } if (m_timer.elapsed() >= EVENT_PROCESS_DELAY) { @@ -155,7 +161,7 @@ } } -FileSystem *KRSearchMod::getFileSystem(const QUrl &url) +FileSystem *FileSearcher::getFileSystem(const QUrl &url) { FileSystem *fileSystem; if (url.scheme() == QStringLiteral("virt")) { @@ -170,7 +176,7 @@ return fileSystem; } -void KRSearchMod::slotProcessEvents(bool &stopped) +void FileSearcher::slotProcessEvents(bool &stopped) { qApp->processEvents(); stopped = m_stopSearch; diff --git a/krusader/FileSystem/krquery.h b/krusader/FileSystem/krquery.h --- a/krusader/FileSystem/krquery.h +++ b/krusader/FileSystem/krquery.h @@ -74,12 +74,12 @@ bool isCaseSensitive() { return matchesCaseSensitive; } // returns if the filter is null (was cancelled) - bool isNull() { return bNull; } + bool isNull() const { return bNull; } // sets the content part of the query void setContent(const QString &content, bool cs = true, bool wholeWord = false, QString encoding = QString(), bool regExp = false); - const QString content() { return contain; } + const QString content() const { return contain; } // sets the minimum file size limit void setMinimumFileSize(KIO::filesize_t); @@ -107,35 +107,39 @@ // in the member QStringList customType void setMimeType(const QString &typeIn, QStringList customList = QStringList()); // true if setMimeType was called - bool hasMimeType() { return type.isEmpty(); } + bool hasMimeType() const { return type.isEmpty(); } // sets the search in archive flag - void setSearchInArchives(bool flag) { inArchive = flag; } + void setSearchInArchives(bool flag) { m_inArchive = flag; } // gets the search in archive flag - bool searchInArchives() { return inArchive; } + bool searchInArchives() const { return m_inArchive; } // sets the recursive flag - void setRecursive(bool flag) { recurse = flag; } + void setRecursive(bool flag) { m_recurse = flag; } // gets the recursive flag - bool isRecursive() { return recurse; } + bool isRecursive() const { return m_recurse; } // sets whether to follow symbolic links - void setFollowLinks(bool flag) { followLinksP = flag; } + void setFollowLinks(bool flag) { m_followLinks = flag; } // gets whether to follow symbolic links - bool followLinks() { return followLinksP; } + bool followLinks() const { return m_followLinks; } + // sets whether to ignore hidden files/folders + void setIgnoreHidden(bool flag) { m_ignoreHidden = flag; } + // gets whether to ignore hidden files/folders + bool ignoreHidden() const { return m_ignoreHidden; } // sets the folder names which the searcher will exclude from traversing void setExcludeFolderNames(const QStringList &urls); // gets the folder names which the searcher excludes const QStringList excludeFolderNames() { return excludedFolderNames; } // sets the folders where the searcher will search void setSearchInDirs(const QList &urls); // gets the folders where the searcher searches - const QList &searchInDirs() { return whereToSearch; } + const QList &searchInDirs() const { return m_whereToSearch; } // sets the folders where search is not permitted void setDontSearchInDirs(const QList &urls); // gets the folders where search is not permitted - const QList &dontSearchInDirs() { return whereNotToSearch; } + const QList &dontSearchInDirs() const { return m_whereNotToSearch; } // checks if a URL is excluded - bool isExcluded(const QUrl &url); + bool isExcluded(const QUrl &url) const ; // gives whether we search for content bool isContentSearched() const { return !contain.isEmpty(); } @@ -177,13 +181,14 @@ QString type; QStringList customType; - bool inArchive; // if true- search in archive. - bool recurse; // if true recurse ob sub-dirs... - bool followLinksP; + bool m_inArchive; // if true- search in archive. + bool m_recurse; // if true recurse ob sub-dirs... + bool m_followLinks; + bool m_ignoreHidden; QStringList excludedFolderNames; // substrings of paths where not to search - QList whereToSearch; // directories to search - QList whereNotToSearch; // directories NOT to search + QList m_whereToSearch; // directories to search + QList m_whereNotToSearch; // directories NOT to search signals: void status(const QString &name); @@ -198,6 +203,7 @@ bool checkBuffer(const char *data, int len) const; bool checkTimer() const; QStringList split(QString); + static QString getFileName(const QString &name); private slots: void containsContentData(KIO::Job *, const QByteArray &); diff --git a/krusader/FileSystem/krquery.cpp b/krusader/FileSystem/krquery.cpp --- a/krusader/FileSystem/krquery.cpp +++ b/krusader/FileSystem/krquery.cpp @@ -45,8 +45,9 @@ : QObject(), matchesCaseSensitive(true), bNull(true), contain(QString()), containCaseSensetive(true), containWholeWord(false), containRegExp(false), minSize(0), maxSize(0), newerThen(0), olderThen(0), owner(QString()), group(QString()), perm(QString()), - type(QString()), inArchive(false), recurse(true), followLinksP(true), receivedBuffer(0), - receivedBufferLen(0), processEventsConnected(0), codec(QTextCodec::codecForLocale()) + type(QString()), m_inArchive(false), m_recurse(true), m_followLinks(true), + m_ignoreHidden(false), receivedBuffer(0), receivedBufferLen(0), processEventsConnected(0), + codec(QTextCodec::codecForLocale()) { QChar ch = '\n'; QTextCodec::ConverterState state(QTextCodec::IgnoreHeader); @@ -60,8 +61,9 @@ : QObject(), bNull(true), contain(QString()), containCaseSensetive(true), containWholeWord(false), containRegExp(false), minSize(0), maxSize(0), newerThen(0), olderThen(0), owner(QString()), group(QString()), perm(QString()), type(QString()), - inArchive(false), recurse(true), followLinksP(true), receivedBuffer(0), receivedBufferLen(0), - processEventsConnected(0), codec(QTextCodec::codecForLocale()) + m_inArchive(false), m_recurse(true), m_followLinks(true), m_ignoreHidden(false), + receivedBuffer(0), receivedBufferLen(0), processEventsConnected(0), + codec(QTextCodec::codecForLocale()) { QChar ch = '\n'; QTextCodec::ConverterState state(QTextCodec::IgnoreHeader); @@ -106,12 +108,12 @@ perm = old.perm; type = old.type; customType = old.customType; - inArchive = old.inArchive; - recurse = old.recurse; - followLinksP = old.followLinksP; - whereToSearch = old.whereToSearch; - excludedFolderNames = old.excludedFolderNames; - whereNotToSearch = old.whereNotToSearch; + m_inArchive = old.m_inArchive; + m_recurse = old.m_recurse; + m_followLinks = old.m_followLinks; + m_ignoreHidden = old.m_ignoreHidden; + m_whereToSearch = old.m_whereToSearch; + m_whereNotToSearch = old.m_whereNotToSearch; origFilter = old.origFilter; codec = old.codec; @@ -153,9 +155,10 @@ LOAD("Perm", perm); LOAD("Type", type); LOAD("CustomType", customType); - LOAD("InArchive", inArchive); - LOAD("Recurse", recurse); - LOAD("FollowLinks", followLinksP); + LOAD("InArchive", m_inArchive); + LOAD("Recurse", m_recurse); + LOAD("FollowLinks", m_followLinks); + LOAD("IgnoreHidden", m_ignoreHidden); // KF5 TODO? // LOAD("WhereToSearch", whereToSearch); // LOAD("WhereNotToSearch", whereNotToSearch); @@ -198,9 +201,10 @@ cfg.writeEntry("Perm", perm); cfg.writeEntry("Type", type); cfg.writeEntry("CustomType", customType); - cfg.writeEntry("InArchive", inArchive); - cfg.writeEntry("Recurse", recurse); - cfg.writeEntry("FollowLinks", followLinksP); + cfg.writeEntry("InArchive", m_inArchive); + cfg.writeEntry("Recurse", m_recurse); + cfg.writeEntry("FollowLinks", m_followLinks); + cfg.writeEntry("IgnoreHidden", m_ignoreHidden); // KF5 TODO? // cfg.writeEntry("WhereToSearch", whereToSearch); // cfg.writeEntry("WhereNotToSearch", whereNotToSearch); @@ -321,6 +325,9 @@ // check permission if (!perm.isEmpty() && !checkPerm(item->getPerm())) return false; + // check hidden + if (m_ignoreHidden && item->getUrl().fileName().startsWith('.')) + return false; if (!contain.isEmpty()) { if ((totalBytes = item->getSize()) == 0) @@ -731,15 +738,15 @@ customType = customList; } -bool KRQuery::isExcluded(const QUrl &url) +bool KRQuery::isExcluded(const QUrl &url) const { - for (QUrl &item : whereNotToSearch) - if (item.isParentOf(url) || url.matches(item, QUrl::StripTrailingSlash)) + for (const QUrl excludedUrl: m_whereNotToSearch) + if (excludedUrl.isParentOf(url) || url.matches(excludedUrl, QUrl::StripTrailingSlash)) return true; // Exclude folder names that are configured in settings - QString filename = url.fileName(); - for (QString &item : excludedFolderNames) + const QString filename = url.fileName(); + for (const QString &item : excludedFolderNames) if (filename == item) return true; @@ -751,23 +758,23 @@ void KRQuery::setSearchInDirs(const QList &urls) { - whereToSearch.clear(); + m_whereToSearch.clear(); for (int i = 0; i < urls.count(); ++i) { QString url = urls[i].url(); QUrl completed = QUrl::fromUserInput(KUrlCompletion::replacedPath(url, true, true), QString(), QUrl::AssumeLocalFile); - whereToSearch.append(completed); + m_whereToSearch.append(completed); } } void KRQuery::setDontSearchInDirs(const QList &urls) { - whereNotToSearch.clear(); + m_whereNotToSearch.clear(); for (int i = 0; i < urls.count(); ++i) { QString url = urls[i].url(); QUrl completed = QUrl::fromUserInput(KUrlCompletion::replacedPath(url, true, true), QString(), QUrl::AssumeLocalFile); - whereNotToSearch.append(completed); + m_whereNotToSearch.append(completed); } } void KRQuery::setExcludeFolderNames(const QStringList &paths) diff --git a/krusader/Filter/filtersettings.cpp b/krusader/Filter/filtersettings.cpp --- a/krusader/Filter/filtersettings.cpp +++ b/krusader/Filter/filtersettings.cpp @@ -257,7 +257,7 @@ KRQuery FilterSettings::toQuery() const { - if(!isValid()) + if (!isValid()) return KRQuery(); KRQuery query; diff --git a/krusader/Filter/filtertabs.h b/krusader/Filter/filtertabs.h --- a/krusader/Filter/filtertabs.h +++ b/krusader/Filter/filtertabs.h @@ -53,11 +53,11 @@ FilterSettings getSettings(); void applySettings(const FilterSettings &s); void reset(); + KRQuery query(); public slots: void loadFromProfile(QString); void saveToProfile(QString); - bool fillQuery(KRQuery *query); void close(bool accept = true) { emit closeRequest(accept); } diff --git a/krusader/Filter/filtertabs.cpp b/krusader/Filter/filtertabs.cpp --- a/krusader/Filter/filtertabs.cpp +++ b/krusader/Filter/filtertabs.cpp @@ -127,11 +127,9 @@ } } -bool FilterTabs::fillQuery(KRQuery *query) +KRQuery FilterTabs::query() { - *query = getSettings().toQuery(); - - return !query->isNull(); + return getSettings().toQuery(); } FilterBase * FilterTabs::get(QString name) diff --git a/krusader/Search/CMakeLists.txt b/krusader/Search/CMakeLists.txt --- a/krusader/Search/CMakeLists.txt +++ b/krusader/Search/CMakeLists.txt @@ -1,7 +1,6 @@ include_directories(${KF5_INCLUDES_DIRS} ${QT_INCLUDES}) set(Search_SRCS - krsearchmod.cpp krsearchdialog.cpp) add_library(Search STATIC ${Search_SRCS}) diff --git a/krusader/Search/krsearchdialog.h b/krusader/Search/krsearchdialog.h --- a/krusader/Search/krsearchdialog.h +++ b/krusader/Search/krsearchdialog.h @@ -31,15 +31,16 @@ #include #include +#include "../FileSystem/krquery.h" + class FileItem; +class FileSearcher; class FilterTabs; class GeneralFilter; class KrSearchBar; class KrSqueezedTextLabel; class KrView; class KrViewItem; -class KRQuery; -class KRSearchMod; class KSqueezedTextLabel; class ProfileManager; class SearchResultContainer; @@ -107,8 +108,8 @@ KrView *resultView; KrSearchBar *searchBar; - KRQuery *query; - KRSearchMod *searcher; + KRQuery query; + FileSearcher *searcher; bool isBusy; bool closed; diff --git a/krusader/Search/krsearchdialog.cpp b/krusader/Search/krsearchdialog.cpp --- a/krusader/Search/krsearchdialog.cpp +++ b/krusader/Search/krsearchdialog.cpp @@ -42,11 +42,11 @@ #include #include -#include "krsearchmod.h" #include "../Dialogs/krdialogs.h" #include "../Dialogs/krspecialwidgets.h" #include "../Dialogs/krsqueezedtextlabel.h" #include "../FileSystem/fileitem.h" +#include "../FileSystem/filesearcher.h" #include "../FileSystem/krquery.h" #include "../FileSystem/virtualfilesystem.h" #include "../Filter/filtertabs.h" @@ -130,7 +130,7 @@ // class starts here ///////////////////////////////////////// KrSearchDialog::KrSearchDialog(QString profile, QWidget* parent) - : QDialog(parent), query(0), searcher(0), isBusy(false), closed(false) + : QDialog(parent), searcher(0), isBusy(false), closed(false) { KConfigGroup group(krConfig, "Search"); @@ -320,8 +320,6 @@ KrSearchDialog::~KrSearchDialog() { - delete query; - query = 0; delete resultView; resultView = 0; } @@ -390,14 +388,9 @@ bool KrSearchDialog::gui2query() { - // prepare the query ... - /////////////////// names, locations and greps - if (query != 0) { - delete query; query = 0; - } - query = new KRQuery(); + query = filterTabs->query(); - return filterTabs->fillQuery(query); + return !query.isNull(); } void KrSearchDialog::startSearch() @@ -409,7 +402,7 @@ if (!gui2query()) return; // first, informative messages - if (query->searchInArchives()) { + if (query.searchInArchives()) { KMessageBox::information(this, i18n("Since you chose to also search in archives, " "note the following limitations:\n" "You cannot search for text (grep) while doing" @@ -435,10 +428,10 @@ // start the search. if (searcher != 0) abort(); - searcher = new KRSearchMod(query); + searcher = new FileSearcher(query); connect(searcher, SIGNAL(searching(QString)), searchingLabel, SLOT(setText(QString))); - connect(searcher, &KRSearchMod::found, this, &KrSearchDialog::slotFound); + connect(searcher, &FileSearcher::found, this, &KrSearchDialog::slotFound); connect(searcher, SIGNAL(finished()), this, SLOT(stopSearch())); searcher->start(); @@ -600,12 +593,13 @@ KConfigGroup group(krConfig, "Search"); int listBoxNum = group.readEntry("Feed To Listbox Counter", 1); QString queryName; - if(query) { - QString where = KrServices::toStringList(query->searchInDirs()).join(", "); - if(query->content().isEmpty()) - queryName = i18n("Search results for \"%1\" in %2", query->nameFilter(), where); + if (!query.isNull()) { + QString where = KrServices::toStringList(query.searchInDirs()).join(", "); + if (query.content().isEmpty()) + queryName = i18n("Search results for \"%1\" in %2", query.nameFilter(), where); else - queryName = i18n("Search results for \"%1\" containing \"%2\" in %3", query->nameFilter(), query->content(), where); + queryName = i18n("Search results for \"%1\" containing \"%2\" in %3", + query.nameFilter(), query.content(), where); } QString fileSystemName; do { diff --git a/krusader/Synchronizer/CMakeLists.txt b/krusader/Synchronizer/CMakeLists.txt --- a/krusader/Synchronizer/CMakeLists.txt +++ b/krusader/Synchronizer/CMakeLists.txt @@ -6,7 +6,9 @@ synchronizergui.cpp feedtolistboxdialog.cpp synchronizertask.cpp - synchronizerdirlist.cpp) + synchronizerdirlist.cpp + synchronizerfileitem.cpp +) add_library(Synchronizer STATIC ${Synchronizer_SRCS}) diff --git a/krusader/Synchronizer/feedtolistboxdialog.h b/krusader/Synchronizer/feedtolistboxdialog.h --- a/krusader/Synchronizer/feedtolistboxdialog.h +++ b/krusader/Synchronizer/feedtolistboxdialog.h @@ -35,7 +35,7 @@ Q_OBJECT public: - FeedToListBoxDialog(QWidget*, Synchronizer *, QTreeWidget *, bool); + FeedToListBoxDialog(QWidget *, Synchronizer *, QTreeWidget *, bool); virtual ~FeedToListBoxDialog() {} bool isAccepted() { @@ -46,13 +46,13 @@ void slotOk(); private: - Synchronizer * synchronizer; - QTreeWidget * syncList; - QCheckBox * cbSelected; - QLineEdit * lineEdit; - QComboBox * sideCombo; - bool equalAllowed; - bool accepted; + Synchronizer *synchronizer; + QTreeWidget *syncList; + QCheckBox *cbSelected; + QLineEdit *lineEdit; + QComboBox *sideCombo; + bool equalAllowed; + bool accepted; }; #endif /* __FEED_TO_LISTBOX_DIALOG__ */ diff --git a/krusader/Synchronizer/feedtolistboxdialog.cpp b/krusader/Synchronizer/feedtolistboxdialog.cpp --- a/krusader/Synchronizer/feedtolistboxdialog.cpp +++ b/krusader/Synchronizer/feedtolistboxdialog.cpp @@ -19,6 +19,7 @@ *****************************************************************************/ #include "feedtolistboxdialog.h" + #include "synchronizer.h" #include "synchronizergui.h" #include "../FileSystem/filesystem.h" @@ -29,23 +30,23 @@ // QtWidgets #include +#include #include -#include #include -#include +#include #include #include #include #include -#define S_LEFT 0 -#define S_RIGHT 1 -#define S_BOTH 2 +#define S_LEFT 0 +#define S_RIGHT 1 +#define S_BOTH 2 -FeedToListBoxDialog::FeedToListBoxDialog(QWidget *parent, Synchronizer *sync, - QTreeWidget *syncL, bool equOK) : QDialog(parent), - synchronizer(sync), syncList(syncL), equalAllowed(equOK), accepted(false) +FeedToListBoxDialog::FeedToListBoxDialog(QWidget *parent, Synchronizer *sync, QTreeWidget *syncL, + bool equOK) + : QDialog(parent), synchronizer(sync), syncList(syncL), equalAllowed(equOK), accepted(false) { setWindowTitle(i18n("Krusader::Feed to listbox")); @@ -63,18 +64,18 @@ QTreeWidgetItemIterator it(syncList); while (*it) { - SynchronizerGUI::SyncViewItem *item = (SynchronizerGUI::SyncViewItem *) * it; + SyncViewItem *item = (SyncViewItem *)*it; SynchronizerFileItem *syncItem = item->synchronizerItemRef(); if (syncItem && syncItem->isMarked()) { if (item->isSelected() || syncItem->task() != TT_EQUALS || equalAllowed) { itemNum++; if (item->isSelected()) selectedNum++; - if (syncItem->existsInLeft()) + if (syncItem->existsLeft()) leftExistingNum++; - if (syncItem->existsInRight()) + if (syncItem->existsRight()) rightExistingNum++; } } @@ -112,7 +113,7 @@ lineEdit->selectAll(); mainLayout->addWidget(lineEdit); - QHBoxLayout * hbox = new QHBoxLayout; + QHBoxLayout *hbox = new QHBoxLayout; QLabel *label2 = new QLabel(i18n("Side to feed:"), this); label2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -147,7 +148,8 @@ mainLayout->addLayout(hbox); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QDialogButtonBox *buttonBox = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); mainLayout->addWidget(buttonBox); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); @@ -168,8 +170,8 @@ QList urlList; QTreeWidgetItemIterator it(syncList); - for (;*it; it++) { - SynchronizerGUI::SyncViewItem *item = (SynchronizerGUI::SyncViewItem *) * it; + for (; *it; it++) { + SyncViewItem *item = (SyncViewItem *)*it; SynchronizerFileItem *syncItem = item->synchronizerItemRef(); if (!syncItem || !syncItem->isMarked()) @@ -179,20 +181,24 @@ if (!equalAllowed && syncItem->task() == TT_EQUALS && (!selected || !item->isSelected())) continue; - if ((side == S_BOTH || side == S_LEFT) && syncItem->existsInLeft()) { - QString leftDirName = syncItem->leftDirectory().isEmpty() ? "" : syncItem->leftDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer->leftBaseDirectory() + leftDirName + syncItem->leftName()); - urlList.push_back(leftURL); + if ((side == S_BOTH || side == S_LEFT) && syncItem->existsLeft()) { + QString leftDirName = + syncItem->leftDirectory().isEmpty() ? "" : syncItem->leftDirectory() + '/'; + const QUrl left = Synchronizer::pathAppend(synchronizer->leftBaseDirectory(), + leftDirName, syncItem->leftName()); + urlList.push_back(left); } - if ((side == S_BOTH || side == S_RIGHT) && syncItem->existsInRight()) { - QString rightDirName = syncItem->rightDirectory().isEmpty() ? "" : syncItem->rightDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer->rightBaseDirectory() + rightDirName + syncItem->rightName()); - urlList.push_back(leftURL); + if ((side == S_BOTH || side == S_RIGHT) && syncItem->existsRight()) { + QString rightDirName = + syncItem->rightDirectory().isEmpty() ? "" : syncItem->rightDirectory() + '/'; + const QUrl right = Synchronizer::pathAppend(synchronizer->rightBaseDirectory(), + rightDirName, syncItem->rightName()); + urlList.push_back(right); } } - QUrl url = QUrl(QString("virt:/") + name); + const QUrl url = Synchronizer::pathAppend(QUrl("virt:/"), name); VirtualFileSystem virtFilesystem; if (!virtFilesystem.refresh(url)) { // create directory if it does not exist KMessageBox::error(parentWidget(), i18n("Cannot open %1.", url.toDisplayString())); @@ -203,4 +209,3 @@ accepted = true; accept(); } - diff --git a/krusader/Synchronizer/synchronizedialog.h b/krusader/Synchronizer/synchronizedialog.h --- a/krusader/Synchronizer/synchronizedialog.h +++ b/krusader/Synchronizer/synchronizedialog.h @@ -22,8 +22,8 @@ #define SYNCHRONIZEDIALOG_H // QtWidgets -#include #include +#include #include #include #include @@ -35,13 +35,11 @@ Q_OBJECT public: - SynchronizeDialog(QWidget*, Synchronizer *sync, - int, KIO::filesize_t, int, KIO::filesize_t, int, KIO::filesize_t, int); + SynchronizeDialog(QWidget *, Synchronizer *sync, int, KIO::filesize_t, int, KIO::filesize_t, + int, KIO::filesize_t, int); ~SynchronizeDialog(); - inline bool wasSyncronizationStarted() { - return syncStarted; - } + inline bool wasSyncronizationStarted() { return syncStarted; } public slots: void startSynchronization(); @@ -51,34 +49,34 @@ void pauseAccepted(); private: - QProgressBar *progress; + QProgressBar *progress; - QCheckBox *cbRightToLeft; - QCheckBox *cbLeftToRight; - QCheckBox *cbDeletable; + QCheckBox *cbRightToLeft; + QCheckBox *cbLeftToRight; + QCheckBox *cbDeletable; - QLabel *lbRightToLeft; - QLabel *lbLeftToRight; - QLabel *lbDeletable; + QLabel *lbRightToLeft; + QLabel *lbLeftToRight; + QLabel *lbDeletable; - QCheckBox *cbOverwrite; + QCheckBox *cbOverwrite; - QPushButton *btnStart; - QPushButton *btnPause; + QPushButton *btnStart; + QPushButton *btnPause; - Synchronizer *synchronizer; + Synchronizer *synchronizer; - int leftCopyNr; - KIO::filesize_t leftCopySize; - int rightCopyNr; - KIO::filesize_t rightCopySize; - int deleteNr; - KIO::filesize_t deleteSize; + int leftCopyNr; + KIO::filesize_t leftCopySize; + int rightCopyNr; + KIO::filesize_t rightCopySize; + int deleteNr; + KIO::filesize_t deleteSize; - int parallelThreads; + int parallelThreads; - bool isPause; - bool syncStarted; + bool isPause; + bool syncStarted; }; #endif /* __SYNCHRONIZE_DIALOG__ */ diff --git a/krusader/Synchronizer/synchronizedialog.cpp b/krusader/Synchronizer/synchronizedialog.cpp --- a/krusader/Synchronizer/synchronizedialog.cpp +++ b/krusader/Synchronizer/synchronizedialog.cpp @@ -19,72 +19,78 @@ *****************************************************************************/ #include "synchronizedialog.h" + #include "../FileSystem/krpermhandler.h" +#include "../defaults.h" #include "../krglobal.h" #include "../icon.h" -#include "../defaults.h" // QtWidgets +#include #include #include -#include #include #include -SynchronizeDialog::SynchronizeDialog(QWidget* parent, - Synchronizer *sync, int pleftCopyNr, KIO::filesize_t pleftCopySize, - int prightCopyNr, KIO::filesize_t prightCopySize, int pdeleteNr, - KIO::filesize_t pdeleteSize, int parThreads) : QDialog(parent), - synchronizer(sync), leftCopyNr(pleftCopyNr), - leftCopySize(pleftCopySize), rightCopyNr(prightCopyNr), - rightCopySize(prightCopySize), deleteNr(pdeleteNr), - deleteSize(pdeleteSize), parallelThreads(parThreads), - isPause(true), syncStarted(false) +SynchronizeDialog::SynchronizeDialog(QWidget *parent, Synchronizer *sync, int pleftCopyNr, + KIO::filesize_t pleftCopySize, int prightCopyNr, + KIO::filesize_t prightCopySize, int pdeleteNr, + KIO::filesize_t pdeleteSize, int parThreads) + : QDialog(parent), synchronizer(sync), leftCopyNr(pleftCopyNr), leftCopySize(pleftCopySize), + rightCopyNr(prightCopyNr), rightCopySize(prightCopySize), deleteNr(pdeleteNr), + deleteSize(pdeleteSize), parallelThreads(parThreads), isPause(true), syncStarted(false) { setWindowTitle(i18n("Krusader::Synchronize")); setModal(true); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(11, 11, 11, 11); layout->setSpacing(6); - cbRightToLeft = new QCheckBox(i18np("Right to left: Copy 1 file", "Right to left: Copy %1 files", leftCopyNr) + ' ' + - i18np("(1 byte)", "(%1 bytes)", KRpermHandler::parseSize(leftCopySize).trimmed().toInt()), - this); + cbRightToLeft = new QCheckBox( + i18np("Right to left: Copy 1 file", "Right to left: Copy %1 files", leftCopyNr) + ' ' + + i18np("(1 byte)", "(%1 bytes)", + KRpermHandler::parseSize(leftCopySize).trimmed().toInt()), + this); cbRightToLeft->setChecked(leftCopyNr != 0); cbRightToLeft->setEnabled(leftCopyNr != 0); layout->addWidget(cbRightToLeft); - lbRightToLeft = new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", leftCopyNr, 0, - 0, KRpermHandler::parseSize(leftCopySize).trimmed()), - this); + lbRightToLeft = + new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", leftCopyNr, 0, + 0, KRpermHandler::parseSize(leftCopySize).trimmed()), + this); lbRightToLeft->setEnabled(leftCopyNr != 0); layout->addWidget(lbRightToLeft); - cbLeftToRight = new QCheckBox(i18np("Left to right: Copy 1 file", "Left to right: Copy %1 files", rightCopyNr) + ' ' + - i18np("(1 byte)", "(%1 bytes)", KRpermHandler::parseSize(rightCopySize).trimmed().toInt()), - this); + cbLeftToRight = new QCheckBox( + i18np("Left to right: Copy 1 file", "Left to right: Copy %1 files", rightCopyNr) + ' ' + + i18np("(1 byte)", "(%1 bytes)", + KRpermHandler::parseSize(rightCopySize).trimmed().toInt()), + this); cbLeftToRight->setChecked(rightCopyNr != 0); cbLeftToRight->setEnabled(rightCopyNr != 0); layout->addWidget(cbLeftToRight); - lbLeftToRight = new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", rightCopyNr, 0, - 0, KRpermHandler::parseSize(rightCopySize).trimmed()), - this); + lbLeftToRight = + new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", rightCopyNr, 0, + 0, KRpermHandler::parseSize(rightCopySize).trimmed()), + this); lbLeftToRight->setEnabled(rightCopyNr != 0); layout->addWidget(lbLeftToRight); - cbDeletable = new QCheckBox(i18np("Left: Delete 1 file", "Left: Delete %1 files", deleteNr) + ' ' + - i18np("(1 byte)", "(%1 bytes)", KRpermHandler::parseSize(deleteSize).trimmed().toInt()), - this); + cbDeletable = new QCheckBox( + i18np("Left: Delete 1 file", "Left: Delete %1 files", deleteNr) + ' ' + + i18np("(1 byte)", "(%1 bytes)", KRpermHandler::parseSize(deleteSize).trimmed().toInt()), + this); cbDeletable->setChecked(deleteNr != 0); cbDeletable->setEnabled(deleteNr != 0); layout->addWidget(cbDeletable); - lbDeletable = new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", deleteNr, 0, - 0, KRpermHandler::parseSize(deleteSize).trimmed()), - this); + lbDeletable = new QLabel(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", + deleteNr, 0, 0, KRpermHandler::parseSize(deleteSize).trimmed()), + this); lbDeletable->setEnabled(deleteNr != 0); layout->addWidget(lbDeletable); @@ -96,16 +102,16 @@ layout->addWidget(progress); QWidget *hboxWidget = new QWidget(this); - QHBoxLayout * hbox = new QHBoxLayout(hboxWidget); + QHBoxLayout *hbox = new QHBoxLayout(hboxWidget); hbox->setSpacing(6); cbOverwrite = new QCheckBox(i18n("Confirm overwrites"), this); KConfigGroup group(krConfig, "Synchronize"); cbOverwrite->setChecked(group.readEntry("Confirm overwrites", _ConfirmOverWrites)); layout->addWidget(cbOverwrite); - QSpacerItem* spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); hbox->addItem(spacer); btnStart = new QPushButton(hboxWidget); @@ -126,9 +132,9 @@ layout->addWidget(hboxWidget); - connect(btnStart, SIGNAL(clicked()), this, SLOT(startSynchronization())); - connect(btnPause, SIGNAL(clicked()), this, SLOT(pauseOrResume())); - connect(btnClose, SIGNAL(clicked()), this, SLOT(reject())); + connect(btnStart, SIGNAL(clicked()), this, SLOT(startSynchronization())); + connect(btnPause, SIGNAL(clicked()), this, SLOT(pauseOrResume())); + connect(btnClose, SIGNAL(clicked()), this, SLOT(reject())); exec(); } @@ -143,44 +149,48 @@ { btnStart->setEnabled(false); btnPause->setEnabled(syncStarted = true); - connect(synchronizer, SIGNAL(synchronizationFinished()), this, SLOT(synchronizationFinished())); - connect(synchronizer, SIGNAL(processedSizes(int,KIO::filesize_t,int,KIO::filesize_t,int,KIO::filesize_t)), - this, SLOT(processedSizes(int,KIO::filesize_t,int,KIO::filesize_t,int,KIO::filesize_t))); - connect(synchronizer, SIGNAL(pauseAccepted()), this, SLOT(pauseAccepted())); - - if (!cbRightToLeft->isChecked()) leftCopySize = 0; - if (!cbLeftToRight->isChecked()) rightCopySize = 0; - if (!cbDeletable->isChecked()) deleteSize = 0; + connect(synchronizer, SIGNAL(synchronizationFinished()), this, SLOT(synchronizationFinished())); + connect(synchronizer, SIGNAL(processedSizes(int, KIO::filesize_t, int, KIO::filesize_t, int, + KIO::filesize_t)), + this, + SLOT(processedSizes(int, KIO::filesize_t, int, KIO::filesize_t, int, KIO::filesize_t))); + connect(synchronizer, SIGNAL(pauseAccepted()), this, SLOT(pauseAccepted())); + + if (!cbRightToLeft->isChecked()) + leftCopySize = 0; + if (!cbLeftToRight->isChecked()) + rightCopySize = 0; + if (!cbDeletable->isChecked()) + deleteSize = 0; synchronizer->synchronize(this, cbRightToLeft->isChecked(), cbLeftToRight->isChecked(), cbDeletable->isChecked(), !cbOverwrite->isChecked(), parallelThreads); } -void SynchronizeDialog::synchronizationFinished() -{ - QDialog::reject(); -} +void SynchronizeDialog::synchronizationFinished() { QDialog::reject(); } void SynchronizeDialog::processedSizes(int leftNr, KIO::filesize_t leftSize, int rightNr, - KIO::filesize_t rightSize, int delNr, KIO::filesize_t delSize) + KIO::filesize_t rightSize, int delNr, + KIO::filesize_t delSize) { - lbRightToLeft->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", leftCopyNr, leftNr, - KRpermHandler::parseSize(leftSize).trimmed(), - KRpermHandler::parseSize(leftCopySize).trimmed())); - lbLeftToRight->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", rightCopyNr, rightNr, - KRpermHandler::parseSize(rightSize).trimmed(), - KRpermHandler::parseSize(rightCopySize).trimmed())); - lbDeletable->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", deleteNr, delNr, - KRpermHandler::parseSize(delSize).trimmed(), - KRpermHandler::parseSize(deleteSize).trimmed())); - - KIO::filesize_t totalSum = leftCopySize + rightCopySize + deleteSize; - KIO::filesize_t processedSum = leftSize + rightSize + delSize; + lbRightToLeft->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", + leftCopyNr, leftNr, KRpermHandler::parseSize(leftSize).trimmed(), + KRpermHandler::parseSize(leftCopySize).trimmed())); + lbLeftToRight->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", + rightCopyNr, rightNr, + KRpermHandler::parseSize(rightSize).trimmed(), + KRpermHandler::parseSize(rightCopySize).trimmed())); + lbDeletable->setText(i18np("\tReady: %2/1 file, %3/%4", "\tReady: %2/%1 files, %3/%4", deleteNr, + delNr, KRpermHandler::parseSize(delSize).trimmed(), + KRpermHandler::parseSize(deleteSize).trimmed())); + + KIO::filesize_t totalSum = leftCopySize + rightCopySize + deleteSize; + KIO::filesize_t processedSum = leftSize + rightSize + delSize; if (totalSum == 0) totalSum++; - progress->setValue((int)(((double)processedSum / (double)totalSum)*1000)); + progress->setValue((int)(((double)processedSum / (double)totalSum) * 1000)); } void SynchronizeDialog::pauseOrResume() @@ -201,4 +211,3 @@ btnPause->setEnabled(true); isPause = false; } - diff --git a/krusader/Synchronizer/synchronizer.h b/krusader/Synchronizer/synchronizer.h --- a/krusader/Synchronizer/synchronizer.h +++ b/krusader/Synchronizer/synchronizer.h @@ -22,114 +22,122 @@ #define SYNCHRONIZER_H // QtCore -#include -#include #include +#include +#include // QtGui #include // QtWidgets #include #include -# include "synchronizertask.h" #include "synchronizerfileitem.h" +#include "synchronizertask.h" -class KRQuery; class FileItem; +class KRQuery; class Synchronizer : public QObject { Q_OBJECT private: - int displayUpdateCount; // the display is refreshed after every x-th change + int displayUpdateCount; // the display is refreshed after every x-th change public: Synchronizer(); ~Synchronizer(); - int compare(QString leftURL, QString rightURL, KRQuery *query, bool subDirs, bool symLinks, - bool igDate, bool asymm, bool cmpByCnt, bool igCase, bool autoSc, QStringList &selFiles, - int equThres, int timeOffs, int parThreads, bool hiddenFiles); - void stop() { - stopped = true; - } - void setMarkFlags(bool left, bool equal, bool differs, bool right, bool dup, bool sing, bool del); - int refresh(bool nostatus = false); - bool totalSizes(int *, KIO::filesize_t *, int *, KIO::filesize_t *, int *, KIO::filesize_t *); - void synchronize(QWidget *, bool leftCopyEnabled, bool rightCopyEnabled, bool deleteEnabled, - bool overWrite, int parThreads); - void synchronizeWithKGet(); - void setScrolling(bool scroll); - void pause(); - void resume(); - void swapSides(); - void reset(); - void clearLists(); - - void exclude(SynchronizerFileItem *); - void restore(SynchronizerFileItem *); - void reverseDirection(SynchronizerFileItem *); - void copyToLeft(SynchronizerFileItem *); - void copyToRight(SynchronizerFileItem *); - void deleteLeft(SynchronizerFileItem *); - - QString leftBaseDirectory(); - QString rightBaseDirectory(); + + int compare(const QUrl &left, const QUrl &right, KRQuery *query, bool subDirs, bool symLinks, + bool igDate, bool asymm, bool cmpByCnt, bool igCase, bool autoSc, + QStringList &selFiles, int equThres, int timeOffs, int parThreads, + bool hiddenFiles); + void stop() { stopped = true; } + void setMarkFlags(bool left, bool equal, bool differs, bool right, bool dup, bool sing, + bool del); + int refresh(bool nostatus = false); + bool totalSizes(int *, KIO::filesize_t *, int *, KIO::filesize_t *, int *, KIO::filesize_t *); + + void synchronize(QWidget *syncDialog, bool leftCopyEnabled, bool rightCopyEnabled, + bool deleteEnabled, bool overWrite, int parThreads); + /** + * Execute sync with KGet. + * + * This is only supported for downloading files from one remote side other local side. + * Local destination files (if exist) are removed before downloading! + */ + void synchronizeWithKGet(); + + void setScrolling(bool scroll); + void pause(); + void resume(); + void swapSides(); + void reset(); + void clearLists(); + + void exclude(SynchronizerFileItem *); + void restore(SynchronizerFileItem *); + void reverseDirection(SynchronizerFileItem *); + void copyToLeft(SynchronizerFileItem *); + void copyToRight(SynchronizerFileItem *); + void deleteLeft(SynchronizerFileItem *); + + const QUrl leftBaseDirectory() { return leftBaseDir; } + const QUrl rightBaseDirectory() { return rightBaseDir; } + + static QUrl pathAppend(const QUrl &url, const QString &fileName); + static QUrl pathAppend(const QUrl &url, const QString &dirName, const QString &fileName); + static QString getTaskTypeName(TaskType taskType); - static QUrl fsUrl(QString strUrl); + SynchronizerFileItem *getItemAt(unsigned ndx); - void setParentWidget(QWidget * widget) { - parentWidget = widget; - } - void compareContentResult(SynchronizerFileItem * item, bool result); + void setParentWidget(QWidget *widget) { parentWidget = widget; } + void compareContentResult(SynchronizerFileItem *item, bool result); signals: - void comparedFileData(SynchronizerFileItem *); - void markChanged(SynchronizerFileItem *, bool); - void synchronizationFinished(); - void processedSizes(int, KIO::filesize_t, int, KIO::filesize_t, int, KIO::filesize_t); - void pauseAccepted(); - void statusInfo(QString); + void comparedFileData(SynchronizerFileItem *); + void markChanged(SynchronizerFileItem *, bool); + void synchronizationFinished(); + void processedSizes(int, KIO::filesize_t, int, KIO::filesize_t, int, KIO::filesize_t); + void pauseAccepted(); + void statusInfo(QString); public slots: - void slotTaskFinished(KJob*); - void slotProcessedSize(KJob * , qulonglong); + void slotTaskFinished(KJob *); + void slotProcessedSize(KJob *, qulonglong); private: - bool isDir(const FileItem * file); - QString readLink(const FileItem * file); - - void compareDirectory(SynchronizerFileItem *, SynchronizerDirList *, SynchronizerDirList *, - const QString &leftDir, const QString &rightDir); - void addSingleDirectory(SynchronizerFileItem *, SynchronizerDirList *, const QString &, bool); - SynchronizerFileItem * addItem(SynchronizerFileItem *, const QString &, const QString &, - const QString &, const QString &, bool, bool, KIO::filesize_t, - KIO::filesize_t, time_t, time_t, const QString &, const QString &, - const QString &, const QString &, const QString &, const QString &, - mode_t, mode_t, const QString &, const QString &, TaskType, bool, bool); - SynchronizerFileItem * addLeftOnlyItem(SynchronizerFileItem *, const QString &, const QString &, - KIO::filesize_t, time_t, const QString &, const QString &, - const QString &, mode_t, const QString &, bool isDir = false, bool isTemp = false); - SynchronizerFileItem * addRightOnlyItem(SynchronizerFileItem *, const QString &, const QString &, - KIO::filesize_t, time_t, const QString &, const QString &, - const QString &, mode_t, const QString &, bool isDir = false, bool isTemp = false); - SynchronizerFileItem * addDuplicateItem(SynchronizerFileItem *, const QString &, const QString &, - const QString &, const QString &, KIO::filesize_t, - KIO::filesize_t, time_t, time_t, const QString &, - const QString &, const QString &, const QString &, - const QString &, const QString &, mode_t, mode_t, const QString &, - const QString &, bool isDir = false, bool isTemp = false); - bool isMarked(TaskType task, bool dupl); - bool markParentDirectories(SynchronizerFileItem *); - void synchronizeLoop(); - SynchronizerFileItem * getNextTask(); - void executeTask(SynchronizerFileItem * task); - void setPermanent(SynchronizerFileItem *); - void operate(SynchronizerFileItem *item, void (*)(SynchronizerFileItem *)); - void compareLoop(); + bool isDir(const FileItem *file); + + void compareDirectory(SynchronizerFileItem *, SynchronizerDirList *, SynchronizerDirList *, + const QString &leftDir, const QString &rightDir); + + SynchronizerFileItem *addItem(FileItem *leftFile, FileItem *rightFile, + SynchronizerFileItem *parent, const QString &leftDir, + const QString &rightDir, TaskType tsk, bool isTemp); + + SynchronizerFileItem *addLeftOnlyItem(FileItem *leftFile, SynchronizerFileItem *parent, + const QString &dir, bool isTemp = false); + SynchronizerFileItem *addRightOnlyItem(FileItem *rightFile, SynchronizerFileItem *parent, + const QString &dir, bool isTemp = false); + SynchronizerFileItem *addDuplicateItem(FileItem *leftFile, FileItem *rightFile, + SynchronizerFileItem *parent, + const QString &leftDir, const QString &rightDir, + bool isTemp = false); + void addSingleDirectory(SynchronizerFileItem *, SynchronizerDirList *, const QString &, bool); + + bool isMarked(TaskType task, bool dupl); + bool markParentDirectories(SynchronizerFileItem *); + void synchronizeLoop(); + SynchronizerFileItem *getNextTask(); + void executeTask(SynchronizerFileItem *task); + KJob *createJob(SynchronizerFileItem *task, const QUrl &src, const QUrl &url, const QString &link); + void setPermanent(SynchronizerFileItem *); + void operate(SynchronizerFileItem *item, void (*)(SynchronizerFileItem *)); + void compareLoop(); static void excludeOperation(SynchronizerFileItem *item); static void restoreOperation(SynchronizerFileItem *item); @@ -139,62 +147,62 @@ static void deleteLeftOperation(SynchronizerFileItem *item); protected: - bool recurseSubDirs; // walk through subdirectories also - bool followSymLinks; // follow the symbolic links - bool ignoreDate; // don't use date info at comparing - bool asymmetric; // asymmetric directory update - bool cmpByContent; // compare the files by content - bool ignoreCase; // case insensitive synchronization for Windows fs - bool autoScroll; // automatic update of the directory - QList resultList; // the found files - QList temporaryList; // temporary files - QString leftBaseDir; // the left-side base directory - QString rightBaseDir; // the right-side base directory - QStringList excludedPaths; // list of the excluded paths - KRQuery *query; // the filter used for the query - bool stopped; // 'Stop' button was pressed - - int equalsThreshold;// threshold to treat files equal - int timeOffset; // time offset between the left and right sides - bool ignoreHidden; // ignores the hidden files - - bool markEquals; // show the equal files - bool markDiffers; // show the different files - bool markCopyToLeft; // show the files to copy from right to left - bool markCopyToRight;// show the files to copy from left to right - bool markDeletable; // show the files to be deleted - bool markDuplicates; // show the duplicated items - bool markSingles; // show the single items - - bool leftCopyEnabled;// copy to left is enabled at synchronize - bool rightCopyEnabled;// copy to right is enabled at synchronize - bool deleteEnabled; // delete is enabled at synchronize - bool overWrite; // overwrite or query each modification - bool autoSkip; // automatic skipping - bool paused; // pause flag - bool disableNewTasks;// at mkdir the further task creation is disabled - - int leftCopyNr; // the file number copied to left - int rightCopyNr; // the file number copied to right - int deleteNr; // the number of the deleted files - int parallelThreads;// the number of the parallel procesing threads - KIO::filesize_t leftCopySize; // the total size copied to left - KIO::filesize_t rightCopySize; // the total size copied to right - KIO::filesize_t deleteSize; // the size of the deleted files - - int comparedDirs; // the number of the compared directories - int fileCount; // the number of counted files + bool recurseSubDirs; // walk through subdirectories also + bool followSymLinks; // follow the symbolic links + bool ignoreDate; // don't use date info at comparing + bool asymmetric; // asymmetric directory update + bool cmpByContent; // compare the files by content + bool ignoreCase; // case insensitive synchronization for Windows fs + bool autoScroll; // automatic update of the directory + QList resultList; // the found files + QList temporaryList; // temporary files + QUrl leftBaseDir; // the left-side base directory + QUrl rightBaseDir; // the right-side base directory + QStringList excludedPaths; // list of the excluded paths + KRQuery *query; // the filter used for the query + bool stopped; // 'Stop' button was pressed + + int equalsThreshold; // threshold to treat files equal + int timeOffset; // time offset between the left and right sides + bool ignoreHidden; // ignores the hidden files + + bool markEquals; // show the equal files + bool markDiffers; // show the different files + bool markCopyToLeft; // show the files to copy from right to left + bool markCopyToRight; // show the files to copy from left to right + bool markDeletable; // show the files to be deleted + bool markDuplicates; // show the duplicated items + bool markSingles; // show the single items + + bool leftCopyEnabled; // copy to left is enabled at synchronize + bool rightCopyEnabled; // copy to right is enabled at synchronize + bool deleteEnabled; // delete is enabled at synchronize + bool overWrite; // overwrite or query each modification + bool autoSkip; // automatic skipping + bool paused; // pause flag + bool disableNewTasks; // at mkdir the further task creation is disabled + + int leftCopyNr; // the file number copied to left + int rightCopyNr; // the file number copied to right + int deleteNr; // the number of the deleted files + int parallelThreads; // the number of the parallel procesing threads + KIO::filesize_t leftCopySize; // the total size copied to left + KIO::filesize_t rightCopySize; // the total size copied to right + KIO::filesize_t deleteSize; // the size of the deleted files + + int comparedDirs; // the number of the compared directories + int fileCount; // the number of counted files private: - QList stack; // stack for comparing - QMap jobMap; // job maps - QMap receivedMap; // the received file size - SynchronizerFileItem *lastTask; // reference to the last stack - int inTaskFinished; // counter of quasy 'threads' in slotTaskFinished - - QStringList selectedFiles; // the selected files to compare - QWidget *parentWidget; // the parent widget - QWidget *syncDlgWidget; // the synchronizer dialog widget + QList stack; // stack for comparing + QMap jobMap; // job maps + QMap receivedMap; // the received file size + SynchronizerFileItem *lastTask; // reference to the last stack + int inTaskFinished; // counter of quasy 'threads' in slotTaskFinished + + QStringList selectedFiles; // the selected files to compare + QWidget *parentWidget; // the parent widget + QWidget *syncDlgWidget; // the synchronizer dialog widget QListIterator resultListIt; // iterator for result list }; @@ -206,28 +214,22 @@ public: explicit KgetProgressDialog(QWidget *parent = 0, const QString &caption = QString(), - const QString &text = QString(), bool modal = false); + const QString &text = QString(), bool modal = false); - QProgressBar *progressBar() { - return mProgressBar; - } + QProgressBar *progressBar() { return mProgressBar; } public slots: void slotPause(); void slotCancel(); - bool wasCancelled() { - return mCancelled; - } - bool isPaused() { - return mPaused; - } + bool wasCancelled() { return mCancelled; } + bool isPaused() { return mPaused; } private: QProgressBar *mProgressBar; QPushButton *mPauseButton; - bool mCancelled; - bool mPaused; + bool mCancelled; + bool mPaused; }; #endif /* __SYNCHRONIZER_H__ */ diff --git a/krusader/Synchronizer/synchronizer.cpp b/krusader/Synchronizer/synchronizer.cpp --- a/krusader/Synchronizer/synchronizer.cpp +++ b/krusader/Synchronizer/synchronizer.cpp @@ -19,67 +19,59 @@ *****************************************************************************/ #include "synchronizer.h" + #include "synchronizerdirlist.h" -#include "../krglobal.h" -#include "../krservices.h" #include "../FileSystem/filesystem.h" #include "../FileSystem/krquery.h" +#include "../krglobal.h" +#include "../krservices.h" #include // QtCore -#include +#include +#include #include #include -#include +#include #include -#include +#include #include // QtWidgets #include #include #include -#include +#include #include #include #include -#include +#include +#include #include #include #include #include -#include #include #include - #ifdef HAVE_POSIX_ACL #include #ifdef HAVE_NON_POSIX_ACL_EXTENSIONS #include #endif #endif +#define DISPLAY_UPDATE_PERIOD 2 -#define DISPLAY_UPDATE_PERIOD 2 - -Synchronizer::Synchronizer() : displayUpdateCount(0), markEquals(true), - markDiffers(true), markCopyToLeft(true), markCopyToRight(true), markDeletable(true), - stack(), jobMap(), receivedMap(), parentWidget(0), resultListIt(resultList) +Synchronizer::Synchronizer() + : displayUpdateCount(0), markEquals(true), markDiffers(true), markCopyToLeft(true), + markCopyToRight(true), markDeletable(true), stack(), jobMap(), receivedMap(), parentWidget(0), + resultListIt(resultList) { } -Synchronizer::~Synchronizer() -{ - clearLists(); -} - -QUrl Synchronizer::fsUrl(QString strUrl) -{ - QUrl result = QUrl::fromUserInput(strUrl, QString(), QUrl::AssumeLocalFile); - return KrServices::escapeFileUrl(result); -} +Synchronizer::~Synchronizer() { clearLists(); } void Synchronizer::clearLists() { @@ -101,8 +93,10 @@ displayUpdateCount = 0; markEquals = markDiffers = markCopyToLeft = markCopyToRight = markDeletable = true; stopped = false; - recurseSubDirs = followSymLinks = ignoreDate = asymmetric = cmpByContent = ignoreCase = autoScroll = false; - markEquals = markDiffers = markCopyToLeft = markCopyToRight = markDeletable = markDuplicates = markSingles = false; + recurseSubDirs = followSymLinks = ignoreDate = asymmetric = cmpByContent = ignoreCase = + autoScroll = false; + markEquals = markDiffers = markCopyToLeft = markCopyToRight = markDeletable = markDuplicates = + markSingles = false; leftCopyEnabled = rightCopyEnabled = deleteEnabled = overWrite = autoSkip = paused = false; leftCopyNr = rightCopyNr = deleteNr = 0; leftCopySize = rightCopySize = deleteSize = 0; @@ -112,55 +106,50 @@ clearLists(); } -int Synchronizer::compare(QString leftURL, QString rightURL, KRQuery *query, bool subDirs, +int Synchronizer::compare(const QUrl &left, const QUrl &right, KRQuery *query, bool subDirs, bool symLinks, bool igDate, bool asymm, bool cmpByCnt, bool igCase, - bool autoSc, QStringList &selFiles, int equThres, int timeOffs, int parThreads, bool hiddenFiles) + bool autoSc, QStringList &selFiles, int equThres, int timeOffs, + int parThreads, bool hiddenFiles) { clearLists(); recurseSubDirs = subDirs; followSymLinks = symLinks; - ignoreDate = igDate; - asymmetric = asymm; - cmpByContent = cmpByCnt; - autoScroll = autoSc; - ignoreCase = igCase; - selectedFiles = selFiles; + ignoreDate = igDate; + asymmetric = asymm; + cmpByContent = cmpByCnt; + autoScroll = autoSc; + ignoreCase = igCase; + selectedFiles = selFiles; equalsThreshold = equThres; - timeOffset = timeOffs; + timeOffset = timeOffs; parallelThreads = parThreads; - ignoreHidden = hiddenFiles; + ignoreHidden = hiddenFiles; stopped = false; this->query = query; - leftURL = KUrlCompletion::replacedPath(leftURL, true, true); - rightURL = KUrlCompletion::replacedPath(rightURL, true, true); - - if (!leftURL.endsWith('/')) leftURL += '/'; - if (!rightURL.endsWith('/')) rightURL += '/'; - excludedPaths = KrServices::toStringList(query->dontSearchInDirs()); for (int i = 0; i != excludedPaths.count(); i++) - if (excludedPaths[ i ].endsWith('/')) - excludedPaths[ i ].truncate(excludedPaths[ i ].length() - 1); + if (excludedPaths[i].endsWith('/')) + excludedPaths[i].truncate(excludedPaths[i].length() - 1); comparedDirs = fileCount = 0; - stack.append(new CompareTask(0, leftBaseDir = leftURL, rightBaseDir = rightURL, "", "", ignoreHidden)); + stack.append(new CompareTask(0, leftBaseDir = left, rightBaseDir = right, QString(), QString(), + ignoreHidden)); compareLoop(); QListIterator it(temporaryList); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); if (item->isTemporary()) delete item; } temporaryList.clear(); - if (!autoScroll) refresh(true); @@ -172,17 +161,18 @@ { while (!stopped && !stack.isEmpty()) { for (int thread = 0; thread < (int)stack.count() && thread < parallelThreads; thread++) { - SynchronizerTask * entry = stack.at(thread); + SynchronizerTask *entry = stack.at(thread); if (entry->state() == ST_STATE_NEW) entry->start(parentWidget); if (entry->inherits("CompareTask")) { if (entry->state() == ST_STATE_READY) { - CompareTask *ctentry = (CompareTask *) entry; + CompareTask *ctentry = (CompareTask *)entry; if (ctentry->isDuplicate()) - compareDirectory(ctentry->parent(), ctentry->leftDirList(), ctentry->rightDirList(), - ctentry->leftDir(), ctentry->rightDir()); + compareDirectory(ctentry->parent(), ctentry->leftDirList(), + ctentry->rightDirList(), ctentry->leftDir(), + ctentry->rightDir()); else addSingleDirectory(ctentry->parent(), ctentry->dirList(), ctentry->dir(), ctentry->isLeft()); @@ -214,140 +204,137 @@ stack.clear(); } -void Synchronizer::compareDirectory(SynchronizerFileItem *parent, SynchronizerDirList * left_directory, - SynchronizerDirList * right_directory, const QString &leftDir, - const QString &rightDir) +void Synchronizer::compareDirectory(SynchronizerFileItem *parent, + SynchronizerDirList *left_directory, + SynchronizerDirList *right_directory, + const QString &leftDir, const QString &rightDir) { - const QString &leftURL = left_directory->url(); - const QString &rightURL = right_directory->url(); + const QUrl leftDirectoryPath = left_directory->url(); + const QUrl rightDirectoryPath = right_directory->url(); + const bool checkIfSelected = leftDir.isEmpty() && rightDir.isEmpty() && selectedFiles.count(); + FileItem *left_file; FileItem *right_file; - QString file_name; - bool checkIfSelected = false; - - if (leftDir.isEmpty() && rightDir.isEmpty() && selectedFiles.count()) - checkIfSelected = true; /* walking through in the left directory */ for (left_file = left_directory->first(); left_file != 0 && !stopped; - left_file = left_directory->next()) { + left_file = left_directory->next()) { + if (isDir(left_file)) continue; - file_name = left_file->getName(); + file_name = left_file->getName(); if (checkIfSelected && !selectedFiles.contains(file_name)) continue; if (!query->match(left_file)) continue; if ((right_file = right_directory->search(file_name, ignoreCase)) == 0) - addLeftOnlyItem(parent, file_name, leftDir, left_file->getSize(), left_file->getTime_t(), - readLink(left_file), left_file->getOwner(), left_file->getGroup(), - left_file->getMode(), left_file->getACL()); + addLeftOnlyItem(left_file, parent, leftDir); else { if (isDir(right_file)) continue; - addDuplicateItem(parent, file_name, right_file->getName(), leftDir, rightDir, left_file->getSize(), right_file->getSize(), - left_file->getTime_t(), right_file->getTime_t(), readLink(left_file), - readLink(right_file), left_file->getOwner(), right_file->getOwner(), - left_file->getGroup(), right_file->getGroup(), - left_file->getMode(), right_file->getMode(), - left_file->getACL(), right_file->getACL()); + addDuplicateItem(left_file, right_file, parent, leftDir, rightDir); } } /* walking through in the right directory */ for (right_file = right_directory->first(); right_file != 0 && !stopped; - right_file = right_directory->next()) { + right_file = right_directory->next()) { if (isDir(right_file)) continue; - file_name = right_file->getName(); + file_name = right_file->getName(); if (checkIfSelected && !selectedFiles.contains(file_name)) continue; if (!query->match(right_file)) continue; if (left_directory->search(file_name, ignoreCase) == 0) - addRightOnlyItem(parent, file_name, rightDir, right_file->getSize(), right_file->getTime_t(), - readLink(right_file), right_file->getOwner(), right_file->getGroup(), - right_file->getMode(), right_file->getACL()); + addRightOnlyItem(right_file, parent, rightDir); } - /* walking through the subdirectories */ if (recurseSubDirs) { + + /* walking through the left side subdirectories */ for (left_file = left_directory->first(); left_file != 0 && !stopped; - left_file = left_directory->next()) { - if (left_file->isDir() && (followSymLinks || !left_file->isSymLink())) { - QString left_file_name = left_file->getName(); - - if (checkIfSelected && !selectedFiles.contains(left_file_name)) - continue; - - if (excludedPaths.contains(leftDir.isEmpty() ? left_file_name : leftDir + '/' + left_file_name)) - continue; - - if (!query->matchDirName(left_file_name)) - continue; - - if ((right_file = right_directory->search(left_file_name, ignoreCase)) == 0) { - SynchronizerFileItem *me = addLeftOnlyItem(parent, left_file_name, leftDir, 0, - left_file->getTime_t(), readLink(left_file), - left_file->getOwner(), left_file->getGroup(), - left_file->getMode(), left_file->getACL(), - true, !query->match(left_file)); - stack.append(new CompareTask(me, leftURL + left_file_name + '/', - leftDir.isEmpty() ? left_file_name : leftDir + '/' + left_file_name, true, ignoreHidden)); - } else { - QString right_file_name = right_file->getName(); - SynchronizerFileItem *me = addDuplicateItem(parent, left_file_name, right_file_name, - leftDir, rightDir, 0, 0, - left_file->getTime_t(), right_file->getTime_t(), - readLink(left_file), readLink(right_file), - left_file->getOwner(), right_file->getOwner(), - left_file->getGroup(), right_file->getGroup(), - left_file->getMode(), right_file->getMode(), - left_file->getACL(), right_file->getACL(), - true, !query->match(left_file)); - stack.append(new CompareTask(me, leftURL + left_file_name + '/', rightURL + right_file_name + '/', - leftDir.isEmpty() ? left_file_name : leftDir + '/' + left_file_name, - rightDir.isEmpty() ? right_file_name : rightDir + '/' + right_file_name, ignoreHidden)); - } + left_file = left_directory->next()) { + + if (!left_file->isDir() || !(followSymLinks || !left_file->isSymLink())) + continue; + + const QString left_file_name = left_file->getName(); + + if (checkIfSelected && !selectedFiles.contains(left_file_name)) + continue; + + if (excludedPaths.contains(leftDir.isEmpty() ? left_file_name : + leftDir + '/' + left_file_name)) + continue; + + if (!query->matchDirName(left_file_name)) + continue; + + const QUrl leftFilePath = pathAppend(leftDirectoryPath, left_file_name); + const QString leftRelativeDir = + leftDir.isEmpty() ? left_file_name : leftDir + '/' + left_file_name; + + if ((right_file = right_directory->search(left_file_name, ignoreCase)) == 0) { + // no right file dir + SynchronizerFileItem *me = + addLeftOnlyItem(left_file, parent, leftDir, !query->match(left_file)); + stack.append( + new CompareTask(me, leftFilePath, leftRelativeDir, true, ignoreHidden)); + } else { + // compare left file dir with right file + const QString right_file_name = right_file->getName(); + const QUrl rightFilePath = pathAppend(rightDirectoryPath, right_file_name); + const QString rightRelativeDir = + rightDir.isEmpty() ? right_file_name : rightDir + '/' + right_file_name; + + SynchronizerFileItem *me = addDuplicateItem(left_file, right_file, parent, leftDir, + rightDir, !query->match(left_file)); + + stack.append(new CompareTask(me, leftFilePath, rightFilePath, leftRelativeDir, + rightRelativeDir, ignoreHidden)); } } /* walking through the right side subdirectories */ for (right_file = right_directory->first(); right_file != 0 && !stopped; - right_file = right_directory->next()) { - if (right_file->isDir() && (followSymLinks || !right_file->isSymLink())) { - file_name = right_file->getName(); - - if (checkIfSelected && !selectedFiles.contains(file_name)) - continue; - - if (excludedPaths.contains(rightDir.isEmpty() ? file_name : rightDir + '/' + file_name)) - continue; - - if (!query->matchDirName(file_name)) - continue; - - if (left_directory->search(file_name, ignoreCase) == 0) { - SynchronizerFileItem *me = addRightOnlyItem(parent, file_name, rightDir, 0, - right_file->getTime_t(), readLink(right_file), - right_file->getOwner(), right_file->getGroup(), - right_file->getMode(), right_file->getACL(), - true, !query->match(right_file)); - stack.append(new CompareTask(me, rightURL + file_name + '/', - rightDir.isEmpty() ? file_name : rightDir + '/' + file_name, false, ignoreHidden)); - } + right_file = right_directory->next()) { + + if (!right_file->isDir() || !(followSymLinks || !right_file->isSymLink())) + continue; + + file_name = right_file->getName(); + + if (checkIfSelected && !selectedFiles.contains(file_name)) + continue; + + const QString rightRelativePath = + rightDir.isEmpty() ? file_name : rightDir + '/' + file_name; + if (excludedPaths.contains(rightRelativePath)) + continue; + + if (!query->matchDirName(file_name)) + continue; + + if (left_directory->search(file_name, ignoreCase) == 0) { + // no left exists + SynchronizerFileItem *me = + addRightOnlyItem(right_file, parent, rightDir, !query->match(right_file)); + stack.append(new CompareTask(me, pathAppend(rightDirectoryPath, file_name), + rightRelativePath, false, ignoreHidden)); } } + } } @@ -358,22 +345,18 @@ return names[taskType]; } -SynchronizerFileItem * Synchronizer::addItem(SynchronizerFileItem *parent, const QString &leftFile, - const QString &rightFile, const QString &leftDir, - const QString &rightDir, bool existsLeft, bool existsRight, - KIO::filesize_t leftSize, KIO::filesize_t rightSize, - time_t leftDate, time_t rightDate, const QString &leftLink, - const QString &rightLink, const QString &leftOwner, - const QString &rightOwner, const QString &leftGroup, - const QString &rightGroup, mode_t leftMode, mode_t rightMode, - const QString &leftACL, const QString &rightACL, TaskType tsk, - bool isDir, bool isTemp) +SynchronizerFileItem *Synchronizer::addItem(FileItem *leftFile, FileItem *rightFile, + SynchronizerFileItem *parent, + const QString &leftDir, const QString &rightDir, + TaskType tsk, bool isTemp) { - bool marked = autoScroll ? !isTemp && isMarked(tsk, existsLeft && existsRight) : false; - SynchronizerFileItem *item = new SynchronizerFileItem(leftFile, rightFile, leftDir, rightDir, marked, - existsLeft, existsRight, leftSize, rightSize, leftDate, rightDate, leftLink, rightLink, - leftOwner, rightOwner, leftGroup, rightGroup, leftMode, rightMode, leftACL, rightACL, tsk, isDir, - isTemp, parent); + const bool existsLeft = leftFile != nullptr; + const bool existsRight = rightFile != nullptr; + const bool marked = autoScroll ? !isTemp && isMarked(tsk, existsLeft && existsRight) : false; + const FileItem left = existsLeft ? FileItem(*leftFile) : FileItem(); + const FileItem right = existsRight ? FileItem(*rightFile) : FileItem(); + SynchronizerFileItem *item = new SynchronizerFileItem(left, right, leftDir, rightDir, + marked, tsk, isTemp, parent); if (!isTemp) { while (parent && parent->isTemporary()) @@ -401,85 +384,50 @@ return item; } -void Synchronizer::compareContentResult(SynchronizerFileItem * item, bool res) +SynchronizerFileItem *Synchronizer::addLeftOnlyItem(FileItem *leftFile, SynchronizerFileItem *parent, + const QString &dir, bool isTemp) { - item->compareContentResult(res); - bool marked = autoScroll ? isMarked(item->task(), item->existsInLeft() && item->existsInRight()) : false; - item->setMarked(marked); - if (marked) { - markParentDirectories(item); - fileCount++; - emit markChanged(item, true); - } + return addItem(leftFile, nullptr, parent, dir, dir, asymmetric ? TT_DELETE : TT_COPY_TO_RIGHT, + isTemp); } -void Synchronizer::setPermanent(SynchronizerFileItem *item) -{ - if (item->parent() && item->parent()->isTemporary()) - setPermanent(item->parent()); - - item->setPermanent(); - resultList.append(item); - emit comparedFileData(item); -} - -SynchronizerFileItem * Synchronizer::addLeftOnlyItem(SynchronizerFileItem *parent, - const QString &file_name, const QString &dir, KIO::filesize_t size, - time_t date, const QString &link, const QString &owner, - const QString &group, mode_t mode, const QString &acl, bool isDir, - bool isTemp) -{ - return addItem(parent, file_name, file_name, dir, dir, true, false, size, 0, date, 0, link, QString(), - owner, QString(), group, QString(), mode, (mode_t) - 1, acl, QString(), - asymmetric ? TT_DELETE : TT_COPY_TO_RIGHT, isDir, isTemp); -} - -SynchronizerFileItem * Synchronizer::addRightOnlyItem(SynchronizerFileItem *parent, - const QString &file_name, const QString &dir, KIO::filesize_t size, - time_t date, const QString &link, const QString &owner, - const QString &group, mode_t mode, const QString &acl, bool isDir, - bool isTemp) +SynchronizerFileItem *Synchronizer::addRightOnlyItem(FileItem *rightFile, SynchronizerFileItem *parent, + const QString &dir, bool isTemp) { - return addItem(parent, file_name, file_name, dir, dir, false, true, 0, size, 0, date, QString(), link, - QString(), owner, QString(), group, (mode_t) - 1, mode, QString(), acl, - TT_COPY_TO_LEFT, isDir, isTemp); + return addItem(nullptr, rightFile, parent, dir, dir, TT_COPY_TO_LEFT, isTemp); } -SynchronizerFileItem * Synchronizer::addDuplicateItem(SynchronizerFileItem *parent, - const QString &leftName, const QString &rightName, - const QString &leftDir, const QString &rightDir, - KIO::filesize_t leftSize, KIO::filesize_t rightSize, time_t leftDate, time_t rightDate, - const QString &leftLink, const QString &rightLink, - const QString &leftOwner, const QString &rightOwner, - const QString &leftGroup, const QString &rightGroup, - mode_t leftMode, mode_t rightMode, - const QString &leftACL, const QString &rightACL, - bool isDir, bool isTemp) +SynchronizerFileItem *Synchronizer::addDuplicateItem(FileItem *leftFile, FileItem *rightFile, + SynchronizerFileItem *parent, const QString &leftDir, const QString &rightDir, bool isTemp) { - TaskType task; + TaskType task; - int checkedRightDate = rightDate - timeOffset; + Q_ASSERT(leftFile->isDir() == rightFile->isDir()); + const bool isDir = leftFile->isDir(); + const int checkedRightDate = rightFile->getTime_t() - timeOffset; + const time_t leftDate = leftFile->getTime_t(); int uncertain = 0; do { if (isDir) { task = TT_EQUALS; break; } - if (leftSize == rightSize) { - if (!leftLink.isNull() || !rightLink.isNull()) { - if (leftLink == rightLink) { - task = TT_EQUALS; - break; - } - } else if (cmpByContent) + + if (leftFile->getSize() == rightFile->getSize()) { + if (leftFile->isSymLink() == rightFile->isSymLink() && + rightFile->getSymDest() == rightFile->getSymDest()) { + task = TT_EQUALS; + break; + } else if (cmpByContent) { uncertain = TT_UNKNOWN; - else { + } else { if (ignoreDate || leftDate == checkedRightDate) { task = TT_EQUALS; break; } - time_t diff = (leftDate > checkedRightDate) ? leftDate - checkedRightDate : checkedRightDate - leftDate; + time_t diff = (leftDate > checkedRightDate) ? leftDate - checkedRightDate : + checkedRightDate - leftDate; if (diff <= equalsThreshold) { task = TT_EQUALS; break; @@ -500,83 +448,96 @@ } while (false); - SynchronizerFileItem * item = addItem(parent, leftName, rightName, leftDir, rightDir, true, true, - leftSize, rightSize, leftDate, rightDate, leftLink, rightLink, - leftOwner, rightOwner, leftGroup, rightGroup, - leftMode, rightMode, leftACL, rightACL, - (TaskType)(task + uncertain), isDir, isTemp); + SynchronizerFileItem *item = addItem(leftFile, rightFile, + parent, leftDir, rightDir, (TaskType)(task + uncertain), isTemp); if (uncertain == TT_UNKNOWN) { - QUrl leftURL = Synchronizer::fsUrl(leftDir.isEmpty() ? leftBaseDir + leftName : leftBaseDir + leftDir + '/' + leftName); - QUrl rightURL = Synchronizer::fsUrl(rightDir.isEmpty() ? rightBaseDir + rightName : rightBaseDir + rightDir + '/' + rightName); - stack.append(new CompareContentTask(this, item, leftURL, rightURL, leftSize)); + const QUrl leftURL = pathAppend(leftBaseDir, leftDir, leftFile->getName()); + const QUrl rightURL = pathAppend(rightBaseDir, rightDir, rightFile->getName()); + stack.append(new CompareContentTask(this, item, leftURL, rightURL, leftFile->getSize())); } return item; } void Synchronizer::addSingleDirectory(SynchronizerFileItem *parent, SynchronizerDirList *directory, const QString &dirName, bool isLeft) { - const QString &url = directory->url(); + const QUrl &url = directory->url(); FileItem *file; QString file_name; /* walking through the directory files */ for (file = directory->first(); file != 0 && !stopped; file = directory->next()) { if (isDir(file)) continue; - file_name = file->getName(); + file_name = file->getName(); if (!query->match(file)) continue; if (isLeft) - addLeftOnlyItem(parent, file_name, dirName, file->getSize(), file->getTime_t(), readLink(file), - file->getOwner(), file->getGroup(), file->getMode(), file->getACL()); + addLeftOnlyItem(file, parent, dirName); else - addRightOnlyItem(parent, file_name, dirName, file->getSize(), file->getTime_t(), readLink(file), - file->getOwner(), file->getGroup(), file->getMode(), file->getACL()); + addRightOnlyItem(file, parent, dirName); } /* walking through the subdirectories */ for (file = directory->first(); file != 0 && !stopped; file = directory->next()) { if (file->isDir() && (followSymLinks || !file->isSymLink())) { - file_name = file->getName(); + file_name = file->getName(); if (excludedPaths.contains(dirName.isEmpty() ? file_name : dirName + '/' + file_name)) continue; if (!query->matchDirName(file_name)) continue; - SynchronizerFileItem *me; - - if (isLeft) - me = addLeftOnlyItem(parent, file_name, dirName, 0, file->getTime_t(), readLink(file), - file->getOwner(), file->getGroup(), file->getMode(), - file->getACL(), true, !query->match(file)); - else - me = addRightOnlyItem(parent, file_name, dirName, 0, file->getTime_t(), readLink(file), - file->getOwner(), file->getGroup(), file->getMode(), - file->getACL(), true, !query->match(file)); - stack.append(new CompareTask(me, url + file_name + '/', - dirName.isEmpty() ? file_name : dirName + '/' + file_name, isLeft, ignoreHidden)); + SynchronizerFileItem *me = + isLeft ? addLeftOnlyItem(file, parent, dirName, !query->match(file)) : + addRightOnlyItem(file, parent, dirName, !query->match(file)); + + stack.append(new CompareTask(me, pathAppend(url, file_name), + dirName.isEmpty() ? file_name : dirName + '/' + file_name, + isLeft, ignoreHidden)); } } } -void Synchronizer::setMarkFlags(bool left, bool equal, bool differs, bool right, bool dup, bool sing, - bool del) +void Synchronizer::compareContentResult(SynchronizerFileItem *item, bool res) { - markEquals = equal; - markDiffers = differs; - markCopyToLeft = left; + item->compareContentResult(res); + bool marked = + autoScroll ? isMarked(item->task(), item->existsLeft() && item->existsRight()) : false; + item->setMarked(marked); + if (marked) { + markParentDirectories(item); + fileCount++; + emit markChanged(item, true); + } +} + +void Synchronizer::setPermanent(SynchronizerFileItem *item) +{ + if (item->parent() && item->parent()->isTemporary()) + setPermanent(item->parent()); + + item->setPermanent(); + resultList.append(item); + emit comparedFileData(item); +} + +void Synchronizer::setMarkFlags(bool left, bool equal, bool differs, bool right, bool dup, + bool sing, bool del) +{ + markEquals = equal; + markDiffers = differs; + markCopyToLeft = left; markCopyToRight = right; - markDeletable = del; - markDuplicates = dup; - markSingles = sing; + markDeletable = del; + markDuplicates = dup; + markSingles = sing; } bool Synchronizer::isMarked(TaskType task, bool isDuplicate) @@ -620,9 +581,9 @@ QListIterator it(resultList); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); - bool marked = isMarked(item->task(), item->existsInLeft() && item->existsInRight()); + bool marked = isMarked(item->task(), item->existsLeft() && item->existsRight()); item->setMarked(marked); if (marked) { @@ -633,7 +594,7 @@ it.toFront(); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); emit markChanged(item, false); } @@ -649,57 +610,55 @@ executeOperation(item); if (item->isDir()) { - QString leftDirName = (item->leftDirectory().isEmpty()) ? - item->leftName() : item->leftDirectory() + '/' + item->leftName(); - QString rightDirName = (item->rightDirectory().isEmpty()) ? - item->rightName() : item->rightDirectory() + '/' + item->rightName(); + const QString leftDirName = (item->leftDirectory().isEmpty()) ? + item->leftName() : + item->leftDirectory() + '/' + item->leftName(); + const QString rightDirName = (item->rightDirectory().isEmpty()) ? + item->rightName() : + item->rightDirectory() + '/' + item->rightName(); QListIterator it(resultList); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); - if (item->leftDirectory() == leftDirName || item->leftDirectory().startsWith(leftDirName + '/') || - item->rightDirectory() == rightDirName || item->rightDirectory().startsWith(rightDirName + '/')) + if (item->leftDirectory() == leftDirName || + item->leftDirectory().startsWith(leftDirName + '/') || + item->rightDirectory() == rightDirName || + item->rightDirectory().startsWith(rightDirName + '/')) executeOperation(item); } } } -void Synchronizer::excludeOperation(SynchronizerFileItem *item) -{ - item->setTask(TT_DIFFERS); -} +void Synchronizer::excludeOperation(SynchronizerFileItem *item) { item->setTask(TT_DIFFERS); } void Synchronizer::exclude(SynchronizerFileItem *item) { if (!item->parent() || item->parent()->task() != TT_DELETE) - operate(item, excludeOperation); /* exclude only if the parent task is not DEL */ + operate(item, excludeOperation); /* exclude only if the parent task is not DEL */ } -void Synchronizer::restoreOperation(SynchronizerFileItem *item) -{ - item->restoreOriginalTask(); -} +void Synchronizer::restoreOperation(SynchronizerFileItem *item) { item->restoreOriginalTask(); } void Synchronizer::restore(SynchronizerFileItem *item) { operate(item, restoreOperation); - while ((item = item->parent()) != 0) /* in case of restore, the parent directories */ - { /* must be changed for being consistent */ + while ((item = item->parent()) != 0) /* in case of restore, the parent directories */ + { /* must be changed for being consistent */ if (item->task() != TT_DIFFERS) break; - if (item->originalTask() == TT_DELETE) /* if the parent original task is delete */ - break; /* don't touch it */ + if (item->originalTask() == TT_DELETE) /* if the parent original task is delete */ + break; /* don't touch it */ - item->restoreOriginalTask(); /* restore */ + item->restoreOriginalTask(); /* restore */ } } void Synchronizer::reverseDirectionOperation(SynchronizerFileItem *item) { - if (item->existsInRight() && item->existsInLeft()) { + if (item->existsRight() && item->existsLeft()) { if (item->task() == TT_COPY_TO_LEFT) item->setTask(TT_COPY_TO_RIGHT); else if (item->task() == TT_COPY_TO_RIGHT) @@ -714,24 +673,35 @@ void Synchronizer::deleteLeftOperation(SynchronizerFileItem *item) { - if (!item->existsInRight() && item->existsInLeft()) + if (!item->existsRight() && item->existsLeft()) item->setTask(TT_DELETE); } -void Synchronizer::deleteLeft(SynchronizerFileItem *item) +QUrl Synchronizer::pathAppend(const QUrl &url, const QString &fileName) { - operate(item, deleteLeftOperation); + QUrl newUrl = QUrl(url); + newUrl.setPath(QDir(url.path()).filePath(fileName)); + return newUrl; } +QUrl Synchronizer::pathAppend(const QUrl &url, const QString &dirName, const QString &fileName) +{ + QUrl newUrl = QUrl(url); + newUrl.setPath(QDir(QDir(url.path()).filePath(dirName)).filePath(fileName)); + return newUrl; +} + +void Synchronizer::deleteLeft(SynchronizerFileItem *item) { operate(item, deleteLeftOperation); } + void Synchronizer::copyToLeftOperation(SynchronizerFileItem *item) { - if (item->existsInRight()) { + if (item->existsRight()) { if (!item->isDir()) item->setTask(TT_COPY_TO_LEFT); else { - if (item->existsInLeft() && item->existsInRight()) + if (item->existsLeft() && item->existsRight()) item->setTask(TT_EQUALS); - else if (!item->existsInLeft() && item->existsInRight()) + else if (!item->existsLeft() && item->existsRight()) item->setTask(TT_COPY_TO_LEFT); } } @@ -745,22 +715,22 @@ if (item->task() != TT_DIFFERS) break; - if (item->existsInLeft() && item->existsInRight()) + if (item->existsLeft() && item->existsRight()) item->setTask(TT_EQUALS); - else if (!item->existsInLeft() && item->existsInRight()) + else if (!item->existsLeft() && item->existsRight()) item->setTask(TT_COPY_TO_LEFT); } } void Synchronizer::copyToRightOperation(SynchronizerFileItem *item) { - if (item->existsInLeft()) { + if (item->existsLeft()) { if (!item->isDir()) item->setTask(TT_COPY_TO_RIGHT); else { - if (item->existsInLeft() && item->existsInRight()) + if (item->existsLeft() && item->existsRight()) item->setTask(TT_EQUALS); - else if (item->existsInLeft() && !item->existsInRight()) + else if (item->existsLeft() && !item->existsRight()) item->setTask(TT_COPY_TO_RIGHT); } } @@ -774,24 +744,25 @@ if (item->task() != TT_DIFFERS && item->task() != TT_DELETE) break; - if (item->existsInLeft() && item->existsInRight()) + if (item->existsLeft() && item->existsRight()) item->setTask(TT_EQUALS); - else if (item->existsInLeft() && !item->existsInRight()) + else if (item->existsLeft() && !item->existsRight()) item->setTask(TT_COPY_TO_RIGHT); } } -bool Synchronizer::totalSizes(int * leftCopyNr, KIO::filesize_t *leftCopySize, int * rightCopyNr, - KIO::filesize_t *rightCopySize, int *deleteNr, KIO::filesize_t *deletableSize) +bool Synchronizer::totalSizes(int *leftCopyNr, KIO::filesize_t *leftCopySize, int *rightCopyNr, + KIO::filesize_t *rightCopySize, int *deleteNr, + KIO::filesize_t *deletableSize) { bool hasAnythingToDo = false; *leftCopySize = *rightCopySize = *deletableSize = 0; *leftCopyNr = *rightCopyNr = *deleteNr = 0; QListIterator it(resultList); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); if (item->isMarked()) { switch (item->task()) { @@ -821,13 +792,13 @@ void Synchronizer::swapSides() { - QString leftTmp = leftBaseDir; + const QUrl leftTmp = leftBaseDir; leftBaseDir = rightBaseDir; rightBaseDir = leftTmp; QListIterator it(resultList); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); item->swap(asymmetric); } @@ -843,15 +814,15 @@ } } -void Synchronizer::synchronize(QWidget *syncWdg, bool leftCopyEnabled, bool rightCopyEnabled, +void Synchronizer::synchronize(QWidget *syncDialog, bool leftCopyEnabled, bool rightCopyEnabled, bool deleteEnabled, bool overWrite, int parThreads) { - this->leftCopyEnabled = leftCopyEnabled; - this->rightCopyEnabled = rightCopyEnabled; - this->deleteEnabled = deleteEnabled; - this->overWrite = overWrite; - this->parallelThreads = parThreads; - this->syncDlgWidget = syncWdg; + this->leftCopyEnabled = leftCopyEnabled; + this->rightCopyEnabled = rightCopyEnabled; + this->deleteEnabled = deleteEnabled; + this->overWrite = overWrite; + this->parallelThreads = parThreads; + this->syncDlgWidget = syncDialog; autoSkip = paused = disableNewTasks = false; @@ -889,10 +860,10 @@ } } -SynchronizerFileItem * Synchronizer::getNextTask() +SynchronizerFileItem *Synchronizer::getNextTask() { TaskType task; - SynchronizerFileItem * currentTask; + SynchronizerFileItem *currentTask; do { if (!resultListIt.hasNext()) @@ -915,104 +886,77 @@ return lastTask = currentTask; } - -void Synchronizer::executeTask(SynchronizerFileItem * task) +void Synchronizer::executeTask(SynchronizerFileItem *task) { - QString leftDirName = task->leftDirectory(); - if (!leftDirName.isEmpty()) - leftDirName += '/'; - QString rightDirName = task->rightDirectory(); - if (!rightDirName.isEmpty()) - rightDirName += '/'; + const QUrl leftURL = pathAppend(leftBaseDir, task->leftDirectory(), task->leftName()); + const QUrl rightURL = pathAppend(rightBaseDir, task->rightDirectory(), task->rightName()); - QUrl leftURL = Synchronizer::fsUrl(leftBaseDir + leftDirName + task->leftName()); - QUrl rightURL = Synchronizer::fsUrl(rightBaseDir + rightDirName + task->rightName()); + KJob *job = nullptr; switch (task->task()) { case TT_COPY_TO_LEFT: - if (task->isDir()) { - KIO::SimpleJob *job = KIO::mkdir(leftURL); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - disableNewTasks = true; - } else { - QUrl destURL(leftURL); - if (!task->destination().isNull()) - destURL = Synchronizer::fsUrl(task->destination()); - - if (task->rightLink().isNull()) { - KIO::FileCopyJob *job = KIO::file_copy(rightURL, destURL, -1, - ((overWrite || task->overWrite()) ? KIO::Overwrite : KIO::DefaultFlags) | KIO::HideProgressInfo); - connect(job, SIGNAL(processedSize(KJob*,qulonglong)), this, - SLOT(slotProcessedSize(KJob*,qulonglong))); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - } else { - KIO::SimpleJob *job = KIO::symlink(task->rightLink(), destURL, - ((overWrite || task->overWrite()) ? KIO::Overwrite : KIO::DefaultFlags) | KIO::HideProgressInfo); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - } - } + job = createJob(task, rightURL, leftURL, task->rightLink()); break; case TT_COPY_TO_RIGHT: - if (task->isDir()) { - KIO::SimpleJob *job = KIO::mkdir(rightURL); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - disableNewTasks = true; - } else { - QUrl destURL(rightURL); - if (!task->destination().isNull()) - destURL = Synchronizer::fsUrl(task->destination()); - - if (task->leftLink().isNull()) { - KIO::FileCopyJob *job = KIO::file_copy(leftURL, destURL, -1, - ((overWrite || task->overWrite()) ? KIO::Overwrite : KIO::DefaultFlags) | KIO::HideProgressInfo); - connect(job, SIGNAL(processedSize(KJob*,qulonglong)), this, - SLOT(slotProcessedSize(KJob*,qulonglong))); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - } else { - KIO::SimpleJob *job = KIO::symlink(task->leftLink(), destURL, - ((overWrite || task->overWrite()) ? KIO::Overwrite : KIO::DefaultFlags) | KIO::HideProgressInfo); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - } - } + job = createJob(task, leftURL, rightURL, task->leftLink()); break; - case TT_DELETE: { - KIO::DeleteJob *job = KIO::del(leftURL, KIO::DefaultFlags); - connect(job, SIGNAL(result(KJob*)), this, SLOT(slotTaskFinished(KJob*))); - jobMap[ job ] = task; - } - break; - default: + case TT_DELETE: + job = KIO::del(leftURL, KIO::DefaultFlags); break; + default: + return; + } + + if (job) { + connect(job, &KIO::FileCopyJob::result, this, &Synchronizer::slotTaskFinished); + jobMap[job] = task; + } +} + +KJob *Synchronizer::createJob(SynchronizerFileItem *task, const QUrl &src, const QUrl &dest, + const QString &link) +{ + KJob *job; + if (task->isDir()) { + job = KIO::mkdir(dest); + disableNewTasks = true; + } else { + const QUrl destURL = task->destination().isEmpty() ? dest : task->destination(); + const KIO::JobFlags flags = + ((overWrite || task->overWrite()) ? KIO::Overwrite : KIO::DefaultFlags) | + KIO::HideProgressInfo; + + if (link.isNull()) { + job = KIO::file_copy(src, destURL, -1, flags); + connect(job, SIGNAL(processedSize(KJob *, qulonglong)), this, + SLOT(slotProcessedSize(KJob *, qulonglong))); + } else { + job = KIO::symlink(link, destURL, flags); + } } + + return job; } void Synchronizer::slotTaskFinished(KJob *job) { inTaskFinished++; - SynchronizerFileItem * item = jobMap[ job ]; + SynchronizerFileItem *item = jobMap[job]; jobMap.remove(job); KIO::filesize_t receivedSize = 0; if (receivedMap.contains(job)) { - receivedSize = receivedMap[ job ]; + receivedSize = receivedMap[job]; receivedMap.remove(job); } if (disableNewTasks && item == lastTask) disableNewTasks = false; // the blocker task finished - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(leftBaseDir + leftDirName + item->leftName()); - QUrl rightURL = Synchronizer::fsUrl(rightBaseDir + rightDirName + item->rightName()); + const QUrl leftURL = pathAppend(leftBaseDir, item->leftDirectory() , item->leftName()); + const QUrl rightURL = pathAppend(rightBaseDir, item->rightDirectory(), item->rightName()); do { if (!job->error()) { @@ -1024,33 +968,40 @@ timestamp.actime = time(0); timestamp.modtime = item->rightDate() - timeOffset; - utime((const char *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), ×tamp); + utime((const char + *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + ×tamp); - uid_t newOwnerID = (uid_t) - 1; // chown(2) : -1 means no change + uid_t newOwnerID = (uid_t)-1; // chown(2) : -1 means no change if (!item->rightOwner().isEmpty()) { - struct passwd* pw = getpwnam(QFile::encodeName(item->rightOwner())); + struct passwd *pw = getpwnam(QFile::encodeName(item->rightOwner())); if (pw != 0L) newOwnerID = pw->pw_uid; } - gid_t newGroupID = (gid_t) - 1; // chown(2) : -1 means no change + gid_t newGroupID = (gid_t)-1; // chown(2) : -1 means no change if (!item->rightGroup().isEmpty()) { - struct group* g = getgrnam(QFile::encodeName(item->rightGroup())); + struct group *g = getgrnam(QFile::encodeName(item->rightGroup())); if (g != 0L) newGroupID = g->gr_gid; } - int status1 = chown((const char *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), newOwnerID, (gid_t) - 1); - int status2 = chown((const char *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), (uid_t) - 1, newGroupID); - if (status1 < 0 || status2 < 0) { - // synchronizer currently ignores chown errors - } + chown((const char + *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + newOwnerID, (gid_t)-1); + chown((const char + *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + (uid_t)-1, newGroupID); - chmod((const char *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), item->rightMode() & 07777); + chmod((const char + *)(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + item->rightMode() & 07777); #ifdef HAVE_POSIX_ACL if (!item->rightACL().isNull()) { acl_t acl = acl_from_text(item->rightACL().toLatin1()); if (acl && !acl_valid(acl)) - acl_set_file(leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit(), ACL_TYPE_ACCESS, acl); + acl_set_file( + leftURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit(), + ACL_TYPE_ACCESS, acl); if (acl) acl_free(acl); } @@ -1064,33 +1015,40 @@ timestamp.actime = time(0); timestamp.modtime = item->leftDate() + timeOffset; - utime((const char *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), ×tamp); + utime((const char + *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + ×tamp); - uid_t newOwnerID = (uid_t) - 1; // chown(2) : -1 means no change + uid_t newOwnerID = (uid_t)-1; // chown(2) : -1 means no change if (!item->leftOwner().isEmpty()) { - struct passwd* pw = getpwnam(QFile::encodeName(item->leftOwner())); + struct passwd *pw = getpwnam(QFile::encodeName(item->leftOwner())); if (pw != 0L) newOwnerID = pw->pw_uid; } - gid_t newGroupID = (gid_t) - 1; // chown(2) : -1 means no change + gid_t newGroupID = (gid_t)-1; // chown(2) : -1 means no change if (!item->leftGroup().isEmpty()) { - struct group* g = getgrnam(QFile::encodeName(item->leftGroup())); + struct group *g = getgrnam(QFile::encodeName(item->leftGroup())); if (g != 0L) newGroupID = g->gr_gid; } - int status1 = chown((const char *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), newOwnerID, (uid_t) - 1); - int status2 = chown((const char *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), (uid_t) - 1, newGroupID); - if (status1 < 0 || status2 < 0) { - // synchronizer currently ignores chown errors - } + chown((const char + *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + newOwnerID, (uid_t)-1); + chown((const char + *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + (uid_t)-1, newGroupID); - chmod((const char *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), item->leftMode() & 07777); + chmod((const char + *)(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit()), + item->leftMode() & 07777); #ifdef HAVE_POSIX_ACL if (!item->leftACL().isNull()) { acl_t acl = acl_from_text(item->leftACL().toLatin1()); if (acl && !acl_valid(acl)) - acl_set_file(rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit(), ACL_TYPE_ACCESS, acl); + acl_set_file( + rightURL.adjusted(QUrl::StripTrailingSlash).path().toLocal8Bit(), + ACL_TYPE_ACCESS, acl); if (acl) acl_free(acl); } @@ -1101,40 +1059,39 @@ break; } } else { - if (job->error() == KIO::ERR_FILE_ALREADY_EXIST && item->task() != TT_DELETE) { - KIO::RenameDialog_Result result; - QString newDest; + if (job->error() == KIO::ERR_FILE_ALREADY_EXIST && item->task() != TT_DELETE) { if (autoSkip) break; - KIO::JobUiDelegate *ui = static_cast(job->uiDelegate()); + KIO::JobUiDelegate *ui = static_cast(job->uiDelegate()); ui->setWindow(syncDlgWidget); - if (item->task() == TT_COPY_TO_LEFT) { - result = - ui->askFileRename(job, i18n("File Already Exists"), rightURL, leftURL, - KIO::RenameDialog_Overwrite | KIO::RenameDialog_Skip | - KIO::RenameDialog_MultipleItems, - newDest, item->rightSize(), item->leftSize(), QDateTime(), - QDateTime(), QDateTime::fromTime_t(item->rightDate()), - QDateTime::fromTime_t(item->leftDate())); - } else { - result = - ui->askFileRename(job, i18n("File Already Exists"), leftURL, rightURL, - KIO::RenameDialog_Overwrite | KIO::RenameDialog_Skip | - KIO::RenameDialog_MultipleItems, - newDest, item->leftSize(), item->rightSize(), QDateTime(), - QDateTime(), QDateTime::fromTime_t(item->leftDate()), - QDateTime::fromTime_t(item->rightDate())); - } + const bool fromRightToLeft = item->task() == TT_COPY_TO_LEFT; + const QUrl source = fromRightToLeft ? rightURL : leftURL; + const QUrl destination = fromRightToLeft ? leftURL : rightURL; + KIO::filesize_t sizeSrc = fromRightToLeft ? item->rightSize() : item->leftSize(); + KIO::filesize_t sizeDest = fromRightToLeft ? item->leftSize() : item->rightSize(); + time_t mTimeSrc = fromRightToLeft ? item->rightDate() : item->leftDate(); + time_t mTimeDest = fromRightToLeft ? item->leftDate() : item->rightDate(); + + QString newDest; + KIO::RenameDialog_Result result = ui->askFileRename( + job, i18n("File Already Exists"), source, destination, + KIO::RenameDialog_Overwrite | KIO::RenameDialog_Skip | + KIO::RenameDialog_MultipleItems, + newDest, sizeSrc, sizeDest, QDateTime(), QDateTime(), + QDateTime::fromTime_t(mTimeSrc), QDateTime::fromTime_t(mTimeDest)); switch (result) { - case KIO::R_RENAME: - item->setDestination(newDest); + case KIO::R_RENAME: { + QUrl newDestUrl = QUrl(destination); + newDestUrl.setPath(newDest); // new destination does not contain scheme + item->setDestination(newDestUrl); executeTask(item); inTaskFinished--; return; + } case KIO::R_OVERWRITE: item->setOverWrite(); executeTask(item); @@ -1162,30 +1119,35 @@ switch (item->task()) { case TT_COPY_TO_LEFT: - error = i18n("Error at copying file %1 to %2.", + error = i18n("Error at copying file %1 to %2:\n%3", rightURL.toDisplayString(QUrl::PreferLocalFile), - leftURL.toDisplayString(QUrl::PreferLocalFile)); + leftURL.toDisplayString(QUrl::PreferLocalFile), + job->errorString()); break; case TT_COPY_TO_RIGHT: - error = i18n("Error at copying file %1 to %2.", + error = i18n("Error at copying file %1 to %2:\n%3", leftURL.toDisplayString(QUrl::PreferLocalFile), - rightURL.toDisplayString(QUrl::PreferLocalFile)); + rightURL.toDisplayString(QUrl::PreferLocalFile), + job->errorString()); break; case TT_DELETE: - error = i18n("Error at deleting file %1.", leftURL.toDisplayString(QUrl::PreferLocalFile)); + error = i18n("Error at deleting file %1:\n%2", + leftURL.toDisplayString(QUrl::PreferLocalFile), + job->errorString()); break; default: break; } - KIO::JobUiDelegate *ui = static_cast(job->uiDelegate()); + KIO::JobUiDelegate *ui = static_cast(job->uiDelegate()); ui->setWindow(syncDlgWidget); - KIO::SkipDialog_Result result = ui->askSkip(job, KIO::SkipDialog_MultipleItems, error); + KIO::SkipDialog_Result result = + ui->askSkip(job, KIO::SkipDialog_MultipleItems, error); switch (result) { case KIO::S_CANCEL: - executeTask(item); /* simply retry */ + executeTask(item); /* simply retry */ inTaskFinished--; return; case KIO::S_AUTO_SKIP: @@ -1224,16 +1186,16 @@ } } -void Synchronizer::slotProcessedSize(KJob * job , qulonglong size) +void Synchronizer::slotProcessedSize(KJob *job, qulonglong size) { KIO::filesize_t dl = 0, dr = 0, dd = 0; - SynchronizerFileItem * item = jobMap[ job ]; + SynchronizerFileItem *item = jobMap[job]; KIO::filesize_t lastProcessedSize = 0; if (receivedMap.contains(job)) - lastProcessedSize = receivedMap[ job ]; + lastProcessedSize = receivedMap[job]; - receivedMap[ job ] = size; + receivedMap[job] = size; switch (item->task()) { case TT_COPY_TO_LEFT: @@ -1249,32 +1211,21 @@ break; } - emit processedSizes(leftCopyNr, leftCopySize += dl, rightCopyNr, rightCopySize += dr, deleteNr, deleteSize += dd); + emit processedSizes(leftCopyNr, leftCopySize += dl, rightCopyNr, rightCopySize += dr, deleteNr, + deleteSize += dd); } -void Synchronizer::pause() -{ - paused = true; -} +void Synchronizer::pause() { paused = true; } void Synchronizer::resume() { paused = false; synchronizeLoop(); } -QString Synchronizer::leftBaseDirectory() -{ - return leftBaseDir; -} - -QString Synchronizer::rightBaseDirectory() -{ - return rightBaseDir; -} - -KgetProgressDialog::KgetProgressDialog(QWidget *parent, const QString &caption, - const QString &text, bool modal) : QDialog(parent) +KgetProgressDialog::KgetProgressDialog(QWidget *parent, const QString &caption, const QString &text, + bool modal) + : QDialog(parent) { if (caption.isEmpty()) setWindowTitle(caption); @@ -1315,28 +1266,31 @@ reject(); } - void Synchronizer::synchronizeWithKGet() { - bool isLeftLocal = QUrl::fromUserInput(leftBaseDirectory(), QString(), QUrl::AssumeLocalFile).isLocalFile(); + const bool isLeftLocal = leftBaseDirectory().isLocalFile(); + + if (isLeftLocal == rightBaseDirectory().isLocalFile()) { + qDebug() << "one side must be local, the other remote"; + return; + } + KgetProgressDialog *progDlg = 0; - int processedCount = 0, totalCount = 0; + int processedCount = 0, totalCount = 0; QListIterator it(resultList); while (it.hasNext()) if (it.next()->isMarked()) totalCount++; it.toFront(); while (it.hasNext()) { - SynchronizerFileItem * item = it.next(); + SynchronizerFileItem *item = it.next(); if (item->isMarked()) { QUrl downloadURL; QUrl destURL; - QString destDir; - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; + QUrl destDir; if (progDlg == 0) { progDlg = new KgetProgressDialog(krMainWindow, i18n("Krusader::Synchronizer"), @@ -1347,45 +1301,56 @@ } if (item->task() == TT_COPY_TO_RIGHT && !isLeftLocal) { - downloadURL = Synchronizer::fsUrl(leftBaseDirectory() + leftDirName + item->leftName()); - destDir = rightBaseDirectory() + rightDirName; - destURL = Synchronizer::fsUrl(destDir + item->rightName()); + downloadURL = pathAppend(leftBaseDirectory(), item->leftDirectory(), item->leftName()); + destDir = pathAppend(rightBaseDirectory(), item->rightDirectory()); + destURL = pathAppend(destDir, item->rightName()); if (item->isDir()) - destDir += item->leftName(); + destDir = pathAppend(destDir, item->leftName()); } - if (item->task() == TT_COPY_TO_LEFT && isLeftLocal) { - downloadURL = Synchronizer::fsUrl(rightBaseDirectory() + rightDirName + item->rightName()); - destDir = leftBaseDirectory() + leftDirName; - destURL = Synchronizer::fsUrl(destDir + item->leftName()); + else if (item->task() == TT_COPY_TO_LEFT && isLeftLocal) { + downloadURL = pathAppend(rightBaseDirectory(), item->rightDirectory(), item->rightName()); + destDir = pathAppend(leftBaseDirectory(), item->leftDirectory()); + destURL = pathAppend(destDir, item->leftName()); if (item->isDir()) - destDir += item->rightName(); + destDir = pathAppend(destDir, item->rightName()); + } else { + qDebug() << "KGet can only download from remote to local"; + continue; } + const QString destLocalDir = destDir.toLocalFile(); + // creating the directory system - for (int i = 0; i >= 0 ; i = destDir.indexOf('/', i + 1)) - if (!QDir(destDir.left(i)).exists()) - QDir().mkdir(destDir.left(i)); + for (int i = 0; i >= 0; i = destLocalDir.indexOf('/', i + 1)) { + if (!QDir(destLocalDir.left(i)).exists()) + QDir().mkdir(destLocalDir.left(i)); + } if (!item->isDir() && !downloadURL.isEmpty()) { - if (QFile(destURL.path()).exists()) + // ovewrite destination + if (QFile(destURL.path()).exists()) { QFile(destURL.path()).remove(); + } QString source = downloadURL.toDisplayString(); - if (source.indexOf('@') >= 2) { /* is this an ftp proxy URL? */ - int lastAt = source.lastIndexOf('@'); + if (source.indexOf('@') >= 2) { /* is this an ftp proxy URL? */ + const int lastAt = source.lastIndexOf('@'); QString startString = source.left(lastAt); - QString endString = source.mid(lastAt); startString.replace('@', "%40"); + const QString endString = source.mid(lastAt); source = startString + endString; } KProcess p; - p << KrServices::fullPathName("kget") << source << destURL.path(); - if (!p.startDetached()) - KMessageBox::error(parentWidget, i18n("Error executing %1.", KrServices::fullPathName("kget"))); + const QString kgetPath = KrServices::fullPathName("kget"); + p << kgetPath << source << destURL.path(); + + if (!p.startDetached()) { + KMessageBox::error(parentWidget, i18n("Error executing %1.", kgetPath)); + } } progDlg->progressBar()->setValue(++processedCount); @@ -1403,7 +1368,7 @@ canExit = (t.elapsed() > 100); if (progDlg->isPaused() || !canExit) - usleep(10000); + usleep(10 * 1000); // wait 10 seconds for some reason } while (progDlg->isPaused() || !canExit); @@ -1418,19 +1383,7 @@ bool Synchronizer::isDir(const FileItem *file) { - if (followSymLinks) { - return file->isDir(); - } else { - return file->isDir() && !file->isSymLink(); - } -} - -QString Synchronizer::readLink(const FileItem *file) -{ - if (file->isSymLink()) - return file->getSymDest(); - else - return QString(); + return file->isDir() && (followSymLinks || !file->isSymLink()); } SynchronizerFileItem *Synchronizer::getItemAt(unsigned ndx) @@ -1440,4 +1393,3 @@ else return 0; } - diff --git a/krusader/Synchronizer/synchronizerdirlist.h b/krusader/Synchronizer/synchronizerdirlist.h --- a/krusader/Synchronizer/synchronizerdirlist.h +++ b/krusader/Synchronizer/synchronizerdirlist.h @@ -22,12 +22,12 @@ #define SYNCHRONIZERDIRLIST_H // QtCore -#include #include +#include #include -#include "../FileSystem/fileitem.h" +class FileItem; class SynchronizerDirList : public QObject, public QHash { @@ -41,14 +41,12 @@ FileItem *first(); FileItem *next(); - inline const QString & url() { - return currentUrl; - } - bool load(const QString &urlIn, bool wait = false); + inline const QUrl &url() { return currentUrl; } + bool load(const QUrl &url, bool wait = false); public slots: - void slotEntries(KIO::Job * job, const KIO::UDSEntryList& entries); + void slotEntries(KIO::Job *job, const KIO::UDSEntryList &entries); void slotListResult(KJob *job); signals: @@ -60,7 +58,7 @@ bool busy; bool result; bool ignoreHidden; - QString currentUrl; + QUrl currentUrl; }; #endif /* __SYNCHRONIZER_DIR_LIST_H__ */ diff --git a/krusader/Synchronizer/synchronizerdirlist.cpp b/krusader/Synchronizer/synchronizerdirlist.cpp --- a/krusader/Synchronizer/synchronizerdirlist.cpp +++ b/krusader/Synchronizer/synchronizerdirlist.cpp @@ -34,25 +34,27 @@ #include #include -#include #include +#include #include +#include "../krservices.h" +#include "../FileSystem/fileitem.h" #include "../FileSystem/filesystem.h" #include "../FileSystem/krpermhandler.h" -#include "../krservices.h" -SynchronizerDirList::SynchronizerDirList(QWidget *w, bool hidden) : QObject(), QHash(), fileIterator(0), - parentWidget(w), busy(false), result(false), ignoreHidden(hidden), currentUrl() +SynchronizerDirList::SynchronizerDirList(QWidget *w, bool hidden) + : QObject(), QHash(), fileIterator(0), parentWidget(w), busy(false), + result(false), ignoreHidden(hidden), currentUrl() { } SynchronizerDirList::~SynchronizerDirList() { if (fileIterator) delete fileIterator; - QHashIterator< QString, FileItem *> lit(*this); + QHashIterator lit(*this); while (lit.hasNext()) delete lit.next().value(); } @@ -62,14 +64,15 @@ if (!ignoreCase) { if (!contains(name)) return 0; - return (*this)[ name ]; + return (*this)[name]; } QHashIterator iter(*this); iter.toFront(); QString file = name.toLower(); + // TODO use a map while (iter.hasNext()) { FileItem *item = iter.next().value(); if (file == item->getName().toLower()) @@ -81,7 +84,7 @@ FileItem *SynchronizerDirList::first() { if (fileIterator == 0) - fileIterator = new QHashIterator (*this); + fileIterator = new QHashIterator(*this); fileIterator->toFront(); if (fileIterator->hasNext()) @@ -92,22 +95,21 @@ FileItem *SynchronizerDirList::next() { if (fileIterator == 0) - fileIterator = new QHashIterator (*this); + fileIterator = new QHashIterator(*this); if (fileIterator->hasNext()) return fileIterator->next().value(); return 0; } -bool SynchronizerDirList::load(const QString &urlIn, bool wait) +bool SynchronizerDirList::load(const QUrl &url, bool wait) { if (busy) return false; - currentUrl = urlIn; - const QUrl url = QUrl::fromUserInput(urlIn, QString(), QUrl::AssumeLocalFile); + currentUrl = url; - QHashIterator< QString, FileItem *> lit(*this); + QHashIterator lit(*this); while (lit.hasNext()) delete lit.next().value(); clear(); @@ -119,20 +121,23 @@ if (url.isLocalFile()) { const QString dir = FileSystem::ensureTrailingSlash(url).path(); - QT_DIR* qdir = QT_OPENDIR(dir.toLocal8Bit()); - if (!qdir) { - KMessageBox::error(parentWidget, i18n("Cannot open the folder %1.", dir), i18n("Error")); + QT_DIR *qdir = QT_OPENDIR(dir.toLocal8Bit()); + if (!qdir) { + KMessageBox::error(parentWidget, i18n("Cannot open the folder %1.", dir), + i18n("Error")); emit finished(result = false); return false; } - QT_DIRENT* dirEnt; + QT_DIRENT *dirEnt; while ((dirEnt = QT_READDIR(qdir)) != NULL) { const QString name = QString::fromLocal8Bit(dirEnt->d_name); - if (name == "." || name == "..") continue; - if (ignoreHidden && name.startsWith('.')) continue; + if (name == "." || name == "..") + continue; + if (ignoreHidden && name.startsWith('.')) + continue; FileItem *item = FileSystem::createLocalFileItem(name, dir); @@ -144,10 +149,9 @@ return true; } else { KIO::Job *job = KIO::listDir(KrServices::escapeFileUrl(url), KIO::HideProgressInfo, true); - connect(job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)), - this, SLOT(slotEntries(KIO::Job*,KIO::UDSEntryList))); - connect(job, SIGNAL(result(KJob*)), - this, SLOT(slotListResult(KJob*))); + connect(job, SIGNAL(entries(KIO::Job *, KIO::UDSEntryList)), this, + SLOT(slotEntries(KIO::Job *, KIO::UDSEntryList))); + connect(job, SIGNAL(result(KJob *)), this, SLOT(slotListResult(KJob *))); busy = true; if (!wait) @@ -159,7 +163,7 @@ } } -void SynchronizerDirList::slotEntries(KIO::Job *job, const KIO::UDSEntryList& entries) +void SynchronizerDirList::slotEntries(KIO::Job *job, const KIO::UDSEntryList &entries) { KIO::ListJob *listJob = static_cast(job); for (const KIO::UDSEntry entry : entries) { @@ -180,4 +184,3 @@ } emit finished(result = true); } - diff --git a/krusader/Synchronizer/synchronizerfileitem.h b/krusader/Synchronizer/synchronizerfileitem.h --- a/krusader/Synchronizer/synchronizerfileitem.h +++ b/krusader/Synchronizer/synchronizerfileitem.h @@ -23,213 +23,99 @@ // QtCore #include +#include #include +#include "../FileSystem/fileitem.h" + +class SyncViewItem; + typedef enum { - TT_EQUALS = 0, // the files are equals -> do nothing - TT_DIFFERS = 1, // the files are differents -> don't know what to do - TT_COPY_TO_LEFT = 2, // the right file is newer -> copy from right to left - TT_COPY_TO_RIGHT = 3, // the left file is newer -> copy from left to right - TT_DELETE = 4, // the left file is single -> delete it - TT_UNKNOWN = 5, // (5-9) the type of the task is not yet known - TT_MAX = 10 // the maximum number of task types + TT_EQUALS = 0, // the files are equals -> do nothing + TT_DIFFERS = 1, // the files are differents -> don't know what to do + TT_COPY_TO_LEFT = 2, // the right file is newer -> copy from right to left + TT_COPY_TO_RIGHT = 3, // the left file is newer -> copy from left to right + TT_DELETE = 4, // the left file is single -> delete it + TT_UNKNOWN = 5, // (5-9) the type of the task is not yet known + TT_MAX = 10 // the maximum number of task types } TaskType; -#define SWAP( A, B, TYPE ) {TYPE TMP = A; A = B; B = TMP;} -#define REVERSE_TASK( A, asym ) {switch( A ) \ - { \ - case TT_COPY_TO_LEFT: \ - if( asym ) \ - A = !m_existsRight ? TT_DELETE : TT_COPY_TO_LEFT; \ - else \ - A = TT_COPY_TO_RIGHT; \ - break; \ - case TT_COPY_TO_RIGHT: \ - case TT_DELETE: \ - A = TT_COPY_TO_LEFT; \ - default: \ - break; \ - }}; - class SynchronizerFileItem { -private: - QString m_leftName; // the left file name - QString m_rightName; // the right file name - QString m_leftDirectory;// the left relative directory path from the base - QString m_rightDirectory;// the left relative directory path from the base - bool m_marked; // flag, indicates to show the file - bool m_existsLeft; // flag, the file exists in the left directory - bool m_existsRight; // flag, the file exists in the right directory - KIO::filesize_t m_leftSize; // the file size at the left directory - KIO::filesize_t m_rightSize; // the file size at the right directory - time_t m_leftDate; // the file date at the left directory - time_t m_rightDate; // the file date at the left directory - QString m_leftLink; // the left file's symbolic link destination - QString m_rightLink; // the right file's symbolic link destination - QString m_leftOwner; // the left file's owner - QString m_rightOwner; // the right file's owner - QString m_leftGroup; // the left file's group - QString m_rightGroup; // the right file's group - mode_t m_leftMode; // mode for left - mode_t m_rightMode; // mode for right - QString m_leftACL; // ACL of the left file - QString m_rightACL; // ACL of the right file - TaskType m_task; // the task with the file - bool m_isDir; // flag, indicates that the file is a directory - SynchronizerFileItem *m_parent; // pointer to the parent directory item or 0 - void *m_userData; // user data - bool m_overWrite; // overwrite flag - QString m_destination; // the destination URL at rename - bool m_temporary; // flag indicates temporary directory - TaskType m_originalTask; // the original task type - public: - SynchronizerFileItem(const QString &leftNam, const QString &rightNam, const QString &leftDir, - const QString &rightDir, bool mark, bool exL, bool exR, KIO::filesize_t leftSize, - KIO::filesize_t rightSize, time_t leftDate, time_t rightDate, - const QString &leftLink, const QString &rightLink, const QString &leftOwner, - const QString &rightOwner, const QString &leftGroup, const QString &rightGroup, - mode_t leftMode, mode_t rightMode, const QString &leftACL, const QString &rightACL, - TaskType tsk, bool isDir, bool tmp, SynchronizerFileItem *parent) : - m_leftName(leftNam), m_rightName(rightNam), m_leftDirectory(leftDir), m_rightDirectory(rightDir), - m_marked(mark), m_existsLeft(exL), m_existsRight(exR), m_leftSize(leftSize), - m_rightSize(rightSize), m_leftDate(leftDate), m_rightDate(rightDate), - m_leftLink(leftLink), m_rightLink(rightLink), m_leftOwner(leftOwner), - m_rightOwner(rightOwner), m_leftGroup(leftGroup), m_rightGroup(rightGroup), - m_leftMode(leftMode), m_rightMode(rightMode), m_leftACL(leftACL), - m_rightACL(rightACL), m_task(tsk), m_isDir(isDir), m_parent(parent), - m_userData(0), m_overWrite(false), m_destination(QString()), - m_temporary(tmp), m_originalTask(tsk) {} - - inline bool isMarked() { - return m_marked; - } - inline void setMarked(bool flag) { - m_marked = flag; - } - inline const QString & leftName() { - return m_leftName; - } - inline const QString & rightName() { - return m_rightName; - } - inline const QString & leftDirectory() { - return m_leftDirectory; - } - inline const QString & rightDirectory() { - return m_rightDirectory; - } - inline bool existsInLeft() { - return m_existsLeft; - } - inline bool existsInRight() { - return m_existsRight; - } - inline bool overWrite() { - return m_overWrite; - } - inline KIO::filesize_t leftSize() { - return m_leftSize; - } - inline KIO::filesize_t rightSize() { - return m_rightSize; - } - inline time_t leftDate() { - return m_leftDate; - } - inline time_t rightDate() { - return m_rightDate; - } - inline const QString & leftLink() { - return m_leftLink; - } - inline const QString & rightLink() { - return m_rightLink; - } - inline const QString & leftOwner() { - return m_leftOwner; - } - inline const QString & rightOwner() { - return m_rightOwner; - } - inline const QString & leftGroup() { - return m_leftGroup; - } - inline const QString & rightGroup() { - return m_rightGroup; - } - inline mode_t leftMode() { - return m_leftMode; - } - inline mode_t rightMode() { - return m_rightMode; - } - inline const QString & leftACL() { - return m_leftACL; - } - inline const QString & rightACL() { - return m_rightACL; - } - inline TaskType task() { - return m_task; - } - inline void compareContentResult(bool res) { - if (res == true) - m_task = m_originalTask = TT_EQUALS; - else if (m_originalTask >= TT_UNKNOWN) - m_task = m_originalTask = (TaskType)(m_originalTask - TT_UNKNOWN); - } - inline bool isDir() { - return m_isDir; - } - inline SynchronizerFileItem * parent() { - return m_parent; - } - inline void * userData() { - return m_userData; - } - inline void setUserData(void *ud) { - m_userData = ud; - } - inline void setOverWrite() { - m_overWrite = true; - } - inline const QString & destination() { - return m_destination; - } - inline void setDestination(QString d) { - m_destination = d; - } - inline bool isTemporary() { - return m_temporary; - } - inline void setPermanent() { - m_temporary = false; - } - inline TaskType originalTask() { - return m_originalTask; - } - inline void restoreOriginalTask() { - m_task = m_originalTask; - } - inline void setTask(TaskType t) { - m_task = t; - } - inline void swap(bool asym = false) { - SWAP(m_existsLeft, m_existsRight, bool); - SWAP(m_leftName, m_rightName, QString); - SWAP(m_leftDirectory, m_rightDirectory, QString); - SWAP(m_leftSize, m_rightSize, KIO::filesize_t); - SWAP(m_leftDate, m_rightDate, time_t); - SWAP(m_leftLink, m_rightLink, QString); - SWAP(m_leftOwner, m_rightOwner, QString); - SWAP(m_leftGroup, m_rightGroup, QString); - SWAP(m_leftACL, m_rightACL, QString); - REVERSE_TASK(m_originalTask, asym); - REVERSE_TASK(m_task, asym); + SynchronizerFileItem(const FileItem &leftFile, const FileItem &rightFile, + const QString &leftDir, const QString &rightDir, + bool mark, TaskType tsk, bool tmp, SynchronizerFileItem *parent); + + inline bool existsLeft() const { return !m_leftFile.getName().isNull(); } + inline bool existsRight() const { return !m_rightFile.getName().isNull(); } + inline bool isDir() const + { + return !m_leftFile.getName().isNull() ? m_leftFile.isDir() : m_rightFile.isDir(); } + + inline const QString &leftName() const + { + return existsLeft() ? m_leftFile.getName() : m_rightFile.getName(); + } + inline const QString &rightName() const + { + return existsRight() ? m_rightFile.getName() : m_leftFile.getName(); + } + inline KIO::filesize_t leftSize() const { return m_leftFile.getSize(); } + inline KIO::filesize_t rightSize() const { return m_rightFile.getSize(); } + inline time_t leftDate() const { return m_leftFile.getTime_t(); } + inline time_t rightDate() const { return m_rightFile.getTime_t(); } + inline const QString &leftLink() const { return m_leftFile.getSymDest(); } + inline const QString &rightLink() const { return m_rightFile.getSymDest(); } + inline const QString &leftOwner() const { return m_leftFile.getOwner(); } + inline const QString &rightOwner() const { return m_rightFile.getOwner(); } + inline const QString &leftGroup() const { return m_leftFile.getGroup(); } + inline const QString &rightGroup() const { return m_rightFile.getGroup(); } + inline mode_t leftMode() const { return m_leftFile.getMode(); } + inline mode_t rightMode() const { return m_rightFile.getMode(); } + inline const QString &leftACL() { return m_leftFile.getACL(); } + inline const QString &rightACL() { return m_rightFile.getACL(); } + + inline bool isMarked() const { return m_marked; } + inline const QString &leftDirectory() const { return m_leftDirectory; } + inline const QString &rightDirectory() const { return m_rightDirectory; } + inline bool overWrite() const { return m_overWrite; } + inline TaskType task() const { return m_task; } + inline SynchronizerFileItem *parent() const { return m_parent; } + inline SyncViewItem *viewItem() const { return m_viewItem; } + inline const QUrl &destination() const { return m_destination; } + inline bool isTemporary() const { return m_temporary; } + inline TaskType originalTask() const { return m_originalTask; } + + inline void setMarked(bool flag) { m_marked = flag; } + inline void setPermanent() { m_temporary = false; } + inline void restoreOriginalTask() { m_task = m_originalTask; } + inline void setViewItem(SyncViewItem *viewItem) { m_viewItem = viewItem; } + inline void setOverWrite() { m_overWrite = true; } + inline void setDestination(QUrl d) { m_destination = d; } + inline void setTask(TaskType t) { m_task = t; } + + void compareContentResult(bool res); + void swap(bool asym = false); + +private: + void reverseTask(TaskType &taskType, bool asym); + + FileItem m_leftFile; + FileItem m_rightFile; + QString m_leftDirectory; // the left relative directory path from the base + QString m_rightDirectory; // the left relative directory path from the base + + bool m_marked; // flag, indicates to show the file + TaskType m_task; // the task with the file + SynchronizerFileItem *m_parent; // pointer to the parent directory item or 0 + SyncViewItem *m_viewItem; // user data + bool m_overWrite; // overwrite flag + QUrl m_destination; // the destination URL at rename + bool m_temporary; // flag indicates temporary directory + TaskType m_originalTask; // the original task type }; #endif /* __SYNCHRONIZER_FILE_ITEM_H__ */ diff --git a/krusader/Synchronizer/synchronizerfileitem.cpp b/krusader/Synchronizer/synchronizerfileitem.cpp new file mode 100644 --- /dev/null +++ b/krusader/Synchronizer/synchronizerfileitem.cpp @@ -0,0 +1,69 @@ +/***************************************************************************** + * Copyright (C) 2017 Krusader Krew * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This package is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this package; if not, write to the Free Software * + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * + *****************************************************************************/ + +#include + +#define SWAP(A, B, TYPE) \ + { \ + TYPE TMP = A; \ + A = B; \ + B = TMP; \ + } + +SynchronizerFileItem::SynchronizerFileItem(const FileItem &leftFile, const FileItem &rightFile, + const QString &leftDir, const QString &rightDir, + bool mark, TaskType tsk, bool tmp, + SynchronizerFileItem *parent) + : m_leftFile(leftFile), m_rightFile(rightFile), m_leftDirectory(leftDir), + m_rightDirectory(rightDir), m_marked(mark), m_task(tsk), m_parent(parent), m_viewItem(0), + m_overWrite(false), m_destination(QUrl()), m_temporary(tmp), m_originalTask(tsk) +{ +} + +void SynchronizerFileItem::compareContentResult(bool res) +{ + if (res == true) + m_task = m_originalTask = TT_EQUALS; + else if (m_originalTask >= TT_UNKNOWN) + m_task = m_originalTask = (TaskType)(m_originalTask - TT_UNKNOWN); +} + +void SynchronizerFileItem::swap(bool asym) +{ + SWAP(m_leftFile, m_rightFile, FileItem); + SWAP(m_leftDirectory, m_rightDirectory, QString); + reverseTask(m_originalTask, asym); + reverseTask(m_task, asym); +} + +void SynchronizerFileItem::reverseTask(TaskType &taskType, bool asym) +{ + switch (taskType) { + case TT_COPY_TO_LEFT: + if (asym) + taskType = !existsRight() ? TT_DELETE : TT_COPY_TO_LEFT; + else + taskType = TT_COPY_TO_RIGHT; + break; + case TT_COPY_TO_RIGHT: + case TT_DELETE: + taskType = TT_COPY_TO_LEFT; + default: + break; + } +} diff --git a/krusader/Synchronizer/synchronizergui.h b/krusader/Synchronizer/synchronizergui.h --- a/krusader/Synchronizer/synchronizergui.h +++ b/krusader/Synchronizer/synchronizergui.h @@ -24,117 +24,71 @@ // QtCore #include // QtGui -#include #include #include +#include // QtWidgets #include #include #include +#include #include +#include #include +#include #include "synchronizer.h" -#include "../GUI/profilemanager.h" -#include "../GUI/krtreewidget.h" -#include "../Filter/filtertabs.h" -#include "../Filter/generalfilter.h" -class QSpinBox; +class FilterTabs; +class GeneralFilter; +class KrTreeWidget; +class ProfileManager; -class SynchronizerGUI : public QDialog +class SyncViewItem : public QTreeWidgetItem { - Q_OBJECT +private: + SynchronizerFileItem *syncItemRef; + SyncViewItem *lastItemRef; public: - class SyncViewItem : public QTreeWidgetItem - { - private: - SynchronizerFileItem *syncItemRef; - SyncViewItem *lastItemRef; - - public: - SyncViewItem(SynchronizerFileItem *item, QColor txt, QColor base, QTreeWidget * parent, QTreeWidgetItem *after, QString label1, - QString label2 = QString(), QString label3 = QString(), QString label4 = QString(), - QString label5 = QString(), QString label6 = QString(), - QString label7 = QString(), QString label8 = QString()) : - QTreeWidgetItem(parent, after), syncItemRef(item), lastItemRef(0) { - setText(0, label1); - setText(1, label2); - setText(2, label3); - setText(3, label4); - setText(4, label5); - setText(5, label6); - setText(6, label7); - setText(7, label8); - - setTextAlignment(1, Qt::AlignRight); - setTextAlignment(3, Qt::AlignHCenter); - setTextAlignment(5, Qt::AlignRight); - item->setUserData((void *)this); - - setColors(txt, base); - } - - SyncViewItem(SynchronizerFileItem *item, QColor txt, QColor base, QTreeWidgetItem * parent, QTreeWidgetItem *after, QString label1, - QString label2 = QString(), QString label3 = QString(), QString label4 = QString(), - QString label5 = QString(), QString label6 = QString(), - QString label7 = QString(), QString label8 = QString()) : - QTreeWidgetItem(parent, after), syncItemRef(item), lastItemRef(0) { - setText(0, label1); - setText(1, label2); - setText(2, label3); - setText(3, label4); - setText(4, label5); - setText(5, label6); - setText(6, label7); - setText(7, label8); - - setTextAlignment(1, Qt::AlignRight); - setTextAlignment(3, Qt::AlignHCenter); - setTextAlignment(5, Qt::AlignRight); - item->setUserData((void *)this); - - setColors(txt, base); - } - - ~SyncViewItem() { - syncItemRef->setUserData(0); - } - - inline SynchronizerFileItem * synchronizerItemRef() { - return syncItemRef; - } - inline SyncViewItem * lastItem() { - return lastItemRef; - } - inline void setLastItem(SyncViewItem*s) { - lastItemRef = s; - } - - void setColors(QColor fore, QColor back) { - QBrush textColor(fore); - QBrush baseColor(back); - - for (int i = 0; i != columnCount(); i++) { - if (back.isValid()) - setBackground(i, baseColor); - if (fore.isValid()) - setForeground(i, textColor); - } - } - }; + SyncViewItem(SynchronizerFileItem *item, const QColor &txt, const QColor &base, + QTreeWidget *parent, QTreeWidgetItem *after, const QString &label1, + const QString &label2, const QString &label3, const QString &label4, + const QString &label5, const QString &label6, const QString &label7); + + SyncViewItem(SynchronizerFileItem *item, const QColor &txt, const QColor &base, + QTreeWidgetItem *parent, QTreeWidgetItem *after, const QString &label1, + const QString &label2, const QString &label3, const QString &label4, + const QString &label5, const QString &label6, const QString &label7); + + ~SyncViewItem() { syncItemRef->setViewItem(nullptr); } + + inline SynchronizerFileItem *synchronizerItemRef() { return syncItemRef; } + inline SyncViewItem *lastItem() { return lastItemRef; } + inline void setLastItem(SyncViewItem *s) { lastItemRef = s; } + + void setColors(const QColor &fore, const QColor &back); + +private: + void setColumns(const QString &label1, const QString &label2, const QString &label3, + const QString &label4, const QString &label5, const QString &label6, + const QString &label7, SynchronizerFileItem *item, const QColor &txt, + const QColor &base); +}; + +class SynchronizerGUI : public QDialog +{ + Q_OBJECT public: // if rightDirectory is null, leftDirectory is actually the profile name to load - SynchronizerGUI(QWidget* parent, QUrl leftDirectory, QUrl rightDirectory = QUrl(), QStringList selList = QStringList()); - SynchronizerGUI(QWidget* parent, QString profile); + SynchronizerGUI(QWidget *parent, QUrl leftDirectory, QUrl rightDirectory = QUrl(), + QStringList selList = QStringList()); + SynchronizerGUI(QWidget *parent, QString profile); ~SynchronizerGUI(); - inline bool wasSynchronization() { - return wasSync; - } + inline bool wasSynchronization() { return wasSync; } public slots: void rightMouseClicked(QTreeWidgetItem *, const QPoint &); @@ -165,13 +119,13 @@ void initGUI(QString profile, QUrl leftURL, QUrl rightURL, QStringList selList); QString convertTime(time_t time) const; - void setMarkFlags(); - void disableMarkButtons(); - void enableMarkButtons(); - void copyToClipboard(bool isLeft); + void setMarkFlags(); + void disableMarkButtons(); + void enableMarkButtons(); + void copyToClipboard(bool isLeft); - int convertToSeconds(int time, int unit); - void convertFromSeconds(int &time, int &unit, int second); + int convertToSeconds(int time, int unit); + void convertFromSeconds(int &time, int &unit, int second); static QPushButton *createButton(QWidget *parent, const QString &iconName, bool checked, const QKeySequence &shortCut, const QString &description, @@ -234,6 +188,8 @@ private: static QString dirLabel(); // returns translated '' + static KHistoryComboBox *createHistoryComboBox(QWidget *parent, bool enabled); + static QUrl getUrl(KHistoryComboBox *location); bool isComparing; bool wasClosed; diff --git a/krusader/Synchronizer/synchronizergui.cpp b/krusader/Synchronizer/synchronizergui.cpp --- a/krusader/Synchronizer/synchronizergui.cpp +++ b/krusader/Synchronizer/synchronizergui.cpp @@ -19,44 +19,50 @@ *****************************************************************************/ #include "synchronizergui.h" -#include "../krglobal.h" -#include "../filelisticon.h" -#include "../defaults.h" -#include "../krusaderview.h" -#include "../Panel/listpanel.h" -#include "../Panel/panelfunc.h" -#include "../FileSystem/krpermhandler.h" -#include "../KViewer/krviewer.h" + +#include "feedtolistboxdialog.h" +#include "synchronizedialog.h" +#include "synchronizercolors.h" #include "../Dialogs/krspwidgets.h" +#include "../FileSystem/krpermhandler.h" #include "../FileSystem/krquery.h" +#include "../Filter/filtertabs.h" +#include "../Filter/generalfilter.h" +#include "../GUI/krtreewidget.h" +#include "../GUI/profilemanager.h" +#include "../KViewer/krviewer.h" +#include "../Panel/listpanel.h" +#include "../Panel/panelfunc.h" +#include "../defaults.h" +#include "../filelisticon.h" +#include "../icon.h" +#include "../krglobal.h" #include "../krservices.h" #include "../krslots.h" -#include "synchronizedialog.h" -#include "feedtolistboxdialog.h" -#include "synchronizercolors.h" +#include "../krusaderview.h" // QtCore #include -#include -#include #include +#include +#include // QtGui -#include +#include +#include +#include #include #include #include -#include -#include -#include +#include // QtWidgets #include -#include +#include #include -#include #include #include -#include #include +#include +#include #include #include @@ -66,6 +72,58 @@ #include #include +SyncViewItem::SyncViewItem(SynchronizerFileItem *item, const QColor &txt, const QColor &base, + QTreeWidget *parent, QTreeWidgetItem *after, const QString &label1, + const QString &label2, const QString &label3, const QString &label4, + const QString &label5, const QString &label6, const QString &label7) + : QTreeWidgetItem(parent, after), syncItemRef(item), lastItemRef(0) +{ + setColumns(label1, label2, label3, label4, label5, label6, label7, item, txt, base); +} + +SyncViewItem::SyncViewItem(SynchronizerFileItem *item, const QColor &txt, const QColor &base, + QTreeWidgetItem *parent, QTreeWidgetItem *after, const QString &label1, + const QString &label2, const QString &label3, const QString &label4, + const QString &label5, const QString &label6, const QString &label7) + : QTreeWidgetItem(parent, after), syncItemRef(item), lastItemRef(0) +{ + setColumns(label1, label2, label3, label4, label5, label6, label7, item, txt, base); +} + +void SyncViewItem::setColumns(const QString &label1, const QString &label2, const QString &label3, + const QString &label4, const QString &label5, const QString &label6, + const QString &label7, SynchronizerFileItem *item, const QColor &txt, + const QColor &base) +{ + setText(0, label1); + setText(1, label2); + setText(2, label3); + setText(3, label4); + setText(4, label5); + setText(5, label6); + setText(6, label7); + + setTextAlignment(1, Qt::AlignRight); + setTextAlignment(3, Qt::AlignHCenter); + setTextAlignment(5, Qt::AlignRight); + item->setViewItem(this); + + setColors(txt, base); +} + +void SyncViewItem::setColors(const QColor &fore, const QColor &back) +{ + QBrush textColor(fore); + QBrush baseColor(back); + + for (int i = 0; i != columnCount(); i++) { + if (back.isValid()) + setBackground(i, baseColor); + if (fore.isValid()) + setForeground(i, textColor); + } +} + class SynchronizerListView : public KrTreeWidget { @@ -89,20 +147,20 @@ SynchronizerFileItem *currentItem; while ((currentItem = synchronizer->getItemAt(ndx++)) != 0) { - SynchronizerGUI::SyncViewItem *viewItem = (SynchronizerGUI::SyncViewItem *)currentItem->userData(); + SyncViewItem *viewItem = (SyncViewItem *)currentItem->viewItem(); if (!viewItem || !viewItem->isSelected() || viewItem->isHidden()) continue; SynchronizerFileItem *item = viewItem->synchronizerItemRef(); if (item) { - if (isLeft && item->existsInLeft()) { - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer->leftBaseDirectory() + leftDirName + item->leftName()); + if (isLeft && item->existsLeft()) { + const QUrl leftURL = Synchronizer::pathAppend( + synchronizer->leftBaseDirectory(), item->leftDirectory(), item->leftName()); urls.push_back(leftURL); - } else if (!isLeft && item->existsInRight()) { - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - QUrl rightURL = Synchronizer::fsUrl(synchronizer->rightBaseDirectory() + rightDirName + item->rightName()); + } else if (!isLeft && item->existsRight()) { + const QUrl rightURL = Synchronizer::pathAppend( + synchronizer->rightBaseDirectory(), item->rightDirectory(), item->rightName()); urls.push_back(rightURL); } } @@ -165,80 +223,83 @@ synchronizerGrid->setSpacing(6); synchronizerGrid->setContentsMargins(11, 11, 11, 11); - QGroupBox *compareDirs = new QGroupBox(synchronizerTab); - compareDirs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - compareDirs->setTitle(i18n("Folder Comparison")); + QGroupBox *compareGroupBox = new QGroupBox(synchronizerTab); + compareGroupBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + compareGroupBox->setTitle(i18n("Folder Comparison")); - QGridLayout *grid = new QGridLayout(compareDirs); + QGridLayout *grid = new QGridLayout(compareGroupBox); grid->setSpacing(6); grid->setContentsMargins(11, 11, 11, 11); - leftDirLabel = new QLabel(compareDirs); + leftDirLabel = new QLabel(compareGroupBox); leftDirLabel->setAlignment(Qt::AlignHCenter); grid->addWidget(leftDirLabel, 0 , 0); - QLabel *filterLabel = new QLabel(compareDirs); + QLabel *filterLabel = new QLabel(compareGroupBox); filterLabel->setText(i18n("File &Filter:")); filterLabel->setAlignment(Qt::AlignHCenter); grid->addWidget(filterLabel, 0 , 1); - rightDirLabel = new QLabel(compareDirs); + rightDirLabel = new QLabel(compareGroupBox); rightDirLabel->setAlignment(Qt::AlignHCenter); grid->addWidget(rightDirLabel, 0 , 2); KConfigGroup group(krConfig, "Synchronize"); - leftLocation = new KHistoryComboBox(false, compareDirs); - leftLocation->setMaxCount(25); // remember 25 items - leftLocation->setDuplicatesEnabled(false); - leftLocation->setEditable(true); - leftLocation->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); - QStringList list = group.readEntry("Left Folder History", QStringList()); - leftLocation->setHistoryItems(list); - KUrlRequester *leftUrlReq = new KUrlRequester(leftLocation, compareDirs); + leftLocation = createHistoryComboBox(compareGroupBox, !hasSelectedFiles); + leftLocation->setHistoryItems(group.readEntry("Left Folder History", QStringList())); + leftLocation->setWhatsThis(i18n("The left base folder used during the synchronization process.")); + leftDirLabel->setBuddy(leftLocation); + KUrlRequester *leftUrlReq = new KUrlRequester(leftLocation, compareGroupBox); leftUrlReq->setUrl(leftURL); leftUrlReq->setMode(KFile::Directory); leftUrlReq->setMinimumWidth(250); - grid->addWidget(leftUrlReq, 1 , 0); - leftLocation->setWhatsThis(i18n("The left base folder used during the synchronization process.")); leftUrlReq->setEnabled(!hasSelectedFiles); - leftLocation->setEnabled(!hasSelectedFiles); - leftDirLabel->setBuddy(leftLocation); + grid->addWidget(leftUrlReq, 1 , 0); - fileFilter = new KHistoryComboBox(false, compareDirs); + fileFilter = new KHistoryComboBox(false, compareGroupBox); fileFilter->setMaxCount(25); // remember 25 items fileFilter->setDuplicatesEnabled(false); fileFilter->setMinimumWidth(100); fileFilter->setMaximumWidth(100); fileFilter->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - list = group.readEntry("File Filter", QStringList()); - fileFilter->setHistoryItems(list); + fileFilter->setHistoryItems(group.readEntry("File Filter", QStringList())); fileFilter->setEditText("*"); grid->addWidget(fileFilter, 1 , 1); filterLabel->setBuddy(fileFilter); - QString wtFilter = "

" + i18n("

The filename filtering criteria is defined here.

You can make use of wildcards. Multiple patterns are separated by space (means logical OR) and patterns are excluded from the search using the pipe symbol.

If the pattern is ended with a slash (*pattern*/), that means that pattern relates to recursive search of folders.

  • pattern - means to search those files/folders that name is pattern, recursive search goes through all subfolders independently of the value of pattern
  • pattern/ - means to search all files/folders, but recursive search goes through/excludes the folders that name is pattern

It is allowed to use quotation marks for names that contain space. Filter \"Program Files\" searches out those files/folders that name is Program Files.

Examples:

  • *.o
  • *.h *.c\?\?
  • *.cpp *.h | *.moc.cpp
  • * | .svn/ .git/

Note: the search term 'text' is equivalent to '*text*'.

"); + const QString wtFilter = + "

" + + i18n("

The filename filtering criteria is defined here.

You can make use of " + "wildcards. Multiple patterns are separated by space (means logical OR) and patterns " + "are excluded from the search using the pipe symbol.

If the pattern is ended " + "with a slash (*pattern*/), that means that pattern relates to recursive " + "search of folders.

  • pattern - means to search those files/folders " + "that name is pattern, recursive search goes through all subfolders " + "independently of the value of pattern
  • pattern/ - " + "means to search all files/folders, but recursive search goes through/excludes the " + "folders that name is pattern

It is allowed to use " + "quotation marks for names that contain space. Filter " + "\"Program Files\" searches out those files/folders that name is " + "Program Files.

Examples:

  • *.o
  • *.h *.c\?\?
  • *.cpp *.h | " + "*.moc.cpp
  • * | .svn/ .git/

Note: the " + "search term 'text' is equivalent to '*text*'.

"); fileFilter->setWhatsThis(wtFilter); filterLabel->setWhatsThis(wtFilter); - rightLocation = new KHistoryComboBox(compareDirs); - rightLocation->setMaxCount(25); // remember 25 items - rightLocation->setDuplicatesEnabled(false); - rightLocation->setEditable(true); - rightLocation->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); - list = group.readEntry("Right Folder History", QStringList()); - rightLocation->setHistoryItems(list); - KUrlRequester *rightUrlReq = new KUrlRequester(rightLocation, compareDirs); + rightLocation = createHistoryComboBox(compareGroupBox, !hasSelectedFiles); + rightLocation->setHistoryItems(group.readEntry("Right Folder History", QStringList())); + rightLocation->setWhatsThis(i18n("The right base folder used during the synchronization process.")); + rightDirLabel->setBuddy(rightLocation); + KUrlRequester *rightUrlReq = new KUrlRequester(rightLocation, compareGroupBox); rightUrlReq->setUrl(rightURL); rightUrlReq->setMode(KFile::Directory); rightUrlReq->setMinimumWidth(250); - grid->addWidget(rightUrlReq, 1 , 2); - rightLocation->setWhatsThis(i18n("The right base folder used during the synchronization process.")); rightUrlReq->setEnabled(!hasSelectedFiles); - rightLocation->setEnabled(!hasSelectedFiles); - rightDirLabel->setBuddy(rightLocation); + grid->addWidget(rightUrlReq, 1 , 2); - QWidget *optionWidget = new QWidget(compareDirs); + QWidget *optionWidget = new QWidget(compareGroupBox); QHBoxLayout *optionBox = new QHBoxLayout(optionWidget); optionBox->setContentsMargins(0, 0, 0, 0); @@ -263,15 +324,22 @@ cbIgnoreDate = new QCheckBox(i18n("Ignore Date"), optionGridWidget); cbIgnoreDate->setChecked(group.readEntry("Ignore Date", _IgnoreDate)); optionGrid->addWidget(cbIgnoreDate, 1, 0); - cbIgnoreDate->setWhatsThis(i18n("

Ignore date information during the compare process.

Note: useful if the files are located on network filesystems or in archives.

")); + cbIgnoreDate->setWhatsThis( + i18n("

Ignore date information during the compare process.

Note: useful if " + "the files are located on network filesystems or in archives.

")); cbAsymmetric = new QCheckBox(i18n("Asymmetric"), optionGridWidget); cbAsymmetric->setChecked(group.readEntry("Asymmetric", _Asymmetric)); optionGrid->addWidget(cbAsymmetric, 1, 1); - cbAsymmetric->setWhatsThis(i18n("

Asymmetric mode

The left side is the destination, the right is the source folder. Files existing only in the left folder will be deleted, the other differing ones will be copied from right to left.

Note: useful when updating a folder from a file server.

")); + cbAsymmetric->setWhatsThis( + i18n("

Asymmetric mode

The left side is the destination, the right is the " + "source folder. Files existing only in the left folder will be deleted, the other " + "differing ones will be copied from right to left.

Note: useful when " + "updating a folder from a file server.

")); cbIgnoreCase = new QCheckBox(i18n("Ignore Case"), optionGridWidget); cbIgnoreCase->setChecked(group.readEntry("Ignore Case", _IgnoreCase)); optionGrid->addWidget(cbIgnoreCase, 1, 2); - cbIgnoreCase->setWhatsThis(i18n("

Case insensitive filename compare.

Note: useful when synchronizing Windows filesystems.

")); + cbIgnoreCase->setWhatsThis(i18n("

Case insensitive filename compare.

Note: " + "useful when synchronizing Windows filesystems.

")); /* =========================== Show options groupbox ============================= */ @@ -332,7 +400,7 @@ grid->addWidget(optionWidget, 2, 0, 1, 3); - synchronizerGrid->addWidget(compareDirs, 0, 0); + synchronizerGrid->addWidget(compareGroupBox, 0, 0); /* ========================= Synchronization list view ========================== */ syncList = new SynchronizerListView(&synchronizer, synchronizerTab); // create the main container @@ -580,12 +648,16 @@ DECLARE_SYNCHRONIZER_FOREGROUND_DEFAULTS; for (int clr = 0; clr != TT_MAX; clr ++) { - QString colorName = clr > 4 ? "Equals" : COLOR_NAMES[ clr ]; - QColor backgroundDefault = clr > 4 ? defaultPalette.color(QPalette::Active, QPalette::Base) : SYNCHRONIZER_BACKGROUND_DEFAULTS[ clr ]; - QColor foregroundDefault = clr > 4 ? defaultPalette.color(QPalette::Active, QPalette::Text) : SYNCHRONIZER_FOREGROUND_DEFAULTS[ clr ]; + const QString colorName = clr > 4 ? "Equals" : COLOR_NAMES[clr]; + const QColor backgroundDefault = + clr > 4 ? defaultPalette.color(QPalette::Active, QPalette::Base) : + SYNCHRONIZER_BACKGROUND_DEFAULTS[clr]; + const QColor foregroundDefault = + clr > 4 ? defaultPalette.color(QPalette::Active, QPalette::Text) : + SYNCHRONIZER_FOREGROUND_DEFAULTS[clr]; - QString foreEntry = QString("Synchronizer ") + colorName + QString(" Foreground"); - QString bckgEntry = QString("Synchronizer ") + colorName + QString(" Background"); + const QString foreEntry = QString("Synchronizer ") + colorName + QString(" Foreground"); + const QString bckgEntry = QString("Synchronizer ") + colorName + QString(" Background"); if (gc.readEntry(foreEntry, QString()) == "KDE default") foreGrounds[ clr ] = QColor(); @@ -596,7 +668,7 @@ if (gc.readEntry(bckgEntry, QString()) == "KDE default") backGrounds[ clr ] = QColor(); - else if (gc.readEntry(foreEntry, QString()).isEmpty()) // KDE4 workaround, default color doesn't work + else if (gc.readEntry(foreEntry, QString()).isEmpty()) // KDE4 workaround, default color doesn't work backGrounds[ clr ] = backgroundDefault; else backGrounds[ clr ] = gc.readEntry(bckgEntry, backgroundDefault); @@ -658,28 +730,22 @@ void SynchronizerGUI::setCompletion() { - generalFilter->dontSearchIn->setCompletionDir(Synchronizer::fsUrl(rightLocation->currentText())); + generalFilter->dontSearchIn->setCompletionDir(getUrl(rightLocation)); } void SynchronizerGUI::checkExcludeURLValidity(QString &text, QString &error) { - QUrl url = Synchronizer::fsUrl(text); + const QUrl url(text); if (url.isRelative()) return; - QString leftBase = leftLocation->currentText(); - if (!leftBase.endsWith('/')) - leftBase += '/'; - QUrl leftBaseURL = Synchronizer::fsUrl(leftBase); + const QUrl leftBaseURL = getUrl(leftLocation); if (leftBaseURL.isParentOf(url) && !url.isParentOf(leftBaseURL)) { text = QDir(leftBaseURL.path()).relativeFilePath(url.path()); return; } - QString rightBase = rightLocation->currentText(); - if (!rightBase.endsWith('/')) - rightBase += '/'; - QUrl rightBaseURL = Synchronizer::fsUrl(rightBase); + const QUrl rightBaseURL = getUrl(rightLocation); if (rightBaseURL.isParentOf(url) && !url.isParentOf(rightBaseURL)) { text = QDir(rightBaseURL.path()).relativeFilePath(url.path()); return; @@ -695,11 +761,11 @@ SyncViewItem *syncItem = (SyncViewItem *)itemIn; SynchronizerFileItem *item = syncItem->synchronizerItemRef(); - if (item && item->existsInLeft() && item->existsInRight() && !item->isDir()) { - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer.leftBaseDirectory() + leftDirName + item->leftName()); - QUrl rightURL = Synchronizer::fsUrl(synchronizer.rightBaseDirectory() + rightDirName + item->rightName()); + if (item && item->existsLeft() && item->existsRight() && !item->isDir()) { + const QUrl leftURL = Synchronizer::pathAppend(synchronizer.leftBaseDirectory(), + item->leftDirectory(), item->leftName()); + const QUrl rightURL = Synchronizer::pathAppend(synchronizer.rightBaseDirectory(), + item->rightDirectory(), item->rightName()); SLOTS->compareContent(leftURL,rightURL); } else if (item && item->isDir()) { @@ -735,7 +801,7 @@ SynchronizerFileItem *item = syncItem->synchronizerItemRef(); - bool isDuplicate = item->existsInLeft() && item->existsInRight(); + bool isDuplicate = item->existsLeft() && item->existsRight(); bool isDir = item->isDir(); // create the menu @@ -761,10 +827,10 @@ popup.addSeparator(); myact = popup.addAction(i18n("V&iew left file")); - myact->setEnabled(!isDir && item->existsInLeft()); + myact->setEnabled(!isDir && item->existsLeft()); actHash[ myact ] = VIEW_LEFT_FILE_ID; myact = popup.addAction(i18n("Vi&ew right file")); - myact->setEnabled(!isDir && item->existsInRight()); + myact->setEnabled(!isDir && item->existsRight()); actHash[ myact ] = VIEW_RIGHT_FILE_ID; myact = popup.addAction(i18n("&Compare Files")); myact->setEnabled(!isDir && isDuplicate); @@ -786,8 +852,8 @@ myact = popup.addAction(i18n("I&nvert selection")); actHash[ myact ] = INVERT_SELECTION_ID; - QUrl leftBDir = Synchronizer::fsUrl(synchronizer.leftBaseDirectory()); - QUrl rightBDir = Synchronizer::fsUrl(synchronizer.rightBaseDirectory()); + const QUrl leftBDir = synchronizer.leftBaseDirectory(); + const QUrl rightBDir = synchronizer.rightBaseDirectory(); if (KrServices::cmdExist("kget") && ((!leftBDir.isLocalFile() && rightBDir.isLocalFile() && btnLeftToRight->isChecked()) || @@ -810,11 +876,11 @@ void SynchronizerGUI::executeOperation(SynchronizerFileItem *item, int op) { // check out the user's option - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer.leftBaseDirectory() + leftDirName + item->leftName()); - QUrl rightURL = Synchronizer::fsUrl(synchronizer.rightBaseDirectory() + rightDirName + item->rightName()); + const QUrl leftURL = Synchronizer::pathAppend(synchronizer.leftBaseDirectory(), + item->leftDirectory(), item->leftName()); + const QUrl rightURL = Synchronizer::pathAppend(synchronizer.rightBaseDirectory(), + item->rightDirectory(), item->rightName()); switch (op) { case EXCLUDE_ID: @@ -827,7 +893,7 @@ SynchronizerFileItem *currentItem; while ((currentItem = synchronizer.getItemAt(ndx++)) != 0) { - SyncViewItem *viewItem = (SyncViewItem *)currentItem->userData(); + SyncViewItem *viewItem = (SyncViewItem *)currentItem->viewItem(); if (!viewItem || !viewItem->isSelected() || viewItem->isHidden()) continue; @@ -877,7 +943,7 @@ SynchronizerFileItem *currentItem; while ((currentItem = synchronizer.getItemAt(ndx++)) != 0) { - SyncViewItem *viewItem = (SyncViewItem *)currentItem->userData(); + SyncViewItem *viewItem = (SyncViewItem *)currentItem->viewItem(); if (!viewItem || viewItem->isHidden()) continue; @@ -893,7 +959,7 @@ SynchronizerFileItem *currentItem; while ((currentItem = synchronizer.getItemAt(ndx++)) != 0) { - SyncViewItem *viewItem = (SyncViewItem *)currentItem->userData(); + SyncViewItem *viewItem = (SyncViewItem *)currentItem->viewItem(); if (!viewItem || viewItem->isHidden()) continue; @@ -984,9 +1050,8 @@ void SynchronizerGUI::compare() { - KRQuery query; - - if (!filterTabs->fillQuery(&query)) + KRQuery query = filterTabs->query(); + if (query.isNull()) return; // perform some previous tests @@ -1034,7 +1099,7 @@ btnScrollResults->show(); disableMarkButtons(); - int fileCount = synchronizer.compare(leftLocation->currentText(), rightLocation->currentText(), + int fileCount = synchronizer.compare(getUrl(leftLocation), getUrl(rightLocation), &query, cbSubdirs->isChecked(), cbSymlinks->isChecked(), cbIgnoreDate->isChecked(), cbAsymmetric->isChecked(), cbByContent->isChecked(), cbIgnoreCase->isChecked(), btnScrollResults->isChecked(), selectedFiles, @@ -1086,13 +1151,13 @@ QColor textColor = foreGrounds[ item->task()]; QColor baseColor = backGrounds[ item->task()]; - if (item->existsInLeft()) { + if (item->existsLeft()) { leftName = item->leftName(); leftSize = isDir ? dirLabel() + ' ' : KRpermHandler::parseSize(item->leftSize()); leftDate = SynchronizerGUI::convertTime(item->leftDate()); } - if (item->existsInRight()) { + if (item->existsRight()) { rightName = item->rightName(); rightSize = isDir ? dirLabel() + ' ' : KRpermHandler::parseSize(item->rightSize()); rightDate = SynchronizerGUI::convertTime(item->rightDate()); @@ -1107,7 +1172,7 @@ rightSize, rightName); lastItem = listItem; } else { - dirItem = (SyncViewItem *)item->parent()->userData(); + dirItem = (SyncViewItem *)item->parent()->viewItem(); if (dirItem) { dirItem->setExpanded(true); listItem = new SyncViewItem(item, textColor, baseColor, dirItem, dirItem->lastItem(), leftName, @@ -1129,21 +1194,21 @@ void SynchronizerGUI::markChanged(SynchronizerFileItem *item, bool ensureVisible) { - SyncViewItem *listItem = (SyncViewItem *)item->userData(); + SyncViewItem *listItem = (SyncViewItem *)item->viewItem(); if (listItem) { if (!item->isMarked()) { listItem->setHidden(true); } else { QString leftName = "", rightName = "", leftDate = "", rightDate = "", leftSize = "", rightSize = ""; bool isDir = item->isDir(); - if (item->existsInLeft()) { + if (item->existsLeft()) { leftName = item->leftName(); leftSize = isDir ? dirLabel() + ' ' : KRpermHandler::parseSize(item->leftSize()); leftDate = SynchronizerGUI::convertTime(item->leftDate()); } - if (item->existsInRight()) { + if (item->existsRight()) { rightName = item->rightName(); rightSize = isDir ? dirLabel() + ' ' : KRpermHandler::parseSize(item->rightSize()); rightDate = SynchronizerGUI::convertTime(item->rightDate()); @@ -1307,24 +1372,25 @@ if (listItem == 0) break; - bool isedit = e->key() == Qt::Key_F4; + const bool isedit = e->key() == Qt::Key_F4; SynchronizerFileItem *item = ((SyncViewItem *)listItem)->synchronizerItemRef(); - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - if (item->isDir()) return; - if (e->modifiers() == Qt::ShiftModifier && item->existsInRight()) { - QUrl rightURL = Synchronizer::fsUrl(synchronizer.rightBaseDirectory() + rightDirName + item->rightName()); + if (e->modifiers() == Qt::ShiftModifier && item->existsRight()) { + const QUrl rightURL = Synchronizer::pathAppend( + synchronizer.rightBaseDirectory(), item->rightDirectory(), item->rightName()); + if (isedit) KrViewer::edit(rightURL, this); // view the file else KrViewer::view(rightURL, this); // view the file return; - } else if (e->modifiers() == 0 && item->existsInLeft()) { - QUrl leftURL = Synchronizer::fsUrl(synchronizer.leftBaseDirectory() + leftDirName + item->leftName()); + } else if (e->modifiers() == 0 && item->existsLeft()) { + const QUrl leftURL = Synchronizer::pathAppend( + synchronizer.leftBaseDirectory(), item->leftDirectory(), item->leftName()); + if (isedit) KrViewer::edit(leftURL, this); // view the file else @@ -1346,9 +1412,11 @@ } else { e->accept(); if (syncList->topLevelItemCount() != 0) { - int result = KMessageBox::warningYesNo(this, i18n("The synchronizer window contains data from a previous compare. If you exit, this data will be lost. Do you really want to exit?"), - i18n("Krusader::Synchronize Folders"), - KStandardGuiItem::yes(), KStandardGuiItem::no(), "syncGUIexit"); + int result = KMessageBox::warningYesNo( + this, i18n("The synchronizer window contains data from a previous compare. If " + "you exit, this data will be lost. Do you really want to exit?"), + i18n("Krusader::Synchronize Folders"), KStandardGuiItem::yes(), + KStandardGuiItem::no(), "syncGUIexit"); if (result != KMessageBox::Yes) return; } @@ -1589,20 +1657,20 @@ SynchronizerFileItem *currentItem; while ((currentItem = synchronizer.getItemAt(ndx++)) != 0) { - SynchronizerGUI::SyncViewItem *viewItem = (SynchronizerGUI::SyncViewItem *)currentItem->userData(); + SyncViewItem *viewItem = (SyncViewItem *)currentItem->viewItem(); if (!viewItem || !viewItem->isSelected() || viewItem->isHidden()) continue; SynchronizerFileItem *item = viewItem->synchronizerItemRef(); if (item) { - if (isLeft && item->existsInLeft()) { - QString leftDirName = item->leftDirectory().isEmpty() ? "" : item->leftDirectory() + '/'; - QUrl leftURL = Synchronizer::fsUrl(synchronizer.leftBaseDirectory() + leftDirName + item->leftName()); + if (isLeft && item->existsLeft()) { + const QUrl leftURL = Synchronizer::pathAppend( + synchronizer.leftBaseDirectory(), item->leftDirectory(), item->leftName()); urls.push_back(leftURL); - } else if (!isLeft && item->existsInRight()) { - QString rightDirName = item->rightDirectory().isEmpty() ? "" : item->rightDirectory() + '/'; - QUrl rightURL = Synchronizer::fsUrl(synchronizer.rightBaseDirectory() + rightDirName + item->rightName()); + } else if (!isLeft && item->existsRight()) { + const QUrl rightURL = Synchronizer::pathAppend( + synchronizer.rightBaseDirectory(), item->rightDirectory(), item->rightName()); urls.push_back(rightURL); } } @@ -1626,3 +1694,18 @@ return label; } +KHistoryComboBox *SynchronizerGUI::createHistoryComboBox(QWidget *parent, bool enabled) +{ + KHistoryComboBox *location = new KHistoryComboBox(false, parent); + location->setMaxCount(25); // remember 25 items + location->setDuplicatesEnabled(false); + location->setEditable(true); + location->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); + location->setEnabled(enabled); + return location; +} + +QUrl SynchronizerGUI::getUrl(KHistoryComboBox *location) +{ + return QUrl::fromUserInput(location->currentText()); +} diff --git a/krusader/Synchronizer/synchronizertask.h b/krusader/Synchronizer/synchronizertask.h --- a/krusader/Synchronizer/synchronizertask.h +++ b/krusader/Synchronizer/synchronizertask.h @@ -32,11 +32,11 @@ class QTimer; class QFile; -#define ST_STATE_NEW 0 -#define ST_STATE_PENDING 1 -#define ST_STATE_STATUS 2 -#define ST_STATE_READY 3 -#define ST_STATE_ERROR 4 +#define ST_STATE_NEW 0 +#define ST_STATE_PENDING 1 +#define ST_STATE_STATUS 2 +#define ST_STATE_READY 3 +#define ST_STATE_ERROR 4 class SynchronizerTask : public QObject { @@ -46,21 +46,24 @@ SynchronizerTask() : QObject(), m_state(ST_STATE_NEW), m_statusMessage(QString()) {} virtual ~SynchronizerTask() {} - inline int start(QWidget *parentWidget) { - this->parentWidget = parentWidget; start(); return state(); + inline int start(QWidget *parentWidget) + { + this->parentWidget = parentWidget; + start(); + return state(); } - inline int state() { - return m_state; - } + inline int state() { return m_state; } - void setStatusMessage(const QString & statMsg) { + void setStatusMessage(const QString &statMsg) + { if (m_state == ST_STATE_PENDING || m_state == ST_STATE_STATUS) m_state = ST_STATE_STATUS; m_statusMessage = statMsg; } - QString status() { + QString status() + { if (m_state == ST_STATE_STATUS) { m_state = ST_STATE_PENDING; return m_statusMessage; @@ -75,101 +78,73 @@ QWidget *parentWidget; }; - class CompareTask : public SynchronizerTask { Q_OBJECT public: - CompareTask(SynchronizerFileItem *parentIn, const QString &leftURL, - const QString &rightURL, const QString &leftDir, - const QString &rightDir, bool ignoreHidden); - CompareTask(SynchronizerFileItem *parentIn, const QString &urlIn, - const QString &dirIn, bool isLeftIn, bool ignoreHidden); + CompareTask(SynchronizerFileItem *parentIn, const QUrl &left, const QUrl &right, + const QString &leftDir, const QString &rightDir, bool hidden); + + CompareTask(SynchronizerFileItem *parentIn, const QUrl &url, const QString &dir, + bool isLeftIn, bool ignoreHidden); virtual ~CompareTask(); - inline bool isDuplicate() { - return m_duplicate; - } - inline bool isLeft() { - return !m_duplicate && m_isLeft; - } - inline const QString & leftURL() { - return m_url; - } - inline const QString & rightURL() { - return m_otherUrl; - } - inline const QString & leftDir() { - return m_dir; - } - inline const QString & rightDir() { - return m_otherDir; - } - inline const QString & url() { - return m_url; - } - inline const QString & dir() { - return m_dir; - } - inline SynchronizerFileItem * parent() { - return m_parent; - } - inline SynchronizerDirList * leftDirList() { - return m_dirList; - } - inline SynchronizerDirList * rightDirList() { - return m_otherDirList; - } - inline SynchronizerDirList * dirList() { - return m_dirList; - } + inline bool isDuplicate() { return m_duplicate; } + inline bool isLeft() { return !m_duplicate && m_isLeft; } + inline const QString &leftDir() { return m_dir; } + inline const QString &rightDir() { return m_otherDir; } + inline const QString &dir() { return m_dir; } + inline SynchronizerFileItem *parent() { return m_parent; } + inline SynchronizerDirList *leftDirList() { return m_dirList; } + inline SynchronizerDirList *rightDirList() { return m_otherDirList; } + inline SynchronizerDirList *dirList() { return m_dirList; } protected slots: virtual void start(); void slotFinished(bool result); void slotOtherFinished(bool result); private: - SynchronizerFileItem * m_parent; - QString m_url; - QString m_dir; - QString m_otherUrl; - QString m_otherDir; + SynchronizerFileItem *m_parent; + const QUrl m_url; + const QString m_dir; + const QUrl m_otherUrl; + const QString m_otherDir; bool m_isLeft; bool m_duplicate; - SynchronizerDirList * m_dirList; - SynchronizerDirList * m_otherDirList; + SynchronizerDirList *m_dirList; + SynchronizerDirList *m_otherDirList; bool m_loadFinished; bool m_otherLoadFinished; bool ignoreHidden; }; - class CompareContentTask : public SynchronizerTask { Q_OBJECT public: - CompareContentTask(Synchronizer *, SynchronizerFileItem *, const QUrl &, const QUrl &, KIO::filesize_t); + CompareContentTask(Synchronizer *, SynchronizerFileItem *, const QUrl &, const QUrl &, + KIO::filesize_t); virtual ~CompareContentTask(); public slots: - void slotDataReceived(KIO::Job *job, const QByteArray &data); - void slotFinished(KJob *job); - void sendStatusMessage(); + void slotDataReceived(KIO::Job *job, const QByteArray &data); + void slotFinished(KJob *job); + void sendStatusMessage(); protected: virtual void start(); protected slots: - void localFileCompareCycle(); + void localFileCompareCycle(); private: - void abortContentComparing(); + void abortContentComparing(); - QUrl leftURL; // the currently processed URL (left) - QUrl rightURL; // the currently processed URL (right) + const QUrl left; // the currently processed URL (left) + const QUrl right; // the currently processed URL (right) KIO::filesize_t size; // the size of the compared files bool errorPrinted; // flag indicates error diff --git a/krusader/Synchronizer/synchronizertask.cpp b/krusader/Synchronizer/synchronizertask.cpp --- a/krusader/Synchronizer/synchronizertask.cpp +++ b/krusader/Synchronizer/synchronizertask.cpp @@ -21,32 +21,29 @@ #include "synchronizertask.h" // QtCore -#include #include +#include #include #include #include "synchronizer.h" -#include "synchronizerfileitem.h" #include "synchronizerdirlist.h" +#include "synchronizerfileitem.h" #include "../FileSystem/filesystem.h" -CompareTask::CompareTask(SynchronizerFileItem *parentIn, const QString &leftURL, - const QString &rightURL, const QString &leftDir, - const QString &rightDir, bool hidden) : SynchronizerTask(), m_parent(parentIn), - m_url(leftURL), m_dir(leftDir), m_otherUrl(rightURL), - m_otherDir(rightDir), m_duplicate(true), - m_dirList(0), m_otherDirList(0) +CompareTask::CompareTask(SynchronizerFileItem *parentIn, const QUrl &left, const QUrl &right, + const QString &leftDir, const QString &rightDir, bool hidden) + : SynchronizerTask(), m_parent(parentIn), m_url(left), m_dir(leftDir), m_otherUrl(right), + m_otherDir(rightDir), m_duplicate(true), m_dirList(0), m_otherDirList(0) { ignoreHidden = hidden; } -CompareTask::CompareTask(SynchronizerFileItem *parentIn, const QString &urlIn, - const QString &dirIn, bool isLeftIn, bool hidden) : SynchronizerTask(), - m_parent(parentIn), m_url(urlIn), m_dir(dirIn), - m_isLeft(isLeftIn), m_duplicate(false), - m_dirList(0), m_otherDirList(0) +CompareTask::CompareTask(SynchronizerFileItem *parentIn, const QUrl &url, const QString &dir, + bool isLeftIn, bool hidden) + : SynchronizerTask(), m_parent(parentIn), m_url(url), m_dir(dir), m_isLeft(isLeftIn), + m_duplicate(false), m_dirList(0), m_otherDirList(0) { ignoreHidden = hidden; } @@ -70,12 +67,12 @@ m_loadFinished = m_otherLoadFinished = false; m_dirList = new SynchronizerDirList(parentWidget, ignoreHidden); - connect(m_dirList, SIGNAL(finished(bool)), this, SLOT(slotFinished(bool))); + connect(m_dirList, &SynchronizerDirList::finished, this, &CompareTask::slotFinished); m_dirList->load(m_url, false); if (m_duplicate) { m_otherDirList = new SynchronizerDirList(parentWidget, ignoreHidden); - connect(m_otherDirList, SIGNAL(finished(bool)), this, SLOT(slotOtherFinished(bool))); + connect(m_otherDirList, &SynchronizerDirList::finished, this, &CompareTask::slotOtherFinished); m_otherDirList->load(m_otherUrl, false); } } @@ -93,7 +90,6 @@ m_state = ST_STATE_READY; } - void CompareTask::slotOtherFinished(bool result) { if (!result) { @@ -106,12 +102,11 @@ m_state = ST_STATE_READY; } -CompareContentTask::CompareContentTask(Synchronizer *syn, SynchronizerFileItem *itemIn, const QUrl &leftURLIn, - const QUrl &rightURLIn, KIO::filesize_t sizeIn) : SynchronizerTask(), - leftURL(leftURLIn), rightURL(rightURLIn), - size(sizeIn), errorPrinted(false), leftReadJob(0), - rightReadJob(0), compareArray(), owner(-1), item(itemIn), timer(0), - leftFile(0), rightFile(0), received(0), sync(syn) +CompareContentTask::CompareContentTask(Synchronizer *syn, SynchronizerFileItem *itemIn, + const QUrl &left, const QUrl &right, KIO::filesize_t sizeIn) + : SynchronizerTask(), left(left), right(right), size(sizeIn), + errorPrinted(false), leftReadJob(0), rightReadJob(0), compareArray(), owner(-1), item(itemIn), + timer(0), leftFile(0), rightFile(0), received(0), sync(syn) { } @@ -131,17 +126,17 @@ { m_state = ST_STATE_PENDING; - if (leftURL.isLocalFile() && rightURL.isLocalFile()) { - leftFile = new QFile(leftURL.path()); + if (left.isLocalFile() && right.isLocalFile()) { + leftFile = new QFile(left.path()); if (!leftFile->open(QIODevice::ReadOnly)) { - KMessageBox::error(parentWidget, i18n("Error at opening %1.", leftURL.path())); + KMessageBox::error(parentWidget, i18n("Error at opening %1.", left.path())); m_state = ST_STATE_ERROR; return; } - rightFile = new QFile(rightURL.path()); + rightFile = new QFile(right.path()); if (!rightFile->open(QIODevice::ReadOnly)) { - KMessageBox::error(parentWidget, i18n("Error at opening %1.", rightURL.path())); + KMessageBox::error(parentWidget, i18n("Error at opening %1.", right.path())); m_state = ST_STATE_ERROR; return; } @@ -153,17 +148,15 @@ localFileCompareCycle(); } else { - leftReadJob = KIO::get(leftURL, KIO::NoReload, KIO::HideProgressInfo); - rightReadJob = KIO::get(rightURL, KIO::NoReload, KIO::HideProgressInfo); - - connect(leftReadJob, SIGNAL(data(KIO::Job*,QByteArray)), - this, SLOT(slotDataReceived(KIO::Job*,QByteArray))); - connect(rightReadJob, SIGNAL(data(KIO::Job*,QByteArray)), - this, SLOT(slotDataReceived(KIO::Job*,QByteArray))); - connect(leftReadJob, SIGNAL(result(KJob*)), - this, SLOT(slotFinished(KJob*))); - connect(rightReadJob, SIGNAL(result(KJob*)), - this, SLOT(slotFinished(KJob*))); + leftReadJob = KIO::get(left, KIO::NoReload, KIO::HideProgressInfo); + rightReadJob = KIO::get(right, KIO::NoReload, KIO::HideProgressInfo); + + connect(leftReadJob, SIGNAL(data(KIO::Job *, QByteArray)), this, + SLOT(slotDataReceived(KIO::Job *, QByteArray))); + connect(rightReadJob, SIGNAL(data(KIO::Job *, QByteArray)), this, + SLOT(slotDataReceived(KIO::Job *, QByteArray))); + connect(leftReadJob, SIGNAL(result(KJob *)), this, SLOT(slotFinished(KJob *))); + connect(rightReadJob, SIGNAL(result(KJob *)), this, SLOT(slotFinished(KJob *))); rightReadJob->suspend(); @@ -179,8 +172,8 @@ bool different = false; - char leftBuffer[ 1440 ]; - char rightBuffer[ 1440 ]; + char leftBuffer[1440]; + char rightBuffer[1440]; QTime timer; timer.start(); @@ -225,12 +218,11 @@ QTimer::singleShot(0, this, SLOT(localFileCompareCycle())); } - void CompareContentTask::slotDataReceived(KIO::Job *job, const QByteArray &data) { int jobowner = (job == leftReadJob) ? 1 : 0; int bufferLen = compareArray.size(); - int dataLen = data.size(); + int dataLen = data.size(); if (job == leftReadJob) received += dataLen; @@ -247,7 +239,7 @@ break; } - int minSize = (dataLen < bufferLen) ? dataLen : bufferLen; + int minSize = (dataLen < bufferLen) ? dataLen : bufferLen; for (int i = 0; i != minSize; i++) if (data[i] != compareArray[i]) { @@ -302,9 +294,10 @@ if (job->error() && job->error() != KIO::ERR_USER_CANCELED && !errorPrinted) { errorPrinted = true; - KMessageBox::error(parentWidget, i18n("I/O error while comparing file %1 with %2.", - leftURL.toDisplayString(QUrl::PreferLocalFile), - rightURL.toDisplayString(QUrl::PreferLocalFile))); + KMessageBox::detailedError(parentWidget, i18n("I/O error while comparing file %1 with %2.", + left.toDisplayString(QUrl::PreferLocalFile), + right.toDisplayString(QUrl::PreferLocalFile)), + job->errorString()); } if (leftReadJob == 0 && rightReadJob == 0) { @@ -337,9 +330,9 @@ { double perc = (size == 0) ? 1. : (double)received / (double)size; int percent = (int)(perc * 10000. + 0.5); - QString statstr = QString("%1.%2%3").arg(percent / 100).arg((percent / 10) % 10).arg(percent % 10) + '%'; - setStatusMessage(i18n("Comparing file %1 (%2)...", leftURL.fileName(), statstr)); + QString statstr = + QString("%1.%2%3").arg(percent / 100).arg((percent / 10) % 10).arg(percent % 10) + '%'; + setStatusMessage(i18n("Comparing file %1 (%2)...", left.fileName(), statstr)); timer->setSingleShot(true); timer->start(500); } - diff --git a/krusader/krslots.cpp b/krusader/krslots.cpp --- a/krusader/krslots.cpp +++ b/krusader/krslots.cpp @@ -82,7 +82,6 @@ #include "Panel/panelfunc.h" #include "Panel/sidebar.h" #include "Search/krsearchdialog.h" -#include "Search/krsearchmod.h" #include "Splitter/combiner.h" #include "Splitter/splitter.h" #include "Splitter/splittergui.h"