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;
229 QAbstractButton *skipDirButton = 0;
232 msgBox.setText(tr("Directory %1 already exists. Overwrite the files inside?")
233 .arg(FileOperator::shortenPath(fileName)));
234 askButton = msgBox.addButton(tr("Ask"), QMessageBox::AcceptRole);
235 skipDirButton = msgBox.addButton(tr("Skip"), QMessageBox::NoRole);
237 msgBox.setText(tr("File %1 already exists. Overwrite?").arg(FileOperator::shortenPath(fileName)));
242 if (msgBox.clickedButton() == abortButton) {
243 manipulator->setResponse(ABORT);
244 } else if (msgBox.clickedButton() == yesButton) {
245 manipulator->setResponse(OVERWRITE);
246 } else if (msgBox.clickedButton() == yesToAllButton) {
247 manipulator->setResponse(OVERWRITE, true);
248 } else if (msgBox.clickedButton() == noButton) {
249 manipulator->setResponse(KEEP);
250 } else if (msgBox.clickedButton() == noToAllButton) {
251 manipulator->setResponse(KEEP, true);
252 } else if (msgBox.clickedButton() == askButton) {
253 manipulator->setResponse(NONE, true);
254 } else if (msgBox.clickedButton() == skipDirButton) {
255 manipulator->setResponse(SKIP_DIR);
260 void FileOperator::remove(FileManipulatorThread* manipulator) {
262 layout()->removeWidget(manipulator->progressBar);
263 manipulatorList.removeAll(manipulator);
268 void FileOperator::setBarSize(FileManipulatorThread* manipulator, unsigned int size) {
269 if (!manipulator->progressBar->maximum()) {
270 manipulator->startTime = time(0);
272 manipulator->progressBar->setMinimum(0);
273 manipulator->progressBar->setMaximum(size);
277 void FileOperator::updateProgress(FileManipulatorThread* manipulator, int value) {
278 manipulator->setText(value);
282 void FileOperator::caterNewThread(FileManipulatorThread *thread) {
283 manipulatorList.append(thread);
285 connect(thread, SIGNAL(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)),
286 this, SLOT(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)));
287 connect(thread, SIGNAL(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)),
288 this, SLOT(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)));
289 connect(thread, SIGNAL(finished(FileManipulatorThread*)),
290 this, SLOT(remove(FileManipulatorThread*)));
291 connect(thread, SIGNAL(setBarSize(FileManipulatorThread*, unsigned int)),
292 this, SLOT(setBarSize(FileManipulatorThread*, unsigned int)));
293 connect(thread, SIGNAL(updateProgress(FileManipulatorThread*, int)),
294 this, SLOT(updateProgress(FileManipulatorThread*, int)));
296 thread->progressBar->setValue(0);
298 layout()->addWidget(thread->progressBar);
299 thread->start(QThread::LowestPriority);
303 FileManipulatorThread::FileManipulatorThread(const QFileInfoList files, QDir dest) :
304 progressBar(new QProgressBar()),
308 response(FileOperator::NONE),
309 overwriteAll(FileOperator::NONE),
317 memset(ignoreAll, false, sizeof(ignoreAll));
318 progressBar->setMaximum(0);
319 QFont barFont = progressBar->font();
320 barFont.setPointSize(12);
321 progressBar->setFont(barFont);
322 progressBar->setFormat(tr("Gathering information..."));
323 progressBar->setMinimumHeight(44);
324 progressBar->setStyle(new QPlastiqueStyle);
325 //progressBar->setStyle(new QMotifStyle);
329 FileManipulatorThread::~FileManipulatorThread() {
330 if (progressBar->value() < progressBar->maximum()) {
331 std::cout << "WARNING: deleting a progressbar which's value " << progressBar->value() <<
332 " has not reached maximum of " << progressBar->maximum() << std::endl;
338 void FileManipulatorThread::setResponse(
339 const FileOperator::Response response,
340 const bool applyToAll,
345 this->response = response;
348 if (response == FileOperator::KEEP
349 || response == FileOperator::OVERWRITE
350 || response == FileOperator::NONE)
352 overwriteAll = response;
355 if (response == FileOperator::IGNORE) {
356 ignoreAll[err] = true;
360 if (response == FileOperator::ABORT) abort = true;
367 void FileManipulatorThread::processFiles(const QFileInfoList &files) {
368 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
375 bool FileManipulatorThread::remove(QString &fileName, const bool doUpdates) {
376 return remove(QFileInfo(fileName), doUpdates);
380 bool FileManipulatorThread::remove(const QFileInfoList &files, const bool doUpdates) {
382 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
383 if (!remove(*it, doUpdates)) res = false;
390 bool FileManipulatorThread::remove(const QFileInfo &file, const bool doUpdates) {
391 std::cout << "DELETING " << file.absoluteFilePath().toStdString() << std::endl;
393 QString path = file.absoluteFilePath();
395 if (removeExcludeFiles.contains(path)) {
396 if (doUpdates) updateProgress(1);
400 QFSFileEngine engine(path);
402 if (doUpdates) updateFile(path);
405 if (!remove(listDirFiles(path), doUpdates)) {
406 if (doUpdates) updateProgress(1);
410 if (!listDirFiles(path).size()) {
411 ERROR_PROMPT(!engine.rmdir(path, false), tr("Error deleting directory %1."), path)
414 ERROR_PROMPT(!engine.remove(), tr("Error deleting file %1."), path)
417 if (!abort && doUpdates) updateProgress(1);
419 if (abort || response == FileOperator::IGNORE) return false;
424 void FileManipulatorThread::copy(const QFileInfo &file) {
425 std::cout << "COPYING " << file.absoluteFilePath().toStdString()
426 << " to " << dest.absolutePath().toStdString() << std::endl;
428 QString path(file.absoluteFilePath());
429 QString newPath(dest.absolutePath() + "/" + file.fileName());
430 QFSFileEngine engine(path);
431 QFSFileEngine newEngine(newPath);
432 QFileInfo newFile(newPath);
436 // hack to prevent asking about the same file if we already asked in the rename(...) function
437 if (overwriteAll == FileOperator::DONT_ASK_ONCE) {
438 overwriteAll = FileOperator::NONE;
440 OVERWRITE_PROMPT(file, newFile)
446 // save the overwrite response, because the response variable will get ovewritten in remove(...)
447 FileOperator::Response overwriteResponse = response;
449 if (newFile.exists() && !newFile.isDir()) {
450 // overwriting a file, so check for KEEP and handle it
451 if (response == FileOperator::KEEP) {
452 updateProgress(fileSizeMap[path]);
453 removeExcludeFiles.insert(path);
457 // if it should not be kept, remove it and return on failure
458 if(!remove(newPath)) {
459 updateProgress(fileSizeMap[path]);
462 // create new info since we deleted the file - is it needed?
463 newFile = QFileInfo(newPath);
465 // overwriting a directory - response KEEP means to keep the files inside,
466 // SKIP_DIR means to skip the dir completely
467 if (response == FileOperator::SKIP_DIR) {
468 updateProgress(fileSizeMap[path]);
469 removeExcludeFiles.insert(path);
474 if (!newFile.exists()) {
475 SPECIAL_COPY_ERROR_PROMPT(!engine.mkdir(newPath, false),
476 tr("Error creating directory %1."), newPath)
479 // we've done the job with the dir, so update progress and recurse into the dir
482 // change the dest for the recursion
483 QDir destBackup = dest;
486 // and set overwriteAll to the response we got a while ago
487 // because it applies to the files inside the dir
488 FileOperator::Response tmpResp = overwriteAll;
489 overwriteAll = overwriteResponse;
491 processFiles(listDirFiles(path));
493 overwriteAll = tmpResp;
495 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
496 tr("Error setting permissions for directory %1."), newPath)
502 if (response == FileOperator::KEEP) {
503 updateProgress(fileSizeMap[path]);
504 removeExcludeFiles.insert(path);
508 SPECIAL_COPY_ERROR_PROMPT(engine.isSequential(), tr("Cannot copy sequential file %1."), path)
510 if (newFile.exists() && newFile.isDir()) {
511 SPECIAL_COPY_ERROR_PROMPT(!remove(newPath),
512 tr("Cannot replace directory %1 due to previous errors."), newPath)
515 SPECIAL_COPY_ERROR_PROMPT(!engine.open(QIODevice::ReadOnly), tr("Error reading file %1."), path)
518 while (!abort && !ignore) {
522 ERROR_PROMPT(!newEngine.open(QIODevice::WriteOnly | QIODevice::Truncate),
523 tr("Error writing file %1."), newPath)
525 if (abort || response == FileOperator::IGNORE) {
526 if (response == FileOperator::IGNORE) {
527 updateProgress(fileSizeMap[path]);
528 removeExcludeFiles.insert(path);
535 char block[BLOCK_SIZE];
537 while ((bytes = engine.read(block, sizeof(block))) > 0) {
538 if (bytes == -1 || bytes != newEngine.write(block, bytes)) {
540 SHOW_ERROR_PROMPT(tr("Error while reading from file %1."), path);
542 SHOW_ERROR_PROMPT(tr("Error while writing to file %1."), newPath);
546 if (response == FileOperator::IGNORE) {
547 updateProgress(fileSizeMap[path] - fileValue);
548 removeExcludeFiles.insert(path);
551 updateProgress(-fileValue);
567 if (abort || ignore) {
570 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
571 tr("Error setting permissions for file %1."), newPath)
577 unsigned int FileManipulatorThread::calculateFileSize(const QFileInfoList &files,
581 unsigned int res = 0;
583 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
584 unsigned int size = 0;
587 size += calculateFileSize(listDirFiles(it->absoluteFilePath()), count, addSize);
594 size += ceil(static_cast<float>(it->size()) / BLOCK_SIZE);
596 fileSizeMap[it->absoluteFilePath()] = size;
610 QFileInfoList FileManipulatorThread::listDirFiles(const QString &dirPath) {
612 return dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries | QDir::System | QDir::Hidden);
616 void FileManipulatorThread::setBarSize(unsigned int size) {
618 emit setBarSize(this, size);
622 void FileManipulatorThread::updateProgress(int value) {
625 emit updateProgress(this, value);
629 void FileManipulatorThread::updateFile(const QString &name) {
631 fileName = FileOperator::shortenPath(name);
632 emit updateProgress(this, 0);
636 void FileManipulatorThread::setText(int value) {
637 if (progressBar->value() + value > progressBar->maximum()) {
638 std::cout << "WARNING: exceeding progressbar maximum (" << progressBar->maximum()
639 << ") by " << value << std::endl;
642 time_t now = time(0);
643 if (lastTimeUpdate < now) {
644 lastTimeUpdate = now;
646 time_t elapsed = now - startTime;
647 time_t remaining = (time_t) ((float) elapsed / barValue * (barSize - barValue));
648 struct tm *ts = gmtime(&remaining);
650 if (remaining < 60) {
651 strftime(timeBuf, sizeof(timeBuf), "%Ss", ts);
652 } else if (remaining < 3600) {
653 strftime(timeBuf, sizeof(timeBuf), "%M:%S", ts);
655 strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", ts);
659 progressBar->setFormat(barText.arg(fileName) + "\n%p% ETA " + timeBuf);
660 progressBar->setValue(progressBar->value() + value);
664 DeleteThread::DeleteThread(const QFileInfoList &files) : FileManipulatorThread(files) {
665 barText = tr("deleting %1");
669 void DeleteThread::run() {
672 setBarSize(calculateFileSize(files, true));
681 void DeleteThread::perform(const QFileInfo &file) {
686 CopyThread::CopyThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
687 barText = tr("copying %1");
691 void CopyThread::run() {
694 setBarSize(calculateFileSize(files, false, true));
703 void CopyThread::perform(const QFileInfo &file) {
708 MoveThread::MoveThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
709 barText = tr("moving %1");
713 void MoveThread::run() {
723 void MoveThread::rename(const QFileInfoList &files, const QDir &dest) {
724 setBarSize(barSize + files.size());
726 for (int i = 0; i < files.size(); ++i) {
727 QString path = files[i].absoluteFilePath();
728 QFSFileEngine engine(path);
729 QString newPath = dest.absolutePath() + "/" + files[i].fileName();
730 QFileInfo newFile(newPath);
734 OVERWRITE_PROMPT(files[i], newFile)
736 if (files[i].isDir() && newFile.exists() && newFile.isDir()) {
737 if (response == FileOperator::SKIP_DIR) {
740 removeExcludeFiles.insert(path);
744 if (response == FileOperator::KEEP) {
747 removeExcludeFiles.insert(path);
752 while (!abort && !engine.rename(newPath)) {
753 // source and target are on different partitions
754 // this should happen on the first file, unless some are skipped by overwrite prompt
755 // we calculate the actual file sizes, because from now on copy & remove takes over
756 if (errno == EXDEV) {
757 overwriteAll = response;
758 // hack: we already checked the first file we are sending to processFiles(...)
759 // so we don't want to ask about this one again
760 if (overwriteAll == FileOperator::NONE) overwriteAll = FileOperator::DONT_ASK_ONCE;
762 QFileInfoList remainingFiles = files.mid(i);
764 setBarSize(barValue + calculateFileSize(remainingFiles, true, true));
766 processFiles(remainingFiles);
768 barText = tr("deleting %1");
770 remove(remainingFiles, true);
772 // just to quit the loops, we are done
774 // the target is nonempty dir. lets call this recursively and rename the contents one by one
775 } else if (errno == ENOTEMPTY || errno == EEXIST) {
776 FileOperator::Response tmpResp = overwriteAll;
777 overwriteAll = response;
779 rename(listDirFiles(path), QDir(newPath));
782 overwriteAll = tmpResp;
787 // source and target are nonmatching types(file and dir)
788 // remove the target and let it loop once again
789 } else if (errno == ENOTDIR || errno == EISDIR) {
790 if (!remove(newPath)) break;
792 SHOW_ERROR_PROMPT(tr("Error moving %1."), path)
794 if (response == FileOperator::IGNORE) {
806 void MoveThread::perform(const QFileInfo &file) {