1/*
2 * Copyright (C) 2007 Staikos Computing Services Inc.
3 * Copyright (C) 2007 Holger Hans Peter Freyther
4 * Copyright (C) 2008 Apple, Inc. All rights reserved.
5 * Copyright (C) 2008 Collabora, Ltd. All rights reserved.
6 * Copyright (C) 2010 Sencha, Inc. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1.  Redistributions of source code must retain the above copyright
13 *     notice, this list of conditions and the following disclaimer.
14 * 2.  Redistributions in binary form must reproduce the above copyright
15 *     notice, this list of conditions and the following disclaimer in the
16 *     documentation and/or other materials provided with the distribution.
17 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
18 *     its contributors may be used to endorse or promote products derived
19 *     from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
22 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
25 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include "config.h"
34#include "FileSystem.h"
35
36#include "FileMetadata.h"
37#include <QDateTime>
38#include <QDir>
39#include <QFile>
40#include <QFileInfo>
41#include <QTemporaryFile>
42#include <wtf/text/CString.h>
43#include <wtf/text/WTFString.h>
44
45#if !defined(Q_OS_WIN)
46#include <sys/statvfs.h>
47#endif
48
49namespace WebCore {
50
51bool fileExists(const String& path)
52{
53    return QFile::exists(path);
54}
55
56
57bool deleteFile(const String& path)
58{
59    return QFile::remove(path);
60}
61
62bool deleteEmptyDirectory(const String& path)
63{
64    return QDir::root().rmdir(path);
65}
66
67bool getFileSize(const String& path, long long& result)
68{
69    QFileInfo info(path);
70    result = info.size();
71    return info.exists();
72}
73
74bool getFileModificationTime(const String& path, time_t& result)
75{
76    QFileInfo info(path);
77    result = info.lastModified().toTime_t();
78    return info.exists();
79}
80
81bool getFileMetadata(const String& path, FileMetadata& result)
82{
83    QFileInfo info(path);
84    if (!info.exists())
85        return false;
86    result.modificationTime = info.lastModified().toTime_t();
87    result.length = info.size();
88    result.type = info.isDir() ? FileMetadata::TypeDirectory : FileMetadata::TypeFile;
89    return true;
90}
91
92bool makeAllDirectories(const String& path)
93{
94    return QDir::root().mkpath(path);
95}
96
97String pathByAppendingComponent(const String& path, const String& component)
98{
99    return QDir::toNativeSeparators(QDir(path).filePath(component));
100}
101
102String homeDirectoryPath()
103{
104    return QDir::homePath();
105}
106
107String pathGetFileName(const String& path)
108{
109    return QFileInfo(path).fileName();
110}
111
112String directoryName(const String& path)
113{
114    return QFileInfo(path).absolutePath();
115}
116
117Vector<String> listDirectory(const String& path, const String& filter)
118{
119    Vector<String> entries;
120
121    QStringList nameFilters;
122    if (!filter.isEmpty())
123        nameFilters.append(filter);
124    QFileInfoList fileInfoList = QDir(path).entryInfoList(nameFilters, QDir::AllEntries | QDir::NoDotAndDotDot);
125    foreach (const QFileInfo fileInfo, fileInfoList) {
126        String entry = String(fileInfo.canonicalFilePath());
127        entries.append(entry);
128    }
129
130    return entries;
131}
132
133String openTemporaryFile(const String& prefix, PlatformFileHandle& handle)
134{
135#ifndef QT_NO_TEMPORARYFILE
136    QTemporaryFile* tempFile = new QTemporaryFile(QDir::tempPath() + QLatin1Char('/') + QString(prefix));
137    tempFile->setAutoRemove(false);
138    QFile* temp = tempFile;
139    if (temp->open(QIODevice::ReadWrite)) {
140        handle = temp;
141        return temp->fileName();
142    }
143#endif
144    handle = invalidPlatformFileHandle;
145    return String();
146}
147
148PlatformFileHandle openFile(const String& path, FileOpenMode mode)
149{
150    QIODevice::OpenMode platformMode;
151
152    if (mode == OpenForRead)
153        platformMode = QIODevice::ReadOnly;
154    else if (mode == OpenForWrite)
155        platformMode = (QIODevice::WriteOnly | QIODevice::Truncate);
156    else
157        return invalidPlatformFileHandle;
158
159    QFile* file = new QFile(path);
160    if (file->open(platformMode))
161        return file;
162
163    return invalidPlatformFileHandle;
164}
165
166int readFromFile(PlatformFileHandle handle, char* data, int length)
167{
168    if (handle && handle->exists() && handle->isReadable())
169        return handle->read(data, length);
170    return 0;
171}
172
173void closeFile(PlatformFileHandle& handle)
174{
175    if (handle) {
176        handle->close();
177        delete handle;
178    }
179}
180
181long long seekFile(PlatformFileHandle handle, long long offset, FileSeekOrigin origin)
182{
183    if (handle) {
184        long long current = 0;
185
186        switch (origin) {
187        case SeekFromBeginning:
188            break;
189        case SeekFromCurrent:
190            current = handle->pos();
191            break;
192        case SeekFromEnd:
193            current = handle->size();
194            break;
195        }
196
197        // Add the offset to the current position and seek to the new position
198        // Return our new position if the seek is successful
199        current += offset;
200        if (handle->seek(current))
201            return current;
202        else
203            return -1;
204    }
205
206    return -1;
207}
208
209uint64_t getVolumeFreeSizeForPath(const char* path)
210{
211#if defined(Q_OS_WIN)
212    ULARGE_INTEGER freeBytesToCaller;
213    BOOL result = GetDiskFreeSpaceExW((LPCWSTR)path, &freeBytesToCaller, 0, 0);
214    if (!result)
215        return 0;
216    return static_cast<uint64_t>(freeBytesToCaller.QuadPart);
217#else
218    struct statvfs volumeInfo;
219    if (statvfs(path, &volumeInfo))
220        return 0;
221
222    return static_cast<uint64_t>(volumeInfo.f_bavail) * static_cast<uint64_t>(volumeInfo.f_frsize);
223#endif
224}
225
226
227int writeToFile(PlatformFileHandle handle, const char* data, int length)
228{
229    if (handle && handle->exists() && handle->isWritable())
230        return handle->write(data, length);
231
232    return 0;
233}
234
235bool unloadModule(PlatformModule module)
236{
237#if defined(Q_WS_MAC)
238    CFRelease(module);
239    return true;
240
241#elif defined(Q_OS_WIN)
242    return ::FreeLibrary(module);
243
244#else
245#ifndef QT_NO_LIBRARY
246    if (module->unload()) {
247        delete module;
248        return true;
249    }
250#endif
251    return false;
252#endif
253}
254
255}
256
257// vim: ts=4 sw=4 et
258