1 // case - file manager for N900
2 // Copyright (C) 2010 Lukas Hrazky <lukkash@email.cz>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #include "fileoperator.h"
22 #include <QMessageBox>
23 #include <QHBoxLayout>
31 #define BLOCK_SIZE 524288
34 #define SHOW_ERROR_PROMPT(promptString, fileName) \
35 response = FileOperator::NONE; \
36 if (ignoreAll[errno]) { \
37 response = FileOperator::IGNORE; \
40 char *realBuf = strerror_r(errno, buf, 255); \
41 emit showErrorPrompt(this, promptString + " " + realBuf + ".", fileName, errno); \
42 waitCond.wait(&mutex); \
46 #define ERROR_PROMPT(operation, promptString, fileName) \
48 response = FileOperator::NONE; \
49 while (!abort && operation) { \
50 SHOW_ERROR_PROMPT(promptString, fileName) \
51 if (response == FileOperator::IGNORE) { \
58 #define SPECIAL_COPY_ERROR_PROMPT(operation, promptString, fileName) \
60 ERROR_PROMPT(operation, promptString, fileName) \
61 if (abort || response == FileOperator::IGNORE) { \
63 updateProgress(fileSizeMap[path]); \
64 removeExcludeFiles.insert(path); \
71 #define OVERWRITE_PROMPT(file, newFile) \
73 response = FileOperator::NONE; \
75 if (newFile.exists()) { \
76 if (overwriteAll != FileOperator::NONE) { \
77 response = overwriteAll; \
79 bool dirOverDir = false; \
80 if (newFile.isDir() && file.isDir()) dirOverDir = true; \
81 emit showOverwritePrompt(this, newFile.absoluteFilePath(), dirOverDir); \
82 waitCond.wait(&mutex); \
88 FileOperator::FileOperator(QWidget *parent) : QWidget(parent) {
89 QHBoxLayout *layout = new QHBoxLayout;
90 layout->setContentsMargins(0, 0, 0, 0);
91 layout->setSpacing(0);
96 QString FileOperator::shortenPath(const QString &path) {
97 QString homePath = QFSFileEngine::homePath();
98 QString result = path;
99 if (path.indexOf(homePath, 0) == 0) {
100 result.replace(0, homePath.size(), "~");
107 void FileOperator::deleteFiles(const QFileInfoList &files) {
109 if (files.size() == 1) {
110 title = tr("Delete file");
111 desc = tr("Are you sure you want to delete %1?")
112 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()));
114 title = tr("Delete files");
115 desc = tr("You are about to delete %1 files. Are you sure you want to continue?").arg(files.size());
118 int confirm = QMessageBox::warning(
126 if(confirm == QMessageBox::Yes) {
127 caterNewThread(new DeleteThread(files));
132 void FileOperator::copyFiles(const QFileInfoList &files, QDir &destination) {
134 if (files.size() == 1) {
135 title = tr("Copy file");
136 desc = tr("Are you sure you want to copy %1 to %2?")
137 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()))
138 .arg(FileOperator::shortenPath(destination.absolutePath()));
140 title = tr("Copy files");
141 desc = tr("You are about to copy %1 files to %2. Are you sure you want to continue?")
142 .arg(files.size()).arg(FileOperator::shortenPath(destination.absolutePath()));
145 int confirm = QMessageBox::warning(
153 if(confirm == QMessageBox::Yes) {
154 caterNewThread(new CopyThread(files, destination));
159 void FileOperator::moveFiles(const QFileInfoList &files, QDir &destination) {
160 // for move we don't wanna move to the same dir
161 if (files[0].absolutePath() == destination.absolutePath()) return;
164 if (files.size() == 1) {
165 title = tr("Move file");
166 desc = tr("Are you sure you want to move %1 to %2?")
167 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()))
168 .arg(FileOperator::shortenPath(destination.absolutePath()));
170 title = tr("Move files");
171 desc = tr("You are about to move %1 files to %2. Are you sure you want to continue?")
172 .arg(files.size()).arg(FileOperator::shortenPath(destination.absolutePath()));
175 int confirm = QMessageBox::warning(
183 if(confirm == QMessageBox::Yes) {
184 caterNewThread(new MoveThread(files, destination));
189 void FileOperator::showErrorPrompt(FileManipulatorThread* manipulator,
190 const QString &message,
191 const QString &fileName,
195 msgBox.addButton(QMessageBox::Cancel);
196 QAbstractButton *abortButton = msgBox.addButton(tr("Abort"), QMessageBox::DestructiveRole);
197 QAbstractButton *retryButton = msgBox.addButton(QMessageBox::Retry);
198 QAbstractButton *ignoreButton = msgBox.addButton(QMessageBox::Ignore);
199 QAbstractButton *ignoreAllButton = msgBox.addButton(tr("Ignore All"), QMessageBox::AcceptRole);
200 msgBox.setText(message.arg(FileOperator::shortenPath(fileName)));
204 if (msgBox.clickedButton() == abortButton) {
205 manipulator->setResponse(ABORT);
206 } else if (msgBox.clickedButton() == retryButton) {
207 manipulator->setResponse(RETRY);
208 } else if (msgBox.clickedButton() == ignoreButton) {
209 manipulator->setResponse(IGNORE);
210 } else if (msgBox.clickedButton() == ignoreAllButton) {
211 manipulator->setResponse(IGNORE, true, err);
216 void FileOperator::showOverwritePrompt(
217 FileManipulatorThread* manipulator,
218 const QString &fileName,
219 const bool dirOverDir)
222 msgBox.addButton(QMessageBox::Cancel);
223 QAbstractButton *yesButton = msgBox.addButton(QMessageBox::Yes);
224 QAbstractButton *yesToAllButton = msgBox.addButton(QMessageBox::YesToAll);
225 QAbstractButton *noButton = msgBox.addButton(QMessageBox::No);
226 QAbstractButton *noToAllButton = msgBox.addButton(QMessageBox::NoToAll);
227 QAbstractButton *abortButton = msgBox.addButton(tr("Abort"), QMessageBox::DestructiveRole);
228 QAbstractButton *askButton = 0;
231 msgBox.setText(tr("Directory %1 already exists. Overwrite the files inside?")
232 .arg(FileOperator::shortenPath(fileName)));
233 askButton = msgBox.addButton(tr("Ask"), QMessageBox::AcceptRole);
235 msgBox.setText(tr("File %1 already exists. Overwrite?").arg(FileOperator::shortenPath(fileName)));
240 if (msgBox.clickedButton() == abortButton) {
241 manipulator->setResponse(ABORT);
242 } else if (msgBox.clickedButton() == yesButton) {
243 manipulator->setResponse(OVERWRITE);
244 } else if (msgBox.clickedButton() == yesToAllButton) {
245 manipulator->setResponse(OVERWRITE, true);
246 } else if (msgBox.clickedButton() == noButton) {
247 manipulator->setResponse(KEEP);
248 } else if (msgBox.clickedButton() == noToAllButton) {
249 manipulator->setResponse(KEEP, true);
250 } else if (msgBox.clickedButton() == askButton) {
251 manipulator->setResponse(NONE, true);
256 void FileOperator::remove(FileManipulatorThread* manipulator) {
258 layout()->removeWidget(manipulator->progressBar);
259 manipulatorList.removeAll(manipulator);
264 void FileOperator::setBarSize(FileManipulatorThread* manipulator, unsigned int size) {
265 if (!manipulator->progressBar->maximum()) {
266 manipulator->startTime = time(0);
268 manipulator->progressBar->setMinimum(0);
269 manipulator->progressBar->setMaximum(size);
273 void FileOperator::updateProgress(FileManipulatorThread* manipulator, int value) {
274 manipulator->setText(value);
278 void FileOperator::caterNewThread(FileManipulatorThread *thread) {
279 manipulatorList.append(thread);
281 connect(thread, SIGNAL(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)),
282 this, SLOT(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)));
283 connect(thread, SIGNAL(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)),
284 this, SLOT(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)));
285 connect(thread, SIGNAL(finished(FileManipulatorThread*)),
286 this, SLOT(remove(FileManipulatorThread*)));
287 connect(thread, SIGNAL(setBarSize(FileManipulatorThread*, unsigned int)),
288 this, SLOT(setBarSize(FileManipulatorThread*, unsigned int)));
289 connect(thread, SIGNAL(updateProgress(FileManipulatorThread*, int)),
290 this, SLOT(updateProgress(FileManipulatorThread*, int)));
292 thread->progressBar->setValue(0);
294 layout()->addWidget(thread->progressBar);
295 thread->start(QThread::LowestPriority);
299 FileManipulatorThread::FileManipulatorThread(const QFileInfoList files, QDir dest) :
300 progressBar(new QProgressBar()),
304 response(FileOperator::NONE),
305 overwriteAll(FileOperator::NONE),
313 memset(ignoreAll, false, sizeof(ignoreAll));
314 progressBar->setMaximum(0);
315 QFont barFont = progressBar->font();
316 barFont.setPointSize(12);
317 progressBar->setFont(barFont);
318 progressBar->setFormat(tr("Gathering information..."));
319 progressBar->setMinimumHeight(44);
320 progressBar->setStyle(new QPlastiqueStyle);
321 //progressBar->setStyle(new QMotifStyle);
325 FileManipulatorThread::~FileManipulatorThread() {
326 if (progressBar->value() < progressBar->maximum()) {
327 std::cout << "WARNING: deleting a progressbar which's value " << progressBar->value() <<
328 " has not reached maximum of " << progressBar->maximum() << std::endl;
334 void FileManipulatorThread::setResponse(
335 const FileOperator::Response response,
336 const bool applyToAll,
341 this->response = response;
344 if (response == FileOperator::KEEP
345 || response == FileOperator::OVERWRITE
346 || response == FileOperator::NONE)
348 overwriteAll = response;
351 if (response == FileOperator::IGNORE) {
352 ignoreAll[err] = true;
356 if (response == FileOperator::ABORT) abort = true;
363 void FileManipulatorThread::processFiles(const QFileInfoList &files) {
364 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
371 bool FileManipulatorThread::remove(QString &fileName, const bool doUpdates) {
372 return remove(QFileInfo(fileName), doUpdates);
376 bool FileManipulatorThread::remove(const QFileInfoList &files, const bool doUpdates) {
378 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
379 if (!remove(*it, doUpdates)) res = false;
386 bool FileManipulatorThread::remove(const QFileInfo &file, const bool doUpdates) {
387 std::cout << "DELETING " << file.absoluteFilePath().toStdString() << std::endl;
389 QString path = file.absoluteFilePath();
391 if (removeExcludeFiles.contains(path)) {
392 if (doUpdates) updateProgress(1);
396 QFSFileEngine engine(path);
398 if (doUpdates) updateFile(path);
401 if (!remove(listDirFiles(path), doUpdates)) {
402 if (doUpdates) updateProgress(1);
406 if (!listDirFiles(path).size()) {
407 ERROR_PROMPT(!engine.rmdir(path, false), tr("Error deleting directory %1."), path)
410 ERROR_PROMPT(!engine.remove(), tr("Error deleting file %1."), path)
413 if (!abort && doUpdates) updateProgress(1);
415 if (abort || response == FileOperator::IGNORE) return false;
420 void FileManipulatorThread::copy(const QFileInfo &file) {
421 std::cout << "COPYING " << file.absoluteFilePath().toStdString()
422 << " to " << dest.absolutePath().toStdString() << std::endl;
424 QString path(file.absoluteFilePath());
425 QString newPath(dest.absolutePath() + "/" + file.fileName());
426 QFSFileEngine engine(path);
427 QFSFileEngine newEngine(newPath);
428 QFileInfo newFile(newPath);
432 // hack to prevent asking about the same file if we already asked in the rename(...) function
433 if (overwriteAll == FileOperator::DONT_ASK_ONCE) {
434 overwriteAll = FileOperator::NONE;
436 OVERWRITE_PROMPT(file, newFile)
441 if (response == FileOperator::KEEP) {
442 updateProgress(fileSizeMap[path]);
443 removeExcludeFiles.insert(path);
448 FileOperator::Response overwriteResponse = response;
450 if (newFile.exists() && !newFile.isDir()) {
451 if(!remove(newPath)) {
452 updateProgress(fileSizeMap[path]);
455 newFile = QFileInfo(newPath);
458 if (!newFile.exists()) {
459 SPECIAL_COPY_ERROR_PROMPT(!engine.mkdir(newPath, false),
460 tr("Error creating directory %1."), newPath)
465 QDir destBackup = dest;
468 FileOperator::Response tmpResp = overwriteAll;
469 overwriteAll = overwriteResponse;
471 processFiles(listDirFiles(path));
473 overwriteAll = tmpResp;
475 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
476 tr("Error setting permissions for directory %1."), newPath)
482 SPECIAL_COPY_ERROR_PROMPT(engine.isSequential(), tr("Cannot copy sequential file %1."), path)
484 if (newFile.exists() && newFile.isDir()) {
485 SPECIAL_COPY_ERROR_PROMPT(!remove(newPath),
486 tr("Cannot replace directory %1 due to previous errors."), newPath)
489 SPECIAL_COPY_ERROR_PROMPT(!engine.open(QIODevice::ReadOnly), tr("Error reading file %1."), path)
492 while (!abort && !ignore) {
496 ERROR_PROMPT(!newEngine.open(QIODevice::WriteOnly | QIODevice::Truncate),
497 tr("Error writing file %1."), newPath)
499 if (abort || response == FileOperator::IGNORE) {
500 if (response == FileOperator::IGNORE) {
501 updateProgress(fileSizeMap[path]);
502 removeExcludeFiles.insert(path);
509 char block[BLOCK_SIZE];
511 while ((bytes = engine.read(block, sizeof(block))) > 0) {
512 if (bytes == -1 || bytes != newEngine.write(block, bytes)) {
514 SHOW_ERROR_PROMPT(tr("Error while reading from file %1."), path);
516 SHOW_ERROR_PROMPT(tr("Error while writing to file %1."), newPath);
520 if (response == FileOperator::IGNORE) {
521 updateProgress(fileSizeMap[path] - fileValue);
522 removeExcludeFiles.insert(path);
525 updateProgress(-fileValue);
541 if (abort || ignore) {
544 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
545 tr("Error setting permissions for file %1."), newPath)
551 unsigned int FileManipulatorThread::calculateFileSize(const QFileInfoList &files,
555 unsigned int res = 0;
557 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
558 unsigned int size = 0;
561 size += calculateFileSize(listDirFiles(it->absoluteFilePath()), count, addSize);
568 size += ceil(static_cast<float>(it->size()) / BLOCK_SIZE);
570 fileSizeMap[it->absoluteFilePath()] = size;
584 QFileInfoList FileManipulatorThread::listDirFiles(const QString &dirPath) {
586 return dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries | QDir::System | QDir::Hidden);
590 void FileManipulatorThread::setBarSize(unsigned int size) {
592 emit setBarSize(this, size);
596 void FileManipulatorThread::updateProgress(int value) {
599 emit updateProgress(this, value);
603 void FileManipulatorThread::updateFile(const QString &name) {
605 fileName = FileOperator::shortenPath(name);
606 emit updateProgress(this, 0);
610 void FileManipulatorThread::setText(int value) {
611 if (progressBar->value() + value > progressBar->maximum()) {
612 std::cout << "WARNING: exceeding progressbar maximum (" << progressBar->maximum()
613 << ") by " << value << std::endl;
616 time_t now = time(0);
617 if (lastTimeUpdate < now) {
618 lastTimeUpdate = now;
620 time_t elapsed = now - startTime;
621 time_t remaining = (time_t) ((float) elapsed / barValue * (barSize - barValue));
622 struct tm *ts = gmtime(&remaining);
624 if (remaining < 60) {
625 strftime(timeBuf, sizeof(timeBuf), "%Ss", ts);
626 } else if (remaining < 3600) {
627 strftime(timeBuf, sizeof(timeBuf), "%M:%S", ts);
629 strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", ts);
633 progressBar->setFormat(barText.arg(fileName) + "\n%p% ETA " + timeBuf);
634 progressBar->setValue(progressBar->value() + value);
638 DeleteThread::DeleteThread(const QFileInfoList &files) : FileManipulatorThread(files) {
639 barText = tr("deleting %1");
643 void DeleteThread::run() {
646 setBarSize(calculateFileSize(files, true));
655 void DeleteThread::perform(const QFileInfo &file) {
660 CopyThread::CopyThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
661 barText = tr("copying %1");
665 void CopyThread::run() {
668 setBarSize(calculateFileSize(files, false, true));
677 void CopyThread::perform(const QFileInfo &file) {
682 MoveThread::MoveThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
683 barText = tr("moving %1");
687 void MoveThread::run() {
697 void MoveThread::rename(const QFileInfoList &files, const QDir &dest) {
698 setBarSize(barSize + files.size());
700 for (int i = 0; i < files.size(); ++i) {
701 QString path = files[i].absoluteFilePath();
702 QFSFileEngine engine(path);
703 QString newPath = dest.absolutePath() + "/" + files[i].fileName();
707 OVERWRITE_PROMPT(files[i], QFileInfo(newPath))
709 if (response == FileOperator::KEEP) {
715 while (!abort && !engine.rename(newPath)) {
716 // source and target are on different partitions
717 // this should happen on the first file, unless some are skipped by overwrite prompt
718 // we calculate the actual file sizes, because from now on copy & remove takes over
719 if (errno == EXDEV) {
720 overwriteAll = response;
721 // hack: we already checked the first file we are sending to processFiles(...)
722 // so we don't want to ask about this one again
723 if (overwriteAll == FileOperator::NONE) overwriteAll = FileOperator::DONT_ASK_ONCE;
725 QFileInfoList remainingFiles = files.mid(i);
727 setBarSize(barValue + calculateFileSize(remainingFiles, true, true));
729 processFiles(remainingFiles);
731 barText = tr("deleting %1");
733 remove(remainingFiles, true);
735 // just to quit the loops, we are done
737 // the target is nonempty dir. lets call this recursively and rename the contents one by one
738 } else if (errno == ENOTEMPTY || errno == EEXIST) {
739 FileOperator::Response tmpResp = overwriteAll;
740 overwriteAll = response;
742 rename(listDirFiles(path), QDir(newPath));
745 overwriteAll = tmpResp;
747 ERROR_PROMPT(!engine.rmdir(path, false), tr("Error deleting directory %1."), path)
750 // source and target are nonmatching types(file and dir)
751 // remove the target and let it loop once again
752 } else if (errno == ENOTDIR || errno == EISDIR) {
753 if (!remove(newPath)) break;
755 SHOW_ERROR_PROMPT(tr("Error moving %1."), path)
757 if (response == FileOperator::IGNORE) {
769 void MoveThread::perform(const QFileInfo &file) {