fileutils.cpp 27 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
hjk's avatar
hjk committed
25 26
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30 31 32 33

#include "fileutils.h"
#include "savefile.h"

34
#include "algorithm.h"
35
#include "hostosinfo.h"
36 37
#include "qtcassert.h"

38
#include <QDir>
39
#include <QDebug>
40
#include <QDateTime>
41 42
#include <QDragEnterEvent>
#include <QDropEvent>
43
#include <QMessageBox>
44
#include <QTimer>
Christian Kandeler's avatar
Christian Kandeler committed
45
#include <QUrl>
46

Orgad Shaneh's avatar
Orgad Shaneh committed
47 48
#ifdef Q_OS_WIN
#include <qt_windows.h>
49
#include <shlobj.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
50 51
#endif

52 53 54 55 56 57 58 59
QT_BEGIN_NAMESPACE
QDebug operator<<(QDebug dbg, const Utils::FileName &c)
{
    return dbg << c.toString();
}

QT_END_NAMESPACE

Eike Ziller's avatar
Eike Ziller committed
60 61 62 63 64 65 66 67 68
#ifdef Q_OS_OSX
// for file drops from Finder, working around QTBUG-40449
namespace Utils {
namespace Internal {
extern QUrl filePathUrl(const QUrl &url);
} // Internal
} // Utils
#endif

69 70
namespace Utils {

71 72
/*! \class Utils::FileUtils

73 74
  \brief The FileUtils class contains file and directory related convenience
  functions.
75 76 77 78 79 80 81 82

*/

/*!
  Removes the directory \a filePath and its subdirectories recursively.

  \note The \a error parameter is optional.

Leena Miettinen's avatar
Leena Miettinen committed
83
  Returns whether the operation succeeded.
84
*/
85
bool FileUtils::removeRecursively(const FileName &filePath, QString *error)
86
{
87
    QFileInfo fileInfo = filePath.toFileInfo();
88
    if (!fileInfo.exists() && !fileInfo.isSymLink())
89
        return true;
90
    QFile::setPermissions(filePath.toString(), fileInfo.permissions() | QFile::WriteUser);
91
    if (fileInfo.isDir()) {
92
        QDir dir(filePath.toString());
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        dir = dir.canonicalPath();
        if (dir.isRoot()) {
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils",
                    "Refusing to remove root directory.");
            }
            return false;
        }
        if (dir.path() == QDir::home().canonicalPath()) {
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils",
                    "Refusing to remove your home directory.");
            }
            return false;
        }

109 110 111
        QStringList fileNames = dir.entryList(QDir::Files | QDir::Hidden
                                              | QDir::System | QDir::Dirs | QDir::NoDotAndDotDot);
        foreach (const QString &fileName, fileNames) {
112
            if (!removeRecursively(FileName(filePath).appendPath(fileName), error))
113 114
                return false;
        }
115
        if (!QDir::root().rmdir(dir.path())) {
116
            if (error) {
117
                *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove directory \"%1\".")
118
                        .arg(filePath.toUserOutput());
119 120 121 122
            }
            return false;
        }
    } else {
123
        if (!QFile::remove(filePath.toString())) {
124
            if (error) {
125
                *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove file \"%1\".")
126
                        .arg(filePath.toUserOutput());
127 128 129 130 131 132 133
            }
            return false;
        }
    }
    return true;
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
/*!
  Copies the directory specified by \a srcFilePath recursively to \a tgtFilePath. \a tgtFilePath will contain
  the target directory, which will be created. Example usage:

  \code
    QString error;
    book ok = Utils::FileUtils::copyRecursively("/foo/bar", "/foo/baz", &error);
    if (!ok)
      qDebug() << error;
  \endcode

  This will copy the contents of /foo/bar into to the baz directory under /foo, which will be created in the process.

  \note The \a error parameter is optional.

Leena Miettinen's avatar
Leena Miettinen committed
149
  Returns whether the operation succeeded.
150
*/
151
bool FileUtils::copyRecursively(const FileName &srcFilePath, const FileName &tgtFilePath,
BogDan Vatra's avatar
BogDan Vatra committed
152
                                QString *error, const std::function<bool (QFileInfo, QFileInfo, QString *)> &copyHelper)
153
{
154
    QFileInfo srcFileInfo = srcFilePath.toFileInfo();
155
    if (srcFileInfo.isDir()) {
hjk's avatar
hjk committed
156
        if (!tgtFilePath.exists()) {
BogDan Vatra's avatar
BogDan Vatra committed
157 158 159 160 161 162 163 164
            QDir targetDir(tgtFilePath.toString());
            targetDir.cdUp();
            if (!targetDir.mkdir(tgtFilePath.toFileInfo().fileName())) {
                if (error) {
                    *error = QCoreApplication::translate("Utils::FileUtils", "Failed to create directory \"%1\".")
                            .arg(tgtFilePath.toUserOutput());
                }
                return false;
165 166
            }
        }
167 168 169
        QDir sourceDir(srcFilePath.toString());
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot
                                                    | QDir::Hidden | QDir::System);
170
        foreach (const QString &fileName, fileNames) {
171 172 173 174
            FileName newSrcFilePath = srcFilePath;
            newSrcFilePath.appendPath(fileName);
            FileName newTgtFilePath = tgtFilePath;
            newTgtFilePath.appendPath(fileName);
BogDan Vatra's avatar
BogDan Vatra committed
175
            if (!copyRecursively(newSrcFilePath, newTgtFilePath, error, copyHelper))
176 177 178
                return false;
        }
    } else {
BogDan Vatra's avatar
BogDan Vatra committed
179 180 181 182 183 184 185 186 187 188
        if (copyHelper) {
            if (!copyHelper(srcFileInfo, tgtFilePath.toFileInfo(), error))
                return false;
        } else {
            if (!QFile::copy(srcFilePath.toString(), tgtFilePath.toString())) {
                if (error) {
                    *error = QCoreApplication::translate("Utils::FileUtils", "Could not copy file \"%1\" to \"%2\".")
                            .arg(srcFilePath.toUserOutput(), tgtFilePath.toUserOutput());
                }
                return false;
189 190 191 192 193 194
            }
        }
    }
    return true;
}

195 196 197
/*!
  If \a filePath is a directory, the function will recursively check all files and return
  true if one of them is newer than \a timeStamp. If \a filePath is a single file, true will
Tobias Hunger's avatar
Tobias Hunger committed
198
  be returned if the file is newer than \a timeStamp.
199

Leena Miettinen's avatar
Leena Miettinen committed
200 201
  Returns whether at least one file in \a filePath has a newer date than
  \a timeStamp.
202
*/
203
bool FileUtils::isFileNewerThan(const FileName &filePath, const QDateTime &timeStamp)
204
{
205
    QFileInfo fileInfo = filePath.toFileInfo();
206 207 208
    if (!fileInfo.exists() || fileInfo.lastModified() >= timeStamp)
        return true;
    if (fileInfo.isDir()) {
209
        const QStringList dirContents = QDir(filePath.toString())
210 211
            .entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
        foreach (const QString &curFileName, dirContents) {
212
            if (isFileNewerThan(FileName(filePath).appendPath(curFileName), timeStamp))
213 214 215 216 217 218
                return true;
        }
    }
    return false;
}

219
/*!
Leena Miettinen's avatar
Leena Miettinen committed
220
  Recursively resolves possibly present symlinks in \a filePath.
221 222 223 224 225
  Unlike QFileInfo::canonicalFilePath(), this function will still return the expected target file
  even if the symlink is dangling.

  \note Maximum recursion depth == 16.

Leena Miettinen's avatar
Leena Miettinen committed
226
  Returns the symlink target file path.
227
*/
228
FileName FileUtils::resolveSymlinks(const FileName &path)
229
{
230
    QFileInfo f = path.toFileInfo();
231 232 233 234
    int links = 16;
    while (links-- && f.isSymLink())
        f.setFile(f.symLinkTarget());
    if (links <= 0)
235 236
        return FileName();
    return FileName::fromString(f.filePath());
237
}
238

239 240 241 242
/*!
  Like QDir::toNativeSeparators(), but use prefix '~' instead of $HOME on unix systems when an
  absolute path is given.

Leena Miettinen's avatar
Leena Miettinen committed
243
  Returns the possibly shortened path with native separators.
244 245 246 247 248 249 250 251 252 253 254 255 256
*/
QString FileUtils::shortNativePath(const FileName &path)
{
    if (HostOsInfo::isAnyUnixHost()) {
        const FileName home = FileName::fromString(QDir::cleanPath(QDir::homePath()));
        if (path.isChildOf(home)) {
            return QLatin1Char('~') + QDir::separator()
                + QDir::toNativeSeparators(path.relativeChildPath(home).toString());
        }
    }
    return path.toUserOutput();
}

257 258 259 260 261 262 263 264 265 266
QString FileUtils::fileSystemFriendlyName(const QString &name)
{
    QString result = name;
    result.replace(QRegExp(QLatin1String("\\W")), QLatin1String("_"));
    result.replace(QRegExp(QLatin1String("_+")), QLatin1String("_")); // compact _
    result.remove(QRegExp(QLatin1String("^_*"))); // remove leading _
    result.remove(QRegExp(QLatin1String("_+$"))); // remove trailing _
    if (result.isEmpty())
        result = QLatin1String("unknown");
    return result;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
}

int FileUtils::indexOfQmakeUnfriendly(const QString &name, int startpos)
{
    static QRegExp checkRegExp(QLatin1String("[^a-zA-Z0-9_.-]"));
    return checkRegExp.indexIn(name, startpos);
}

QString FileUtils::qmakeFriendlyName(const QString &name)
{
    QString result = name;

    // Remove characters that might trip up a build system (especially qmake):
    int pos = indexOfQmakeUnfriendly(result);
    while (pos >= 0) {
        result[pos] = QLatin1Char('_');
        pos = indexOfQmakeUnfriendly(result, pos);
    }
    return fileSystemFriendlyName(result);
286 287
}

288 289 290 291 292 293
bool FileUtils::makeWritable(const FileName &path)
{
    const QString fileName = path.toString();
    return QFile::setPermissions(fileName, QFile::permissions(fileName) | QFile::WriteUser);
}

Orgad Shaneh's avatar
Orgad Shaneh committed
294 295 296 297 298
// makes sure that capitalization of directories is canonical on Windows.
// This mimics the logic in QDeclarative_isFileCaseCorrect
QString FileUtils::normalizePathName(const QString &name)
{
#ifdef Q_OS_WIN
299 300 301 302 303
    const QString nativeSeparatorName(QDir::toNativeSeparators(name));
    const LPCTSTR nameC = reinterpret_cast<LPCTSTR>(nativeSeparatorName.utf16()); // MinGW
    PIDLIST_ABSOLUTE file;
    HRESULT hr = SHParseDisplayName(nameC, NULL, &file, 0, NULL);
    if (FAILED(hr))
Orgad Shaneh's avatar
Orgad Shaneh committed
304
        return name;
305 306
    TCHAR buffer[MAX_PATH];
    if (!SHGetPathFromIDList(file, buffer))
Orgad Shaneh's avatar
Orgad Shaneh committed
307
        return name;
308
    return QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const ushort *>(buffer)));
Orgad Shaneh's avatar
Orgad Shaneh committed
309 310 311 312 313
#else // Filesystem is case-insensitive only on Windows
    return name;
#endif
}

314 315 316 317
bool FileUtils::isRelativePath(const QString &path)
{
    if (path.startsWith(QLatin1Char('/')))
        return false;
Christian Kandeler's avatar
Christian Kandeler committed
318 319 320 321 322 323 324 325 326
    if (HostOsInfo::isWindowsHost()) {
        if (path.startsWith(QLatin1Char('\\')))
            return false;
        // Unlike QFileInfo, this won't accept a relative path with a drive letter.
        // Such paths result in a royal mess anyway ...
        if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
                && (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\')))
            return false;
    }
327 328 329 330 331 332 333 334 335 336 337 338 339
    return true;
}

QString FileUtils::resolvePath(const QString &baseDir, const QString &fileName)
{
    if (fileName.isEmpty())
        return QString();
    if (isAbsolutePath(fileName))
        return QDir::cleanPath(fileName);
    return QDir::cleanPath(baseDir + QLatin1Char('/') + fileName);
}


340 341
QByteArray FileReader::fetchQrc(const QString &fileName)
{
342
    QTC_ASSERT(fileName.startsWith(QLatin1Char(':')), return QByteArray());
343 344
    QFile file(fileName);
    bool ok = file.open(QIODevice::ReadOnly);
345
    QTC_ASSERT(ok, qWarning() << fileName << "not there!"; return QByteArray());
346 347 348 349 350
    return file.readAll();
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode)
{
351
    QTC_ASSERT(!(mode & ~(QIODevice::ReadOnly | QIODevice::Text)), return false);
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | mode)) {
        m_errorString = tr("Cannot open %1 for reading: %2").arg(
                QDir::toNativeSeparators(fileName), file.errorString());
        return false;
    }
    m_data = file.readAll();
    if (file.error() != QFile::NoError) {
        m_errorString = tr("Cannot read %1: %2").arg(
                QDir::toNativeSeparators(fileName), file.errorString());
        return false;
    }
    return true;
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode, QString *errorString)
{
    if (fetch(fileName, mode))
        return true;
    if (errorString)
        *errorString = m_errorString;
    return false;
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode, QWidget *parent)
{
    if (fetch(fileName, mode))
        return true;
    if (parent)
        QMessageBox::critical(parent, tr("File Error"), m_errorString);
    return false;
}


FileSaverBase::FileSaverBase()
    : m_hasError(false)
{
}

FileSaverBase::~FileSaverBase()
{
    delete m_file;
}

bool FileSaverBase::finalize()
{
    m_file->close();
    setResult(m_file->error() == QFile::NoError);
    // We delete the object, so it is really closed even if it is a QTemporaryFile.
    delete m_file;
    m_file = 0;
    return !m_hasError;
}

bool FileSaverBase::finalize(QString *errStr)
{
    if (finalize())
        return true;
    if (errStr)
        *errStr = errorString();
    return false;
}

bool FileSaverBase::finalize(QWidget *parent)
{
    if (finalize())
        return true;
    QMessageBox::critical(parent, tr("File Error"), errorString());
    return false;
}

bool FileSaverBase::write(const char *data, int len)
{
    if (m_hasError)
        return false;
    return setResult(m_file->write(data, len) == len);
}

bool FileSaverBase::write(const QByteArray &bytes)
{
    if (m_hasError)
        return false;
    return setResult(m_file->write(bytes) == bytes.count());
}

bool FileSaverBase::setResult(bool ok)
{
    if (!ok && !m_hasError) {
        m_errorString = tr("Cannot write file %1. Disk full?").arg(
                QDir::toNativeSeparators(m_fileName));
        m_hasError = true;
    }
    return ok;
}

bool FileSaverBase::setResult(QTextStream *stream)
{
    stream->flush();
    return setResult(stream->status() == QTextStream::Ok);
}

bool FileSaverBase::setResult(QDataStream *stream)
{
456
    return setResult(stream->status() == QDataStream::Ok);
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
}

bool FileSaverBase::setResult(QXmlStreamWriter *stream)
{
    return setResult(!stream->hasError());
}


FileSaver::FileSaver(const QString &filename, QIODevice::OpenMode mode)
{
    m_fileName = filename;
    if (mode & (QIODevice::ReadOnly | QIODevice::Append)) {
        m_file = new QFile(filename);
        m_isSafe = false;
    } else {
        m_file = new SaveFile(filename);
        m_isSafe = true;
    }
    if (!m_file->open(QIODevice::WriteOnly | mode)) {
        QString err = QFile::exists(filename) ?
                tr("Cannot overwrite file %1: %2") : tr("Cannot create file %1: %2");
        m_errorString = err.arg(QDir::toNativeSeparators(filename), m_file->errorString());
        m_hasError = true;
    }
}

bool FileSaver::finalize()
{
    if (!m_isSafe)
        return FileSaverBase::finalize();

    SaveFile *sf = static_cast<SaveFile *>(m_file);
489 490 491 492
    if (m_hasError) {
        if (sf->isOpen())
            sf->rollback();
    } else {
493
        setResult(sf->commit());
494
    }
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    delete sf;
    m_file = 0;
    return !m_hasError;
}

TempFileSaver::TempFileSaver(const QString &templ)
    : m_autoRemove(true)
{
    QTemporaryFile *tempFile = new QTemporaryFile();
    if (!templ.isEmpty())
        tempFile->setFileTemplate(templ);
    tempFile->setAutoRemove(false);
    if (!tempFile->open()) {
        m_errorString = tr("Cannot create temporary file in %1: %2").arg(
                QDir::toNativeSeparators(QFileInfo(tempFile->fileTemplate()).absolutePath()),
                tempFile->errorString());
        m_hasError = true;
    }
    m_file = tempFile;
    m_fileName = tempFile->fileName();
}

TempFileSaver::~TempFileSaver()
{
    delete m_file;
    m_file = 0;
    if (m_autoRemove)
        QFile::remove(m_fileName);
}

525 526
/*! \class Utils::FileName

527
    \brief The FileName class is a light-weight convenience class for filenames.
528 529 530 531

    On windows filenames are compared case insensitively.
*/

Daniel Teske's avatar
Daniel Teske committed
532 533 534 535 536 537
FileName::FileName()
    : QString()
{

}

538
/// Constructs a FileName from \a info
Daniel Teske's avatar
Daniel Teske committed
539 540 541 542 543
FileName::FileName(const QFileInfo &info)
    : QString(info.absoluteFilePath())
{
}

544 545 546 547 548 549 550
/// \returns a QFileInfo
QFileInfo FileName::toFileInfo() const
{
    return QFileInfo(*this);
}

/// \returns a QString for passing on to QString based APIs
Daniel Teske's avatar
Daniel Teske committed
551 552 553 554 555
QString FileName::toString() const
{
    return QString(*this);
}

556 557 558 559 560 561 562
/// \returns a QString to display to the user
/// Converts the separators to the native format
QString FileName::toUserOutput() const
{
    return QDir::toNativeSeparators(toString());
}

hjk's avatar
hjk committed
563 564 565 566 567 568 569
/// \returns a bool indicating whether a file with this
/// FileName exists.
bool FileName::exists() const
{
    return QFileInfo::exists(*this);
}

570 571
/// Find the parent directory of a given directory.

Sergio Ahumada's avatar
Sergio Ahumada committed
572
/// Returns an empty FileName if the current directory is already
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
/// a root level directory.

/// \returns \a FileName with the last segment removed.
FileName FileName::parentDir() const
{
    const QString basePath = toString();
    if (basePath.isEmpty())
        return FileName();

    const QDir base(basePath);
    if (base.isRoot())
        return FileName();

    const QString path = basePath + QLatin1String("/..");
    const QString parent = QDir::cleanPath(path);

    return FileName::fromString(parent);
}

592 593
/// Constructs a FileName from \a filename
/// \a filename is not checked for validity.
Daniel Teske's avatar
Daniel Teske committed
594 595 596 597 598
FileName FileName::fromString(const QString &filename)
{
    return FileName(filename);
}

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
/// Constructs a FileName from \a fileName. The \a defaultExtension is appended
/// to \a filename if that does not have an extension already.
/// \a fileName is not checked for validity.
FileName FileName::fromString(const QString &filename, const QString &defaultExtension)
{
    if (filename.isEmpty() || defaultExtension.isEmpty())
        return filename;

    QString rc = filename;
    QFileInfo fi(filename);
    // Add extension unless user specified something else
    const QChar dot = QLatin1Char('.');
    if (!fi.fileName().contains(dot)) {
        if (!defaultExtension.startsWith(dot))
            rc += dot;
        rc += defaultExtension;
    }
    return rc;
}

619 620 621 622 623 624 625
/// Constructs a FileName from \a fileName
/// \a fileName is not checked for validity.
FileName FileName::fromLatin1(const QByteArray &filename)
{
    return FileName(QString::fromLatin1(filename));
}

626 627 628 629
/// Constructs a FileName from \a fileName
/// \a fileName is only passed through QDir::cleanPath
FileName FileName::fromUserInput(const QString &filename)
{
630 631
    QString clean = QDir::cleanPath(filename);
    if (clean.startsWith(QLatin1String("~/")))
Eike Ziller's avatar
Eike Ziller committed
632
        clean = QDir::homePath() + clean.mid(1);
633
    return FileName(clean);
634 635
}

636 637 638 639 640 641 642
/// Constructs a FileName from \a fileName, which is encoded as UTF-8.
/// \a fileName is not checked for validity.
FileName FileName::fromUtf8(const char *filename, int filenameSize)
{
    return FileName(QString::fromUtf8(filename, filenameSize));
}

Daniel Teske's avatar
Daniel Teske committed
643 644 645 646 647
FileName::FileName(const QString &string)
    : QString(string)
{

}
648

Daniel Teske's avatar
Daniel Teske committed
649 650
bool FileName::operator==(const FileName &other) const
{
651
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) == 0;
Daniel Teske's avatar
Daniel Teske committed
652 653
}

654 655 656 657 658
bool FileName::operator!=(const FileName &other) const
{
    return !(*this == other);
}

Daniel Teske's avatar
Daniel Teske committed
659 660
bool FileName::operator<(const FileName &other) const
{
661
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) < 0;
Daniel Teske's avatar
Daniel Teske committed
662 663 664 665
}

bool FileName::operator<=(const FileName &other) const
{
666
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) <= 0;
Daniel Teske's avatar
Daniel Teske committed
667 668 669 670 671 672 673 674 675 676 677 678
}

bool FileName::operator>(const FileName &other) const
{
    return other < *this;
}

bool FileName::operator>=(const FileName &other) const
{
    return other <= *this;
}

679 680
/// \returns whether FileName is a child of \a s
bool FileName::isChildOf(const FileName &s) const
Daniel Teske's avatar
Daniel Teske committed
681
{
682 683
    if (s.isEmpty())
        return false;
684
    if (!QString::startsWith(s, HostOsInfo::fileNameCaseSensitivity()))
685 686 687
        return false;
    if (size() <= s.size())
        return false;
688 689 690 691
    // s is root, '/' was already tested in startsWith
    if (s.QString::endsWith(QLatin1Char('/')))
        return true;
    // s is a directory, next character should be '/' (/tmpdir is NOT a child of /tmp)
692
    return at(s.size()) == QLatin1Char('/');
Daniel Teske's avatar
Daniel Teske committed
693 694
}

695 696 697
/// \overload
bool FileName::isChildOf(const QDir &dir) const
{
698
    return isChildOf(FileName::fromString(dir.absolutePath()));
699 700
}

701
/// \returns whether FileName endsWith \a s
Daniel Teske's avatar
Daniel Teske committed
702 703
bool FileName::endsWith(const QString &s) const
{
704
    return QString::endsWith(s, HostOsInfo::fileNameCaseSensitivity());
Daniel Teske's avatar
Daniel Teske committed
705 706
}

707 708 709 710
/// \returns the relativeChildPath of FileName to parent if FileName is a child of parent
/// \note returns a empty FileName if FileName is not a child of parent
/// That is, this never returns a path starting with "../"
FileName FileName::relativeChildPath(const FileName &parent) const
Daniel Teske's avatar
Daniel Teske committed
711
{
712
    if (!isChildOf(parent))
713
        return FileName();
714
    return FileName(QString::mid(parent.size() + 1, -1));
Daniel Teske's avatar
Daniel Teske committed
715 716
}

717
/// Appends \a s, ensuring a / between the parts
718
FileName &FileName::appendPath(const QString &s)
Daniel Teske's avatar
Daniel Teske committed
719
{
720 721
    if (s.isEmpty())
        return *this;
722
    if (!isEmpty() && !QString::endsWith(QLatin1Char('/')))
723 724
        appendString(QLatin1Char('/'));
    appendString(s);
725 726 727
    return *this;
}

728
FileName &FileName::appendString(const QString &str)
729 730 731 732 733
{
    QString::append(str);
    return *this;
}

734
FileName &FileName::appendString(QChar str)
735 736 737
{
    QString::append(str);
    return *this;
Daniel Teske's avatar
Daniel Teske committed
738 739
}

740 741 742 743 744
QTextStream &operator<<(QTextStream &s, const FileName &fn)
{
    return s << fn.toString();
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
int FileNameList::removeDuplicates()
{
    QSet<FileName> seen;
    int removed = 0;

    for (int i = 0; i < size(); ) {
        const FileName &fn = at(i);
        if (seen.contains(fn)) {
            removeAt(i);
            ++removed;
        } else {
            seen.insert(fn);
            ++i;
        }
    }

    return removed;
}

764
static bool isFileDrop(const QMimeData *d, QList<FileDropSupport::FileSpec> *files = 0)
765
{
766 767 768 769 770 771 772 773
    // internal drop
    if (const FileDropMimeData *internalData = qobject_cast<const FileDropMimeData *>(d)) {
        if (files)
            *files = internalData->files();
        return true;
    }

    // external drop
774 775 776 777 778 779 780 781 782 783 784 785
    if (files)
        files->clear();
    // Extract dropped files from Mime data.
    if (!d->hasUrls())
        return false;
    const QList<QUrl> urls = d->urls();
    if (urls.empty())
        return false;
    // Try to find local files
    bool hasFiles = false;
    const QList<QUrl>::const_iterator cend = urls.constEnd();
    for (QList<QUrl>::const_iterator it = urls.constBegin(); it != cend; ++it) {
Eike Ziller's avatar
Eike Ziller committed
786 787 788 789 790 791
        QUrl url = *it;
#ifdef Q_OS_OSX
        // for file drops from Finder, working around QTBUG-40449
        url = Internal::filePathUrl(url);
#endif
        const QString fileName = url.toLocalFile();
792 793 794
        if (!fileName.isEmpty()) {
            hasFiles = true;
            if (files)
795
                files->append(FileDropSupport::FileSpec(fileName));
796 797 798 799 800 801 802
            else
                break; // No result list, sufficient for checking
        }
    }
    return hasFiles;
}

803 804 805
FileDropSupport::FileDropSupport(QWidget *parentWidget, const DropFilterFunction &filterFunction)
    : QObject(parentWidget),
      m_filterFunction(filterFunction)
806 807 808 809 810 811
{
    QTC_ASSERT(parentWidget, return);
    parentWidget->setAcceptDrops(true);
    parentWidget->installEventFilter(this);
}

812 813 814 815 816
QStringList FileDropSupport::mimeTypesForFilePaths()
{
    return QStringList() << QStringLiteral("text/uri-list");
}

817 818 819 820 821
bool FileDropSupport::eventFilter(QObject *obj, QEvent *event)
{
    Q_UNUSED(obj)
    if (event->type() == QEvent::DragEnter) {
        auto dee = static_cast<QDragEnterEvent *>(event);
822
        if (isFileDrop(dee->mimeData())
823
                && (!m_filterFunction || m_filterFunction(dee)))
824 825 826
            event->accept();
        else
            event->ignore();
827 828 829 830
        return true;
    } else if (event->type() == QEvent::DragMove) {
        event->accept();
        return true;
831 832
    } else if (event->type() == QEvent::Drop) {
        auto de = static_cast<QDropEvent *>(event);
833 834
        QList<FileSpec> tempFiles;
        if (isFileDrop(de->mimeData(), &tempFiles)
835
                && (!m_filterFunction || m_filterFunction(de))) {
836
            const FileDropMimeData *fileDropMimeData = qobject_cast<const FileDropMimeData *>(de->mimeData());
837
            event->accept();
838 839 840 841
            if (fileDropMimeData && fileDropMimeData->isOverridingFileDropAction())
                de->setDropAction(fileDropMimeData->overrideFileDropAction());
            else
                de->acceptProposedAction();
842 843
            bool needToScheduleEmit = m_files.isEmpty();
            m_files.append(tempFiles);
844 845 846 847 848 849 850 851
            if (needToScheduleEmit) { // otherwise we already have a timer pending
                // Delay the actual drop, to avoid conflict between
                // actions that happen when opening files, and actions that the item views do
                // after the drag operation.
                // If we do not do this, e.g. dragging from Outline view crashes if the editor and
                // the selected item changes
                QTimer::singleShot(100, this, SLOT(emitFilesDropped()));
            }
852 853 854
        } else {
            event->ignore();
        }
855
        return true;
856 857 858 859 860 861 862 863 864 865 866
    }
    return false;
}

void FileDropSupport::emitFilesDropped()
{
    QTC_ASSERT(!m_files.isEmpty(), return);
    emit filesDropped(m_files);
    m_files.clear();
}

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
/*!
    Sets the drop action to effectively use, instead of the "proposed" drop action from the
    drop event. This can be useful when supporting move drags within an item view, but not
    "moving" an item from the item view into a split.
 */
FileDropMimeData::FileDropMimeData()
    : m_overrideDropAction(Qt::IgnoreAction),
      m_isOverridingDropAction(false)
{

}

void FileDropMimeData::setOverrideFileDropAction(Qt::DropAction action)
{
    m_isOverridingDropAction = true;
    m_overrideDropAction = action;
}

Qt::DropAction FileDropMimeData::overrideFileDropAction() const
{
    return m_overrideDropAction;
}

bool FileDropMimeData::isOverridingFileDropAction() const
{
    return m_isOverridingDropAction;
}

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
void FileDropMimeData::addFile(const QString &filePath, int line, int column)
{
    // standard mime data
    QList<QUrl> currentUrls = urls();
    currentUrls.append(QUrl::fromLocalFile(filePath));
    setUrls(currentUrls);
    // special mime data
    m_files.append(FileDropSupport::FileSpec(filePath, line, column));
}

QList<FileDropSupport::FileSpec> FileDropMimeData::files() const
{
    return m_files;
}

910
} // namespace Utils
Daniel Teske's avatar
Daniel Teske committed
911

912
QT_BEGIN_NAMESPACE
Daniel Teske's avatar
Daniel Teske committed
913 914
uint qHash(const Utils::FileName &a)
{
915
    if (Utils::HostOsInfo::fileNameCaseSensitivity() == Qt::CaseInsensitive)
916
        return qHash(a.toString().toUpper());
Daniel Teske's avatar
Daniel Teske committed
917 918
    return qHash(a.toString());
}
919
QT_END_NAMESPACE