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>
33 #define BLOCK_SIZE 524288
36 #define SHOW_ERROR_PROMPT(promptString, fileName) \
37 response = FileOperator::NONE; \
38 if (ignoreAll[errno]) { \
39 response = FileOperator::IGNORE; \
42 char *realBuf = strerror_r(errno, buf, 255); \
43 emit showErrorPrompt(this, promptString + " " + realBuf + ".", fileName, errno); \
44 waitCond.wait(&mutex); \
48 #define ERROR_PROMPT(operation, promptString, fileName) \
50 response = FileOperator::NONE; \
51 while (!abort && operation) { \
52 SHOW_ERROR_PROMPT(promptString, fileName) \
53 if (response == FileOperator::IGNORE) { \
60 #define SPECIAL_COPY_ERROR_PROMPT(operation, promptString, fileName) \
62 ERROR_PROMPT(operation, promptString, fileName) \
63 if (abort || response == FileOperator::IGNORE) { \
65 updateProgress(fileSizeMap[path]); \
66 removeExcludeFiles.insert(path); \
73 #define OVERWRITE_PROMPT(file, newFile) \
75 response = FileOperator::NONE; \
77 while (response == FileOperator::NONE && newFile.exists()) { \
78 if (overwriteAll != FileOperator::NONE) { \
79 response = overwriteAll; \
81 emit showOverwritePrompt(this, newFile.absoluteFilePath(), \
82 newFile.isDir() && file.isDir()); \
83 waitCond.wait(&mutex); \
85 if (response == FileOperator::NONE) { \
86 emit showInputFilenamePrompt(this, newFile, file.isDir()); \
87 waitCond.wait(&mutex); \
88 if (newNameFromDialog.size()) { \
89 newFile.setFile(newNameFromDialog); \
94 if (response == FileOperator::ASK) response = FileOperator::NONE; \
98 FileOperator::FileOperator(QWidget *parent) : QWidget(parent) {
99 QHBoxLayout *layout = new QHBoxLayout;
100 layout->setContentsMargins(0, 0, 0, 0);
101 layout->setSpacing(0);
103 qRegisterMetaType<QFileInfo>("QFileInfo");
107 QString FileOperator::shortenPath(const QString &path) {
108 QString homePath = QFSFileEngine::homePath();
109 QString result = path;
110 if (path.indexOf(homePath, 0) == 0) {
111 result.replace(0, homePath.size(), "~");
118 void FileOperator::deleteFiles(const QFileInfoList &files) {
120 if (files.size() == 1) {
121 title = tr("Delete file");
122 desc = tr("Are you sure you want to delete %1?")
123 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()));
125 title = tr("Delete files");
126 desc = tr("You are about to delete %1 files. Are you sure you want to continue?").arg(files.size());
129 int confirm = QMessageBox::warning(
137 if(confirm == QMessageBox::Yes) {
138 caterNewThread(new DeleteThread(files));
143 void FileOperator::copyFiles(const QFileInfoList &files, QDir &destination) {
145 if (files.size() == 1) {
146 title = tr("Copy file");
147 desc = tr("Are you sure you want to copy %1 to %2?")
148 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()))
149 .arg(FileOperator::shortenPath(destination.absolutePath()));
151 title = tr("Copy files");
152 desc = tr("You are about to copy %1 files to %2. Are you sure you want to continue?")
153 .arg(files.size()).arg(FileOperator::shortenPath(destination.absolutePath()));
156 int confirm = QMessageBox::warning(
164 if(confirm == QMessageBox::Yes) {
165 caterNewThread(new CopyThread(files, destination));
170 void FileOperator::moveFiles(const QFileInfoList &files, QDir &destination) {
171 // for move we don't wanna move to the same dir
172 if (files[0].absolutePath() == destination.absolutePath()) return;
175 if (files.size() == 1) {
176 title = tr("Move file");
177 desc = tr("Are you sure you want to move %1 to %2?")
178 .arg(FileOperator::shortenPath(files[0].absoluteFilePath()))
179 .arg(FileOperator::shortenPath(destination.absolutePath()));
181 title = tr("Move files");
182 desc = tr("You are about to move %1 files to %2. Are you sure you want to continue?")
183 .arg(files.size()).arg(FileOperator::shortenPath(destination.absolutePath()));
186 int confirm = QMessageBox::warning(
194 if(confirm == QMessageBox::Yes) {
195 caterNewThread(new MoveThread(files, destination));
200 void FileOperator::showErrorPrompt(FileManipulatorThread* manipulator,
201 const QString &message,
202 const QString &fileName,
206 msgBox.addButton(QMessageBox::Cancel);
207 QAbstractButton *abortButton = msgBox.addButton(tr("Abort"), QMessageBox::DestructiveRole);
208 QAbstractButton *retryButton = msgBox.addButton(QMessageBox::Retry);
209 QAbstractButton *ignoreButton = msgBox.addButton(QMessageBox::Ignore);
210 QAbstractButton *ignoreAllButton = msgBox.addButton(tr("Ignore All"), QMessageBox::AcceptRole);
211 msgBox.setText(message.arg(FileOperator::shortenPath(fileName)));
215 if (msgBox.clickedButton() == abortButton) {
216 manipulator->setResponse(ABORT);
217 } else if (msgBox.clickedButton() == retryButton) {
218 manipulator->setResponse(RETRY);
219 } else if (msgBox.clickedButton() == ignoreButton) {
220 manipulator->setResponse(IGNORE);
221 } else if (msgBox.clickedButton() == ignoreAllButton) {
222 manipulator->setResponse(IGNORE, true, err);
227 void FileOperator::showOverwritePrompt(
228 FileManipulatorThread* manipulator,
229 const QString &fileName,
230 const bool dirOverDir)
233 msgBox.addButtonFirst(QDialogButtonBox::Cancel);
234 QAbstractButton *yesButton = msgBox.addButtonFirst(QDialogButtonBox::Yes);
235 QAbstractButton *yesToAllButton = msgBox.addButtonFirst(QDialogButtonBox::YesToAll);
236 QAbstractButton *noButton = msgBox.addButtonSecond(QDialogButtonBox::No);
237 QAbstractButton *noToAllButton = msgBox.addButtonSecond(QDialogButtonBox::NoToAll);
238 QAbstractButton *abortButton = msgBox.addButtonSecond(tr("Abort"), QDialogButtonBox::DestructiveRole);
239 QAbstractButton *newNameButton = msgBox.addButtonFirst(tr("New Name"), QDialogButtonBox::AcceptRole);
240 QAbstractButton *askButton = 0;
241 QAbstractButton *skipDirButton = 0;
244 msgBox.setText(tr("Directory %1 already exists. Overwrite the files inside?")
245 .arg(FileOperator::shortenPath(fileName)));
246 askButton = msgBox.addButtonFirst(tr("Ask"), QDialogButtonBox::AcceptRole);
247 skipDirButton = msgBox.addButtonSecond(tr("Skip"), QDialogButtonBox::NoRole);
249 msgBox.setText(tr("File %1 already exists. Overwrite?").arg(FileOperator::shortenPath(fileName)));
254 if (msgBox.clickedButton == abortButton) {
255 manipulator->setResponse(ABORT);
256 } else if (msgBox.clickedButton == yesButton) {
257 manipulator->setResponse(OVERWRITE);
258 } else if (msgBox.clickedButton == yesToAllButton) {
259 manipulator->setResponse(OVERWRITE, true);
260 } else if (msgBox.clickedButton == noButton) {
261 manipulator->setResponse(KEEP);
262 } else if (msgBox.clickedButton == noToAllButton) {
263 manipulator->setResponse(KEEP, true);
264 } else if (msgBox.clickedButton == askButton) {
265 manipulator->setResponse(ASK);
266 } else if (msgBox.clickedButton == newNameButton) {
267 manipulator->setResponse(NONE);
268 } else if (msgBox.clickedButton == skipDirButton) {
269 manipulator->setResponse(SKIP_DIR);
274 void FileOperator::showInputFilenamePrompt(FileManipulatorThread* manipulator,
275 const QFileInfo &file,
279 QString prompt, error;
282 prompt = tr("Enter the new directory name.");
284 prompt = tr("Enter the new file name.");
287 manipulator->mutex.lock();
289 manipulator->newNameFromDialog = "";
290 QString text = file.fileName();
294 text = QInputDialog::getText(this, QString(), prompt + error, QLineEdit::Normal, text, &ok);
299 if (text.contains(QRegExp("[\"*/:<>?\\\\|]"))) {
300 error = "<small><br/><font color = 'red'>" + tr("The name cannot contain any of the following characters: ") +
301 "\"*/:<>?\\|</font></small>";
302 } else if (ok && !text.isEmpty()) {
303 QFileInfo info(file.path() + "/" + text);
304 manipulator->newNameFromDialog = info.absoluteFilePath();
309 manipulator->mutex.unlock();
310 manipulator->waitCond.wakeAll();
314 void FileOperator::remove(FileManipulatorThread* manipulator) {
316 layout()->removeWidget(manipulator->progressBar);
317 manipulatorList.removeAll(manipulator);
322 void FileOperator::setBarSize(FileManipulatorThread* manipulator, unsigned int size) {
323 if (!manipulator->progressBar->maximum()) {
324 manipulator->startTime = time(0);
326 manipulator->progressBar->setMinimum(0);
327 manipulator->progressBar->setMaximum(size);
331 void FileOperator::updateProgress(FileManipulatorThread* manipulator, int value) {
332 manipulator->setText(value);
336 void FileOperator::caterNewThread(FileManipulatorThread *thread) {
337 manipulatorList.append(thread);
339 connect(thread, SIGNAL(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)),
340 this, SLOT(showErrorPrompt(FileManipulatorThread*, const QString&, const QString&, const int)));
341 connect(thread, SIGNAL(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)),
342 this, SLOT(showOverwritePrompt(FileManipulatorThread*, const QString&, bool)));
343 connect(thread, SIGNAL(showInputFilenamePrompt(FileManipulatorThread*, const QFileInfo&, bool)),
344 this, SLOT(showInputFilenamePrompt(FileManipulatorThread*, const QFileInfo&, bool)));
345 connect(thread, SIGNAL(finished(FileManipulatorThread*)),
346 this, SLOT(remove(FileManipulatorThread*)));
347 connect(thread, SIGNAL(setBarSize(FileManipulatorThread*, unsigned int)),
348 this, SLOT(setBarSize(FileManipulatorThread*, unsigned int)));
349 connect(thread, SIGNAL(updateProgress(FileManipulatorThread*, int)),
350 this, SLOT(updateProgress(FileManipulatorThread*, int)));
352 layout()->addWidget(thread->progressBar);
353 thread->start(QThread::LowestPriority);
357 FileManipulatorThread::FileManipulatorThread(const QFileInfoList files, QDir dest) :
358 progressBar(new QProgressBar()),
362 response(FileOperator::NONE),
363 overwriteAll(FileOperator::NONE),
371 memset(ignoreAll, false, sizeof(ignoreAll));
372 progressBar->setMaximum(1);
373 progressBar->setValue(0);
374 progressBar->setMinimum(0);
375 QFont barFont = progressBar->font();
376 barFont.setPointSize(12);
377 progressBar->setFont(barFont);
378 progressBar->setFormat(tr("Gathering information..."));
379 progressBar->setMinimumHeight(44);
380 progressBar->setStyle(new QPlastiqueStyle);
381 //progressBar->setStyle(new QMotifStyle);
385 FileManipulatorThread::~FileManipulatorThread() {
386 if (!abort && progressBar->value() < progressBar->maximum()) {
387 std::cout << "WARNING: deleting a progressbar which's value " << progressBar->value() <<
388 " has not reached maximum of " << progressBar->maximum() << std::endl;
394 void FileManipulatorThread::setResponse(
395 const FileOperator::Response response,
396 const bool applyToAll,
401 this->response = response;
404 if (response == FileOperator::KEEP
405 || response == FileOperator::OVERWRITE
406 || response == FileOperator::NONE)
408 overwriteAll = response;
411 if (response == FileOperator::IGNORE) {
412 ignoreAll[err] = true;
416 if (response == FileOperator::ABORT) abort = true;
423 void FileManipulatorThread::processFiles(const QFileInfoList &files) {
424 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
431 bool FileManipulatorThread::remove(QString &fileName, const bool doUpdates) {
432 return remove(QFileInfo(fileName), doUpdates);
436 bool FileManipulatorThread::remove(const QFileInfoList &files, const bool doUpdates) {
438 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
439 if (!remove(*it, doUpdates)) res = false;
446 bool FileManipulatorThread::remove(const QFileInfo &file, const bool doUpdates) {
447 std::cout << "DELETING " << file.absoluteFilePath().toStdString() << std::endl;
449 QString path = file.absoluteFilePath();
451 if (removeExcludeFiles.contains(path)) {
452 if (doUpdates) updateProgress(1);
456 QFSFileEngine engine(path);
458 if (doUpdates) updateFile(path);
461 if (!remove(listDirFiles(path), doUpdates)) {
462 if (doUpdates) updateProgress(1);
466 if (!listDirFiles(path).size()) {
467 ERROR_PROMPT(!engine.rmdir(path, false), tr("Error deleting directory %1."), path)
470 ERROR_PROMPT(!engine.remove(), tr("Error deleting file %1."), path)
473 if (!abort && doUpdates) updateProgress(1);
475 if (abort || response == FileOperator::IGNORE) return false;
480 void FileManipulatorThread::copy(const QFileInfo &file) {
481 std::cout << "COPYING " << file.absoluteFilePath().toStdString()
482 << " to " << dest.absolutePath().toStdString() << std::endl;
484 QString path(file.absoluteFilePath());
485 QFSFileEngine engine(path);
486 QFileInfo newFile(dest.absolutePath() + "/" + file.fileName());
490 // hack to prevent asking about the same file if we already asked in the rename(...) function
491 if (overwriteAll == FileOperator::DONT_ASK_ONCE) {
492 overwriteAll = FileOperator::NONE;
494 OVERWRITE_PROMPT(file, newFile)
497 QString newPath(newFile.absoluteFilePath());
498 QFSFileEngine newEngine(newPath);
503 // save the overwrite response, because the response variable will get ovewritten in remove(...)
504 FileOperator::Response overwriteResponse = response;
506 if (newFile.exists() && !newFile.isDir()) {
507 // overwriting a file, so check for KEEP and handle it
508 if (response == FileOperator::KEEP) {
509 updateProgress(fileSizeMap[path]);
510 removeExcludeFiles.insert(path);
514 // if it should not be kept, remove it and return on failure
515 if(!remove(newPath)) {
516 updateProgress(fileSizeMap[path]);
519 // create new info since we deleted the file - is it needed?
520 newFile = QFileInfo(newPath);
522 // overwriting a directory - response KEEP means to keep the files inside,
523 // SKIP_DIR means to skip the dir completely
524 if (response == FileOperator::SKIP_DIR) {
525 updateProgress(fileSizeMap[path]);
526 removeExcludeFiles.insert(path);
531 if (!newFile.exists()) {
532 SPECIAL_COPY_ERROR_PROMPT(!engine.mkdir(newPath, false),
533 tr("Error creating directory %1."), newPath)
536 // we've done the job with the dir, so update progress and recurse into the dir
539 // change the dest for the recursion
540 QDir destBackup = dest;
543 // and set overwriteAll to the response we got a while ago
544 // because it applies to the files inside the dir
545 FileOperator::Response tmpResp = overwriteAll;
546 overwriteAll = overwriteResponse;
548 processFiles(listDirFiles(path));
550 overwriteAll = tmpResp;
552 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
553 tr("Error setting permissions for directory %1."), newPath)
559 if (response == FileOperator::KEEP) {
560 updateProgress(fileSizeMap[path]);
561 removeExcludeFiles.insert(path);
565 SPECIAL_COPY_ERROR_PROMPT(engine.isSequential(), tr("Cannot copy sequential file %1."), path)
567 if (newFile.exists() && newFile.isDir()) {
568 SPECIAL_COPY_ERROR_PROMPT(!remove(newPath),
569 tr("Cannot replace directory %1 due to previous errors."), newPath)
572 SPECIAL_COPY_ERROR_PROMPT(!engine.open(QIODevice::ReadOnly), tr("Error reading file %1."), path)
574 bool ignore = false, newFileWritten = false;
575 while (!abort && !ignore) {
579 ERROR_PROMPT(!newEngine.open(QIODevice::WriteOnly | QIODevice::Truncate),
580 tr("Error writing file %1."), newPath)
582 if (abort || response == FileOperator::IGNORE) {
583 if (response == FileOperator::IGNORE) {
584 updateProgress(fileSizeMap[path]);
585 removeExcludeFiles.insert(path);
591 newFileWritten = true;
594 char block[BLOCK_SIZE];
596 while ((bytes = engine.read(block, sizeof(block))) > 0) {
597 if (bytes == -1 || bytes != newEngine.write(block, bytes)) {
599 SHOW_ERROR_PROMPT(tr("Error while reading from file %1."), path);
601 SHOW_ERROR_PROMPT(tr("Error while writing to file %1."), newPath);
605 if (response == FileOperator::IGNORE) {
606 updateProgress(fileSizeMap[path] - fileValue);
607 removeExcludeFiles.insert(path);
610 updateProgress(-fileValue);
626 if (abort || ignore) {
627 if (newFileWritten) {
631 ERROR_PROMPT(!newEngine.setPermissions(file.permissions()),
632 tr("Error setting permissions for file %1."), newPath)
638 unsigned int FileManipulatorThread::calculateFileSize(const QFileInfoList &files,
642 unsigned int res = 0;
644 for (QFileInfoList::const_iterator it = files.begin(); it != files.end(); ++it) {
645 unsigned int size = 0;
648 size += calculateFileSize(listDirFiles(it->absoluteFilePath()), count, addSize);
655 size += ceil(static_cast<float>(it->size()) / BLOCK_SIZE);
657 fileSizeMap[it->absoluteFilePath()] = size;
671 QFileInfoList FileManipulatorThread::listDirFiles(const QString &dirPath) {
673 return dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries | QDir::System | QDir::Hidden);
677 void FileManipulatorThread::setBarSize(unsigned int size) {
679 emit setBarSize(this, size);
683 void FileManipulatorThread::updateProgress(int value) {
686 emit updateProgress(this, value);
690 void FileManipulatorThread::updateFile(const QString &name) {
692 fileName = FileOperator::shortenPath(name);
693 emit updateProgress(this, 0);
697 void FileManipulatorThread::setText(int value) {
698 if (progressBar->value() + value > progressBar->maximum()) {
699 std::cout << "WARNING: exceeding progressbar maximum (" << progressBar->maximum()
700 << ") by " << value << std::endl;
703 time_t now = time(0);
704 if (lastTimeUpdate < now) {
705 lastTimeUpdate = now;
707 time_t elapsed = now - startTime;
708 time_t remaining = (time_t) ((float) elapsed / barValue * (barSize - barValue));
709 struct tm *ts = gmtime(&remaining);
711 if (remaining < 60) {
712 strftime(timeBuf, sizeof(timeBuf), "%Ss", ts);
713 } else if (remaining < 3600) {
714 strftime(timeBuf, sizeof(timeBuf), "%M:%S", ts);
716 strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", ts);
720 progressBar->setFormat(barText.arg(fileName) + "\n%p% ETA " + timeBuf);
721 progressBar->setValue(progressBar->value() + value);
725 DeleteThread::DeleteThread(const QFileInfoList &files) : FileManipulatorThread(files) {
726 barText = tr("deleting %1");
730 void DeleteThread::run() {
733 setBarSize(calculateFileSize(files, true));
742 void DeleteThread::perform(const QFileInfo &file) {
747 CopyThread::CopyThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
748 barText = tr("copying %1");
752 void CopyThread::run() {
755 setBarSize(calculateFileSize(files, false, true));
764 void CopyThread::perform(const QFileInfo &file) {
769 MoveThread::MoveThread(const QFileInfoList &files, QDir &dest) : FileManipulatorThread(files, dest) {
770 barText = tr("moving %1");
774 void MoveThread::run() {
784 void MoveThread::rename(const QFileInfoList &files, const QDir &dest) {
785 setBarSize(barSize + files.size());
787 for (int i = 0; i < files.size(); ++i) {
788 QString path = files[i].absoluteFilePath();
789 QFSFileEngine engine(path);
790 QFileInfo newFile(dest.absolutePath() + "/" + files[i].fileName());
794 OVERWRITE_PROMPT(files[i], newFile)
796 // if we are owerwriting dir over a dir, we will get SKIP_DIR
797 // as a response from OVERWRITE_PROMT meaning we should skip it
798 // (KEEP would mean to keep the files inside)
799 if (files[i].isDir() && newFile.exists() && newFile.isDir()) {
800 if (response == FileOperator::SKIP_DIR) {
803 removeExcludeFiles.insert(path);
807 if (response == FileOperator::KEEP) {
810 removeExcludeFiles.insert(path);
815 QString newPath(newFile.absoluteFilePath());
816 QFSFileEngine newEngine(newPath);
818 while (!abort && !engine.rename(newPath)) {
819 // source and target are on different partitions
820 // this should happen on the first file, unless some are skipped by overwrite prompt
821 // we calculate the actual file sizes, because from now on copy & remove takes over
822 if (errno == EXDEV) {
823 overwriteAll = response;
824 // hack: we already checked the first file we are sending to processFiles(...)
825 // so we don't want to ask about this one again
826 if (overwriteAll == FileOperator::NONE) overwriteAll = FileOperator::DONT_ASK_ONCE;
828 QFileInfoList remainingFiles = files.mid(i);
830 setBarSize(barValue + calculateFileSize(remainingFiles, true, true));
832 processFiles(remainingFiles);
834 barText = tr("deleting %1");
836 remove(remainingFiles, true);
838 // just to quit the loops, we are done
840 // the target is nonempty dir. lets call this recursively and rename the contents one by one
841 } else if (errno == ENOTEMPTY || errno == EEXIST) {
842 FileOperator::Response tmpResp = overwriteAll;
843 overwriteAll = response;
845 rename(listDirFiles(path), QDir(newPath));
848 overwriteAll = tmpResp;
853 // source and target are nonmatching types(file and dir)
854 // remove the target and let it loop once again
855 } else if (errno == ENOTDIR || errno == EISDIR) {
856 if (!remove(newPath)) break;
858 SHOW_ERROR_PROMPT(tr("Error moving %1."), path)
860 if (response == FileOperator::IGNORE) {
872 void MoveThread::perform(const QFileInfo &file) {