Debian Codegraph @

src/dci/private/ddcifileengine.cpp

raw
1 // SPDX-FileCopyrightText: 2021 - 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4 #include <QtGlobal>
5
6 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
7 #include <filesystem> //Avoid changing the access control of the standard library
8 #endif
9
10 #define private public
11 #define protected public
12 #include <private/qfile_p.h>
13 #undef private
14 #undef protected
15
16 #include "ddcifileengine_p.h"
17 #include "dci/ddcifile.h"
18
19 #include <QBuffer>
20 #include <QLoggingCategory>
21
22 DCORE_BEGIN_NAMESPACE
23
24 #ifdef QT_DEBUG
25 Q_LOGGING_CATEGORY(logFE, "dtk.dci.fileengine")
26 #else
27 Q_LOGGING_CATEGORY(logFE, "dtk.dci.fileengine", QtInfoMsg)
28 #endif
29
30 #define DCI_FILE_SCHEME "dci:"
31 #define DCI_FILE_SUFFIX ".dci"
32
33 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
34 std::unique_ptr<QAbstractFileEngine> DDciFileEngineHandler::create(const QString &fileName) const
35 #else
36 QAbstractFileEngine *DDciFileEngineHandler::create(const QString &fileName) const
37 #endif
38 {
39 if (!fileName.startsWith(QStringLiteral(DCI_FILE_SCHEME)))
40 return nullptr;
41
42 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
43 std::unique_ptr<DDciFileEngine> engine(new DDciFileEngine(fileName));
44 #else
45 DDciFileEngine *engine = new DDciFileEngine(fileName);
46 #endif
47
48 if (!engine->isValid()) {
49 #if QT_VERSION < QT_VERSION_CHECK(6, 8, 0)
50 delete engine;
51 #endif
52 return nullptr;
53 }
54
55 return engine;
56 }
57
58 // 共享同个线程内的同个 DDciFile
59 static thread_local QHash<QString, QWeakPointer<DDciFile>> sharedDciFile;
60 static void doDeleteSharedDciFile(const QString &path, DDciFile *file) {
61 int count = sharedDciFile.remove(path);
62 Q_ASSERT(count > 0);
63 delete file;
64 }
65
66 static DDciFileShared getDciFile(const QString &dciFilePath, bool usePath = true)
67 {
68 if (auto shared = sharedDciFile.value(dciFilePath)) {
69 return shared.toStrongRef();
70 }
71
72 DDciFileShared shared(usePath ? new DDciFile(dciFilePath) : new DDciFile(),
73 std::bind(doDeleteSharedDciFile, dciFilePath,
74 std::placeholders::_1));
75 sharedDciFile[dciFilePath] = shared.toWeakRef();
76 return shared;
77 }
78
79 DDciFileEngineIterator::DDciFileEngineIterator(QDir::Filters filters, const QStringList &nameFilters)
80 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
81 : QAbstractFileEngineIterator(nullptr, filters, nameFilters)
82 #else
83 : QAbstractFileEngineIterator(filters, nameFilters)
84 #endif
85 {
86
87 }
88
89 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 1)
90 DDciFileEngineIterator::DDciFileEngineIterator(QDirListing::IteratorFlags filters, const QStringList &nameFilters)
91 : QAbstractFileEngineIterator(nullptr, filters, nameFilters)
92 {
93
94 }
95 #endif
96
97 #if QT_VERSION < QT_VERSION_CHECK(6, 8, 0)
98 QString DDciFileEngineIterator::next()
99 {
100 current = nextValid;
101 return DDciFileEngineIterator::currentFileName();
102 }
103
104 bool DDciFileEngineIterator::hasNext() const
105 #else
106 bool DDciFileEngineIterator::advance()
107 #endif
108 {
109 if (!file) {
110 const auto paths = DDciFileEngine::resolvePath(path());
111 if (paths.first.isEmpty()
112 || paths.second.isEmpty())
113 return false;
114
115 file = getDciFile(paths.first);
116 list = file->list(paths.second);
117 }
118
119 for (int i = current + 1; i < list.count(); ++i) {
120 // 先检查文件类型
121 const auto filters = this->filters();
122 const auto fileType = file->type(list.at(i));
123 if (fileType == DDciFile::Directory) {
124 if (!filters.testFlag(QDir::Files))
125 continue;
126 } else if (fileType == DDciFile::File) {
127 if (!filters.testFlag(QDir::Files))
128 continue;
129 } else if (fileType == DDciFile::Symlink) {
130 if (filters.testFlag(QDir::NoSymLinks))
131 continue;
132 } else { // DDciFile::UnknowFile
133 continue;
134 }
135
136 // 按名称进行过滤
137 if (!nameFilters().isEmpty() && !QDir::match(nameFilters(), list.at(i)))
138 continue;
139
140 nextValid = i;
141 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
142 current = nextValid;
143 #endif
144 return true;
145 }
146
147 return false;
148 }
149
150 QString DDciFileEngineIterator::currentFileName() const
151 {
152 return file->name(list.at(current));
153 }
154
155 DDciFileEngine::DDciFileEngine(const QString &fullPath)
156 {
157 setFileName(fullPath);
158 }
159
160 DDciFileEngine::~DDciFileEngine()
161 {
162 close();
163 }
164
165 bool DDciFileEngine::isValid() const
166 {
167 return file && file->isValid();
168 }
169
170 #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
171 bool DDciFileEngine::open(QIODevice::OpenMode openMode, std::optional<QFile::Permissions> permissions)
172 #else
173 bool DDciFileEngine::open(QIODevice::OpenMode openMode)
174 #endif
175 {
176 if (fileBuffer) {
177 setError(QFile::OpenError, "The file is opened");
178 return false;
179 }
180
181 if (!file->isValid()) {
182 setError(QFile::OpenError, "The DCI file is invalid");
183 return false;
184 }
185
186 if (file->type(subfilePath) == DDciFile::Directory) {
187 setError(QFile::OpenError, "Can't open a directory");
188 return false;
189 }
190
191 if (file->type(subfilePath) == DDciFile::Symlink) {
192 if (!file->exists(file->symlinkTarget(subfilePath))) {
193 setError(QFile::OpenError, "The symlink target is not existed");
194 return false;
195 }
196 }
197
198 if (openMode & QIODevice::Text) {
199 setError(QFile::OpenError, "Not supported open mode");
200 return false;
201 }
202
203 if (openMode & QIODevice::NewOnly) {
204 if (file->exists(subfilePath)) {
205 setError(QFile::OpenError, "The file is existed");
206 return false;
207 }
208 }
209
210 if ((openMode & QIODevice::ExistingOnly)
211 || !(openMode & QIODevice::WriteOnly)) {
212 if (!file->exists(subfilePath)) {
213 setError(QFile::OpenError, "The file is not exists");
214 return false;
215 }
216 }
217
218 // 此时当文件不存在时应当创建它
219 if (openMode & QIODevice::WriteOnly) {
220 realDciFile.setFileName(dciFilePath);
221 #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
222 auto success = permissions ? realDciFile.open(openMode, permissions.value()) : realDciFile.open(openMode);
223 if (!success)
224 return false;
225 #else
226 if (!realDciFile.open(openMode)) {
227 return false;
228 }
229 #endif
230
231 // 不存在时尝试新建
232 if (!file->exists(subfilePath)
233 && !file->writeFile(subfilePath, QByteArray())) {
234 return false;
235 }
236 }
237
238 // 加载数据
239 fileData = file->dataRef(subfilePath);
240 fileBuffer = new QBuffer(&fileData);
241 bool ok = fileBuffer->open(openMode);
242 Q_ASSERT(ok);
243 if (Q_UNLIKELY(!ok)) {
244 delete fileBuffer;
245 fileBuffer = nullptr;
246 return false;
247 }
248
249 return true;
250 }
251
252 bool DDciFileEngine::close()
253 {
254 if (!fileBuffer) {
255 return false;
256 }
257
258 fileBuffer->close();
259 delete fileBuffer;
260 fileBuffer = nullptr;
261
262 bool ok = flush();
263 realDciFile.close();
264 return ok;
265 }
266
267 bool DDciFileEngine::flushToFile(QFile *target, bool writeFile) const
268 {
269 if (target->isWritable()) {
270 if (writeFile && !file->writeFile(subfilePath, fileData, true))
271 return false;
272 if (!target->resize(0))
273 return false;
274 const QByteArray &data = file->toData();
275 if (target->write(data) != data.size())
276 return false;
277 return true;
278 }
279
280 return false;
281 }
282
283 bool DDciFileEngine::flush()
284 {
285 if (!flushToFile(&realDciFile, true))
286 return false;
287
288 return realDciFile.flush();
289 }
290
291 bool DDciFileEngine::syncToDisk()
292 {
293 if (!flush())
294 return false;
295 return realDciFile.d_func()->engine()->syncToDisk();
296 }
297
298 qint64 DDciFileEngine::size() const
299 {
300 if (fileBuffer) {
301 return fileData.size();
302 }
303
304 return file->dataRef(subfilePath).size();
305 }
306
307 qint64 DDciFileEngine::pos() const
308 {
309 return fileBuffer->size();
310 }
311
312 bool DDciFileEngine::seek(qint64 pos)
313 {
314 return fileBuffer->seek(pos);
315 }
316
317 bool DDciFileEngine::isSequential() const
318 {
319 return false;
320 }
321
322 bool DDciFileEngine::remove()
323 {
324 return file->isValid() && file->remove(subfilePath) && forceSave();
325 }
326
327 bool DDciFileEngine::copy(const QString &newName)
328 {
329 if (!file->isValid())
330 return false;
331 // 解析出新的 dci 内部文件路径
332 const auto paths = resolvePath(newName, dciFilePath);
333 if (paths.second.isEmpty())
334 return false;
335
336 return file->copy(subfilePath, paths.second) && forceSave();
337 }
338
339 bool DDciFileEngine::rename(const QString &newName)
340 {
341 if (!file->isValid())
342 return false;
343 // 解析出新的 dci 内部文件路径
344 const auto paths = resolvePath(newName, dciFilePath);
345 if (paths.second.isEmpty())
346 return false;
347
348 return file->rename(subfilePath, paths.second, false) && forceSave();
349 }
350
351 bool DDciFileEngine::renameOverwrite(const QString &newName)
352 {
353 if (!file->isValid())
354 return false;
355 // 解析出新的 dci 内部文件路径
356 const auto paths = resolvePath(newName, dciFilePath);
357 if (paths.second.isEmpty())
358 return false;
359
360 return file->rename(subfilePath, paths.second, true) && forceSave();
361 }
362
363 bool DDciFileEngine::link(const QString &newName)
364 {
365 if (!file->isValid())
366 return false;
367
368 // 解析出新的 dci 内部文件路径
369 const auto paths = resolvePath(newName, dciFilePath);
370 const QString &linkPath = paths.second.isEmpty() ? newName : paths.second;
371
372 return file->link(subfilePath, linkPath) && forceSave();
373 }
374
375 #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
376 bool DDciFileEngine::mkdir(const QString &dirName,
377 bool createParentDirectories,
378 std::optional<QFile::Permissions> permissions) const
379 {
380 Q_UNUSED(permissions)
381 #else
382 bool DDciFileEngine::mkdir(const QString &dirName, bool createParentDirectories) const
383 {
384 #endif
385 if (!file->isValid())
386 return false;
387 // 解析出新的 dci 内部文件路径
388 const auto paths = resolvePath(dirName, dciFilePath);
389 if (paths.second.isEmpty())
390 return false;
391
392 if (!createParentDirectories)
393 return file->mkdir(paths.second) && forceSave();
394
395 const QStringList dirItems = paths.second.split('/');
396 QString currentPath;
397 for (const QString &newDir : dirItems) {
398 if (newDir.isEmpty())
399 continue;
400 currentPath += ("/" + newDir);
401 if (file->exists(currentPath)) {
402 continue;
403 }
404 // 创建此路径
405 if (!file->mkdir(currentPath))
406 return false;
407 }
408
409 return forceSave();
410 }
411
412 bool DDciFileEngine::rmdir(const QString &dirName, bool recurseParentDirectories) const
413 {
414 if (!file->isValid())
415 return false;
416 // 解析出新的 dci 内部文件路径
417 const auto paths = resolvePath(dirName, dciFilePath);
418 if (paths.second.isEmpty())
419 return false;
420
421 if (!file->remove(paths.second))
422 return false;
423 if (!recurseParentDirectories)
424 return forceSave();
425
426 // 查找空的父目录
427 QDir dir(paths.second);
428
429 while (dir.cdUp()) {
430 // 不删除根
431 if (dir.isRoot())
432 break;
433
434 if (file->childrenCount(dir.absolutePath()) > 0)
435 continue;
436 if (!file->remove(dir.absolutePath()))
437 return false;
438 }
439
440 return forceSave();
441 }
442
443 bool DDciFileEngine::setSize(qint64 size)
444 {
445 if (!fileBuffer) {
446 fileData = file->dataRef(subfilePath);
447 }
448
449 // 确保新数据填充为 0
450 if (size > fileData.size()) {
451 fileData.append(size - fileData.size(), '\0');
452 } else {
453 fileData.resize(size);
454 }
455
456 return fileBuffer ? true : forceSave(true);
457 }
458
459 bool DDciFileEngine::caseSensitive() const
460 {
461 return true;
462 }
463
464 bool DDciFileEngine::isRelativePath() const
465 {
466 return !subfilePath.startsWith('/');
467 }
468
469 QByteArray DDciFileEngine::id() const
470 {
471 return fileName().toUtf8();
472 }
473
474 uint DDciFileEngine::ownerId(QAbstractFileEngine::FileOwner owner) const
475 {
476 QFileInfo info(dciFilePath);
477 return owner == OwnerUser ? info.ownerId() : info.groupId();
478 }
479
480 QString DDciFileEngine::owner(QAbstractFileEngine::FileOwner owner) const
481 {
482 QFileInfo info(dciFilePath);
483 return owner == OwnerUser ? info.owner() : info.group();
484 }
485
486 QAbstractFileEngine::FileFlags DDciFileEngine::fileFlags(QAbstractFileEngine::FileFlags type) const
487 {
488 auto flags = QAbstractFileEngine::FileFlags();
489
490 if (!file->isValid())
491 return flags;
492
493 if (type & TypesMask) {
494 const auto fileType = file->type(subfilePath);
495
496 if (fileType == DDciFile::Directory) {
497 flags |= DirectoryType;
498 } else if (fileType == DDciFile::File) {
499 flags |= FileType;
500 } else if (fileType == DDciFile::Symlink) {
501 flags |= LinkType;
502 }
503 }
504
505 if ((type & FlagsMask)) {
506 if (file->exists(subfilePath))
507 flags |= ExistsFlag;
508
509 if (subfilePath == QLatin1Char('/'))
510 flags |= RootFlag;
511 }
512
513 if ((type & PermsMask) && file->exists(subfilePath)) {
514 flags |= static_cast<FileFlags>(static_cast<int>(QFileInfo(dciFilePath).permissions()));
515 }
516
517 return flags;
518 }
519
520 QString DDciFileEngine::fileName(QAbstractFileEngine::FileName file) const
521 {
522 switch (file) {
523 case AbsoluteName:
524 case CanonicalName:
525 case DefaultName:
526 return QDir::cleanPath(DCI_FILE_SCHEME + dciFilePath + subfilePath);
527 case AbsolutePathName:
528 return QDir::cleanPath(DCI_FILE_SCHEME + dciFilePath);
529 case BaseName:
530 return QFileInfo(subfilePath).baseName();
531 #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
532 case AbsoluteLinkTarget:
533 #else
534 case LinkName:
535 #endif
536 return this->file->type(subfilePath) == DDciFile::Symlink
537 ? this->file->symlinkTarget(subfilePath)
538 : QString();
539 default:
540 break;
541 }
542
543 return QString();
544 }
545
546 void DDciFileEngine::setFileName(const QString &fullPath)
547 {
548 // 销毁旧的内容
549 close();
550 file.reset(nullptr);
551 dciFilePath.clear();
552 subfilePath.clear();
553
554 const auto paths = resolvePath(fullPath, QString(), false);
555 if (paths.first.isEmpty()
556 || paths.second.isEmpty())
557 return;
558
559 dciFilePath = paths.first;
560 subfilePath = paths.second;
561 file = getDciFile(dciFilePath, QFile::exists(dciFilePath));
562 }
563
564 #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 1)
565 QDateTime DDciFileEngine::fileTime(QFile::FileTime time) const
566 {
567 return QFileInfo(dciFilePath).fileTime(time);
568 }
569 #else
570 QDateTime DDciFileEngine::fileTime(QAbstractFileEngine::FileTime time) const
571 {
572 return QFileInfo(dciFilePath).fileTime(static_cast<QFile::FileTime>(time));
573 }
574 #endif
575 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 1)
576 QAbstractFileEngine::IteratorUniquePtr DDciFileEngine::beginEntryList(const QString &path, QDirListing::IteratorFlags filters, const QStringList &filterNames)
577 #elif QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
578 QAbstractFileEngine::IteratorUniquePtr DDciFileEngine::beginEntryList(const QString &path, QDir::Filters filters, const QStringList &filterNames)
579 #else
580 DDciFileEngine::Iterator *DDciFileEngine::beginEntryList(QDir::Filters filters, const QStringList &filterNames)
581 #endif
582 {
583 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
584 Q_UNUSED(path);
585 return QAbstractFileEngine::IteratorUniquePtr(new DDciFileEngineIterator(filters, filterNames));
586 #else
587 return new DDciFileEngineIterator(filters, filterNames);
588 #endif
589 }
590
591 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
592 QAbstractFileEngine::IteratorUniquePtr DDciFileEngine::endEntryList()
593 #else
594 DDciFileEngine::Iterator *DDciFileEngine::endEntryList()
595 #endif
596 {
597 return nullptr;
598 }
599
600 qint64 DDciFileEngine::read(char *data, qint64 maxlen)
601 {
602 return fileBuffer->read(data, maxlen);
603 }
604
605 qint64 DDciFileEngine::write(const char *data, qint64 len)
606 {
607 return fileBuffer->write(data, len);
608 }
609
610 bool DDciFileEngine::extension(QAbstractFileEngine::Extension extension,
611 const QAbstractFileEngine::ExtensionOption *option,
612 QAbstractFileEngine::ExtensionReturn *output)
613 {
614 Q_UNUSED(option)
615 Q_UNUSED(output)
616 return extension == AtEndExtension && fileBuffer->atEnd();
617 }
618
619 bool DDciFileEngine::supportsExtension(QAbstractFileEngine::Extension extension) const
620 {
621 return extension == AtEndExtension;
622 }
623
624 bool DDciFileEngine::cloneTo(QAbstractFileEngine *target)
625 {
626 const QByteArray &data = file->dataRef(subfilePath);
627 return target->write(data.constData(), data.size()) == data.size();
628 }
629
630 bool DDciFileEngine::forceSave(bool writeFile) const
631 {
632 QFile file(dciFilePath);
633 if (!file.open(QIODevice::WriteOnly)) {
634 return false;
635 }
636
637 return flushToFile(&file, writeFile);
638 }
639
640 QPair<QString, QString> DDciFileEngine::resolvePath(const QString &fullPath,
641 const QString &realFilePath,
642 bool needRealFileExists)
643 {
644 if (!fullPath.startsWith(QStringLiteral(DCI_FILE_SCHEME) + realFilePath))
645 return {};
646
647 qCDebug(logFE(), "Resolve the path: \"%s\"", qPrintable(fullPath));
648 // 此路径来源于调用方,将其格式化为标准格式,尾部添加 "/" 以确保下文中得到的
649 // subfilePath 绝对不为空
650 QString formatFullPath = QDir::cleanPath(fullPath) + "/";
651 QString dciFilePath = realFilePath, subfilePath;
652 const int schemeLength = qstrlen(DCI_FILE_SCHEME);
653 const int suffixLength = qstrlen(DCI_FILE_SUFFIX);
654
655 if (dciFilePath.isEmpty()) {
656 // 尾部加 "/" 是确保 ".dci" 为一个文件的结尾
657 int dciSuffixIndex = formatFullPath.indexOf(DCI_FILE_SUFFIX "/", schemeLength);
658
659 while (dciSuffixIndex > 0) {
660 dciSuffixIndex += suffixLength;
661 dciFilePath = formatFullPath.mid(schemeLength, dciSuffixIndex - schemeLength);
662 // 查找一个有效的后缀名是 ".dci" 的文件
663 if (needRealFileExists) {
664 if (QFileInfo(dciFilePath).isFile())
665 break;
666 } else {
667 QFileInfo info(dciFilePath);
668 // 不存在的文件允许被新建
669 if (!info.exists() && !info.isSymLink())
670 break;
671 }
672
673 dciSuffixIndex = dciFilePath.indexOf(DCI_FILE_SUFFIX, dciSuffixIndex + 1);
674 }
675 } else {
676 qCDebug(logFE(), "The base file path of user is: \"%s\"", qPrintable(realFilePath));
677 }
678
679 // 未找到有效的 dci 文件
680 if (dciFilePath.isEmpty())
681 return {};
682
683 subfilePath = QDir::cleanPath(formatFullPath.mid(schemeLength + dciFilePath.length()));
684 qCDebug(logFE(), "The DCI file path is: \"%s\", the subfile path is: \"%s\"",
685 qPrintable(dciFilePath), qPrintable(subfilePath));
686 Q_ASSERT(!subfilePath.isEmpty());
687
688 return qMakePair(dciFilePath, subfilePath);
689 }
690
691 DCORE_END_NAMESPACE