QGCTemporaryFile.cc 1.94 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8 9
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

10 11 12 13 14 15 16 17 18 19 20

/// @file
///     @brief This class mimics QTemporaryFile. We have our own implementation due to the fact that
///				QTemporaryFile implemenation differs cross platform making it unusable for our use-case.
///				Look for bug reports on QTemporaryFile keeping the file locked for details.
///
///     @author Don Gagne <don@thegagnes.com>

#include "QGCTemporaryFile.h"

#include <QDir>
21
#include <QRandomGenerator>
22 23 24 25 26 27 28 29 30
#include <QStandardPaths>

QGCTemporaryFile::QGCTemporaryFile(const QString& fileTemplate, QObject* parent) :
    QFile(parent),
    _template(fileTemplate)
{

}

31 32 33 34 35 36 37
QGCTemporaryFile::~QGCTemporaryFile()
{
    if (_autoRemove) {
        remove();
    }
}

38 39
bool QGCTemporaryFile::open(QFile::OpenMode openMode)
{
40
    setFileName(_newTempFileFullyQualifiedName(_template));
41
    
42 43 44 45 46 47 48 49
    return QFile::open(openMode);
}

QString QGCTemporaryFile::_newTempFileFullyQualifiedName(const QString& fileTemplate)
{
    QString nameTemplate = fileTemplate;
    QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));

50
    // Generate unique, non-existing filename
51

52
    static const char rgDigits[] = "0123456789";
53

54
    QString tempFilename;
55

56 57 58
    do {
        QString uniqueStr;
        for (int i=0; i<6; i++) {
59
            uniqueStr += rgDigits[QRandomGenerator::global()->generate() % 10];
60
        }
61 62 63

        if (fileTemplate.contains("XXXXXX")) {
            tempFilename = nameTemplate.replace("XXXXXX", uniqueStr, Qt::CaseSensitive);
64
        } else {
65
            tempFilename = nameTemplate + uniqueStr;
66 67 68
        }
    } while (tempDir.exists(tempFilename));

69
    return tempDir.filePath(tempFilename);
70
}