Debian Codegraph @

src/item_model.cpp

raw symbols SCIP
1 #include "item_model.h"
2 #include "icon_cache.h"
3 #include "utils.h"
4 #include <algorithm>
5
6 namespace {
7 static void advanceSpinner(QString &text) {
8 int spinnerPos = (int)((size_t)text.length() - 2);
9 QChar current = text[spinnerPos];
10 static const QChar spinner[] = {'-', '\\', '|', '/'};
11 size_t spinnerCount = sizeof(spinner) / sizeof(*spinner);
12 const QChar *found = std::find(spinner, spinner + spinnerCount, current);
13 size_t idx = found - spinner;
14 size_t next = idx == spinnerCount - 1 ? 0 : idx + 1;
15 text[spinnerPos] = spinner[next];
16 }
17
18 QString getNiceSize(quint64 size) {
19 static const char prefix[] = " KMGTPE";
20 for (int i = sizeof(prefix) - 2; i >= 0; i--) {
21 quint64 base = quint64(1) << (i * 10);
22 if (size >= 10 * base) {
23 return QString("%1 %2").arg(size / base).arg(QChar(prefix[i])).trimmed();
24 }
25 }
26 return "0";
27 }
28 } // namespace
29
30 class ItemSorter {
31 public:
32 inline ItemSorter(int column, Qt::SortOrder order)
33 : mColumn(column), mOrder(order) {
34 mCompare.setNumericMode(true);
35 }
36
37 bool operator()(const Item *a, const Item *b) const {
38 switch (mColumn) {
39 case 0:
40 if (a->isFolder != b->isFolder) {
41 return a->isFolder;
42 }
43 return mOrder == Qt::AscendingOrder
44 ? mCompare.compare(a->name, b->name) < 0
45 : mCompare.compare(b->name, a->name) < 0;
46
47 case 1:
48 if (a->isFolder != b->isFolder) {
49 return a->isFolder;
50 }
51 if (a->size == b->size) {
52 return mOrder == Qt::AscendingOrder
53 ? mCompare.compare(a->name, b->name) < 0
54 : mCompare.compare(b->name, a->name) < 0;
55 }
56 return mOrder == Qt::AscendingOrder ? a->size < b->size
57 : b->size < a->size;
58
59 case 2:
60 if (a->isFolder != b->isFolder) {
61 return a->isFolder;
62 }
63 if (a->modified == b->modified) {
64 return mOrder == Qt::AscendingOrder
65 ? mCompare.compare(a->name, b->name) < 0
66 : mCompare.compare(b->name, a->name) < 0;
67 }
68 return mOrder == Qt::AscendingOrder ? a->modified < b->modified
69 : b->modified < a->modified;
70 }
71 Q_ASSERT(false);
72 return false;
73 }
74
75 private:
76 QCollator mCompare;
77 int mColumn;
78 Qt::SortOrder mOrder;
79 };
80
81 ItemModel::ItemModel(IconCache *icons, const QString &remote, QObject *parent)
82 : QAbstractItemModel(parent), mRemote(remote),
83 mFixedFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)),
84 mRegExpFolder(
85 R"(^[\d-]+ (\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) \s*[\d-]+ (.+)$)"),
86 mRegExpFile(R"(^(\d+) (\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\.\d+ (.+)$)") {
87 QStyle *style = qApp->style();
88 mDriveIcon = style->standardIcon(QStyle::SP_DriveNetIcon);
89 mFolderIcon = style->standardIcon(QStyle::SP_DirIcon);
90 mFileIcon = style->standardIcon(QStyle::SP_FileIcon);
91
92 auto settings = GetSettings();
93 mFolderIcons = settings->value("Settings/showFolderIcons", true).toBool();
94 mFileIcons = settings->value("Settings/showFileIcons", true).toBool();
95
96 mRoot = new Item();
97 mRoot->isFolder = true;
98 mRoot->state = Item::Ready;
99
100 QObject::connect(this, &ItemModel::getIcon, icons, &IconCache::getIcon);
101 QObject::connect(
102 icons, &IconCache::iconReady, this,
103 [=](Item *item, const QPersistentModelIndex &parent, const QIcon &icon) {
104 item->state = Item::Ready;
105 QString ext = QFileInfo(item->name).suffix();
106 if (!mLoadedIcons.contains(ext)) {
107 mLoadedIcons.insert(ext, icon);
108 }
109
110 if (item->isDeleted) {
111 delete item;
112 return;
113 }
114
115 QModelIndex idx = index(item->num(), 0, parent);
116 emit dataChanged(idx, idx, QVector<int>{Qt::DecorationRole});
117 });
118 }
119
120 ItemModel::~ItemModel() { delete mRoot; }
121
122 const QDir &ItemModel::path(const QModelIndex &index) const {
123 return get(index)->path;
124 }
125
126 bool ItemModel::isLoading(const QModelIndex &index) const {
127 return get(index)->parent->isLoading();
128 }
129
130 void ItemModel::refresh(const QModelIndex &index) {
131 Item *item = get(index);
132 Item *folderItem = item->isFolder ? item : item->parent;
133 if (folderItem->isLoading()) {
134 return;
135 }
136 load(item->isFolder ? index : index.parent(), folderItem);
137 }
138
139 void ItemModel::rename(const QModelIndex &index, const QString &name) {
140 Item *item = get(index);
141 item->name = name;
142 item->path.setPath(item->parent->path.filePath(item->name));
143 emit dataChanged(index, index, QVector<int>{Qt::DisplayRole});
144 }
145
146 bool ItemModel::isTopLevel(const QModelIndex &index) const {
147 return get(index)->parent == mRoot;
148 }
149
150 bool ItemModel::isFolder(const QModelIndex &index) const {
151 return get(index)->isFolder;
152 }
153
154 QModelIndex ItemModel::addRoot(const QString &name, const QString &path) {
155 emit layoutAboutToBeChanged();
156
157 Item *item = new Item();
158 item->isFolder = true;
159 item->name = name;
160 item->path.setPath(path);
161 item->parent = mRoot;
162 mRoot->childs.append(item);
163
164 emit layoutChanged();
165
166 return createIndex(item->num(), 0, item);
167 }
168
169 QModelIndex ItemModel::index(int row, int column,
170 const QModelIndex &parent) const {
171 if (!hasIndex(row, column, parent)) {
172 return QModelIndex();
173 }
174
175 Item *item = get(parent);
176 return createIndex(row, column, item->childs[row]);
177 }
178
179 QModelIndex ItemModel::parent(const QModelIndex &index) const {
180 if (!index.isValid()) {
181 return QModelIndex();
182 }
183
184 Item *child = get(index);
185 if (child->parent == mRoot) {
186 return QModelIndex();
187 }
188
189 return createIndex(child->parent->num(), 0, child->parent);
190 }
191
192 bool ItemModel::hasChildren(const QModelIndex &parent) const {
193 Item *item = get(parent);
194 if (item->isFolder) {
195 if (item->state == Item::Ready) {
196 return !item->childs.isEmpty();
197 }
198 return true;
199 }
200 return false;
201 }
202
203 int ItemModel::rowCount(const QModelIndex &parent) const {
204 Item *item = get(parent);
205 if (item->isFolder) {
206 if (item->state == Item::Unknown) {
207 const_cast<ItemModel *>(this)->load(parent, item);
208 }
209 }
210 return item->childs.count();
211 }
212
213 int ItemModel::columnCount(const QModelIndex &parent) const {
214 Q_UNUSED(parent);
215 return 3;
216 }
217
218 void ItemModel::sort(int column, Qt::SortOrder order) {
219 mSortColumn = column;
220 mSortOrder = order;
221 sort(QModelIndex(), mRoot);
222 }
223
224 QVariant ItemModel::data(const QModelIndex &index, int role) const {
225 if (!index.isValid()) {
226 return QVariant();
227 }
228
229 const Item *item = get(index);
230
231 if (role == Qt::DecorationRole && index.column() == 0) {
232 if (item->state == Item::Special) {
233 return QIcon();
234 }
235
236 if (item->isFolder) {
237 if (mFolderIcons) {
238 return item->parent == mRoot ? mDriveIcon : mFolderIcon;
239 }
240 return QIcon();
241 }
242
243 if (mFileIcons) {
244 QString ext = QFileInfo(item->name).suffix();
245 auto it = mLoadedIcons.find(ext);
246 if (it == mLoadedIcons.end()) {
247 return mFileIcon;
248 }
249
250 return it.value();
251 }
252
253 return QIcon();
254 }
255
256 if (role == Qt::TextAlignmentRole) {
257 if (index.column() == 1) {
258 return Qt::AlignRight + Qt::AlignVCenter;
259 }
260 return QVariant();
261 }
262
263 if (role == Qt::DisplayRole) {
264 switch (index.column()) {
265 case 0:
266 return item->name;
267 case 1:
268 if (item->isFolder || item->state == Item::Special) {
269 return QString();
270 } else {
271 return getNiceSize(item->size);
272 }
273 case 2:
274 return item->modified;
275 }
276 Q_ASSERT(false);
277 }
278 return QVariant();
279 }
280
281 QVariant ItemModel::headerData(int section, Qt::Orientation orientation,
282 int role) const {
283 if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
284 switch (section) {
285 case 0:
286 return "Name";
287 case 1:
288 return "Size";
289 case 2:
290 return "Modified";
291 }
292 }
293
294 return QVariant();
295 }
296
297 bool ItemModel::removeRows(int row, int count, const QModelIndex &parent) {
298 if (!hasIndex(row, 0, parent)) {
299 return false;
300 }
301
302 Item *item = get(parent);
303 if (row + count > item->childs.count()) {
304 return false;
305 }
306
307 emit beginRemoveRows(parent, row, row + count - 1);
308
309 for (int i = row; i < row + count; i++) {
310 Item *node = item->childs.at(i);
311 if (node->isLoading() || node->state == Item::LoadingIcon) {
312 node->isDeleted = true;
313 } else {
314 delete node;
315 }
316 }
317 item->childs.remove(row, count);
318
319 emit endRemoveRows();
320
321 return true;
322 }
323
324 Qt::ItemFlags ItemModel::flags(const QModelIndex &index) const {
325 Qt::ItemFlags defaultFlags = QAbstractItemModel::flags(index);
326
327 if (!index.isValid()) {
328 return defaultFlags;
329 }
330
331 return Qt::ItemIsDropEnabled | defaultFlags;
332 }
333
334 bool ItemModel::canDropMimeData(const QMimeData *data, Qt::DropAction action,
335 int row, int column,
336 const QModelIndex &parent) const {
337 Q_UNUSED(row);
338 Q_UNUSED(column);
339 Q_UNUSED(parent);
340
341 if (action != Qt::CopyAction && action != Qt::MoveAction) {
342 return false;
343 }
344
345 if (!data->hasUrls()) {
346 return false;
347 }
348
349 auto urls = data->urls();
350 if (urls.count() == 1) {
351 return urls.front().isLocalFile();
352 }
353
354 return false;
355 }
356
357 bool ItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
358 int row, int column, const QModelIndex &parent) {
359 if (!canDropMimeData(data, action, row, column, parent)) {
360 return false;
361 }
362
363 QDir path = QDir(data->urls().front().toLocalFile());
364 Item *item = get(parent);
365
366 emit drop(path, item->isFolder ? parent : parent.parent());
367
368 return false;
369 }
370
371 Item *ItemModel::get(const QModelIndex &index) const {
372 return index.isValid() ? static_cast<Item *>(index.internalPointer()) : mRoot;
373 }
374
375 void ItemModel::load(const QPersistentModelIndex &parentIndex, Item *parent) {
376 auto lsd = new QProcess(this);
377 auto lsl = new QProcess(this);
378
379 auto cache = new QVector<Item *>();
380
381 Item *loading = new Item();
382 loading->state = Item::Special;
383 loading->name = "... loading [-]";
384 loading->parent = parent;
385
386 QTimer *timer = new QTimer(this);
387
388 QObject::connect(timer, &QTimer::timeout, this, [=]() {
389 advanceSpinner(loading->name);
390 auto loadingIndex = createIndex(loading->num(), 0, loading);
391 emit dataChanged(loadingIndex, loadingIndex, QVector<int>{Qt::DisplayRole});
392 });
393
394 auto rcloneFinished = [=]() {
395 sender()->deleteLater();
396
397 parent->state =
398 parent->state == Item::Loading1 ? Item::Loading2 : Item::Ready;
399 if (parent->state != Item::Ready) {
400 return;
401 }
402
403 timer->stop();
404 timer->deleteLater();
405
406 if (parent->isDeleted) {
407 qDeleteAll(*cache);
408 delete cache;
409 delete parent;
410 return;
411 }
412
413 QHash<QString, int> existing;
414 for (int i = 0; i < parent->childs.count(); i++) {
415 if (parent->childs[i] != loading) {
416 existing.insert(parent->childs[i]->name, i);
417 }
418 }
419
420 QVector<Item *> todo;
421
422 bool modified = false;
423 for (auto &item : *cache) {
424 auto it = existing.find(item->name);
425 if (it == existing.end()) {
426 item->path.setPath(parent->path.filePath(item->name));
427 if (!item->isFolder && mFileIcons) {
428 QString ext = QFileInfo(item->name).suffix();
429 if (!mLoadedIcons.contains(ext)) {
430 item->state = Item::LoadingIcon;
431 emit getIcon(item, parentIndex);
432 }
433 }
434 todo.append(item);
435 item = nullptr;
436 } else {
437 Item *old = parent->childs[it.value()];
438 if (old->isFolder != item->isFolder ||
439 old->modified != item->modified || old->size != item->size) {
440 old->state = Item::Unknown;
441 old->isFolder = item->isFolder;
442 old->modified = item->modified;
443 old->size = item->size;
444 modified = true;
445 emit dataChanged(createIndex(it.value(), 0, parent),
446 createIndex(it.value(), 2, parent),
447 QVector<int>{Qt::DisplayRole});
448 }
449 existing.erase(it);
450 }
451 }
452
453 qDeleteAll(*cache);
454 delete cache;
455
456 for (int i = 0; i < parent->childs.count(); i++) {
457 if (parent->childs[i] == loading ||
458 existing.contains(parent->childs[i]->name)) {
459 emit beginRemoveRows(parentIndex, i, i);
460 delete parent->childs.takeAt(i);
461 emit endRemoveRows();
462 i--;
463 }
464 }
465
466 if (!todo.isEmpty()) {
467 modified = true;
468 emit beginInsertRows(parentIndex, parent->childs.count(),
469 parent->childs.count() + todo.count() - 1);
470 parent->childs += todo;
471 emit endInsertRows();
472 }
473
474 if (modified) {
475 sort(parentIndex, parent);
476 }
477 };
478
479 QObject::connect(lsd,
480 static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(
481 &QProcess::finished),
482 this, rcloneFinished);
483 QObject::connect(lsl,
484 static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(
485 &QProcess::finished),
486 this, rcloneFinished);
487
488 QObject::connect(lsd, &QProcess::readyRead, this, [=]() {
489 while (lsd->canReadLine()) {
490 if (mRegExpFolder.exactMatch(lsd->readLine().trimmed())) {
491 QStringList cap = mRegExpFolder.capturedTexts();
492
493 Item *child = new Item();
494 child->isFolder = true;
495 child->parent = parent;
496 child->name = cap[2];
497 child->modified = cap[1];
498
499 cache->append(child);
500 }
501 }
502 });
503
504 QObject::connect(lsl, &QProcess::readyRead, this, [=]() {
505 while (lsl->canReadLine()) {
506 if (mRegExpFile.exactMatch(lsl->readLine().trimmed())) {
507 QStringList cap = mRegExpFile.capturedTexts();
508
509 Item *child = new Item();
510 child->parent = parent;
511 child->name = cap[3];
512 child->modified = cap[2];
513 child->size = cap[1].toULongLong();
514
515 cache->append(child);
516 }
517 }
518 });
519
520 parent->state = Item::Loading1;
521
522 emit beginInsertRows(parentIndex, 0, 0);
523 parent->childs.prepend(loading);
524 emit endInsertRows();
525
526 timer->start(100);
527 UseRclonePassword(lsd);
528 UseRclonePassword(lsl);
529
530 lsd->start(GetRclone(),
531 QStringList() << "lsd" << GetRcloneConf() << GetDriveSharedWithMe()
532 << GetShowHidden() << GetDefaultRcloneOptionsList()
533 << mRemote + ":" + parent->path.path(),
534 QIODevice::ReadOnly);
535 lsl->start(GetRclone(),
536 QStringList() << "lsl" << GetRcloneConf() << GetDriveSharedWithMe()
537 << GetShowHidden() << "--max-depth"
538 << "1" << GetDefaultRcloneOptionsList()
539 << mRemote + ":" + parent->path.path(),
540 QIODevice::ReadOnly);
541 }
542
543 void ItemModel::sortRecursive(Item *item, const ItemSorter &sorter) {
544 std::sort(item->childs.begin(), item->childs.end(), sorter);
545
546 for (auto child : item->childs) {
547 sortRecursive(child, sorter);
548 }
549 }
550
551 void ItemModel::sort(const QModelIndex &parent, Item *item) {
552 if (item->childs.isEmpty()) {
553 return;
554 }
555
556 QList<QPersistentModelIndex> parents;
557 parents << parent;
558 emit layoutAboutToBeChanged(parents, QAbstractItemModel::VerticalSortHint);
559
560 QModelIndexList oldList = persistentIndexList();
561 QVector<QPair<Item *, int>> oldNodes;
562 oldNodes.reserve(oldList.count());
563 for (const auto &index : oldList) {
564 oldNodes.append(qMakePair(get(index), index.column()));
565 }
566
567 ItemSorter sorter(mSortColumn, mSortOrder);
568 sortRecursive(item, sorter);
569
570 QModelIndexList newList;
571 newList.reserve(oldNodes.size());
572 for (const auto &node : oldNodes) {
573 Item *child = node.first;
574 int column = node.second;
575 int row = child->num();
576 newList.append(createIndex(row, column, child));
577 }
578
579 changePersistentIndexList(oldList, newList);
580
581 emit layoutChanged(parents, QAbstractItemModel::VerticalSortHint);
582 }