summaryrefslogtreecommitdiffstats
path: root/src/assistant/assistant/bookmarkmodel.cpp
blob: 2acb1ed3400352edc502a3d8f970502b48aa7857 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "bookmarkmodel.h"
#include "bookmarkitem.h"

#include <QtCore/QIODevice>
#include <QtCore/QMimeData>
#include <QtCore/QStack>

#include <QtWidgets/QApplication>
#include <QtWidgets/QStyle>
#include <QtWidgets/QTreeView>

using namespace Qt::StringLiterals;

const quint32 VERSION = 0xe53798;
const QLatin1StringView MIMETYPE("application/bookmarks.assistant");

BookmarkModel::BookmarkModel()
    : QAbstractItemModel()
    , m_folder(false)
    , m_editable(false)
    , rootItem(nullptr)
{
}

BookmarkModel::~BookmarkModel()
{
    delete rootItem;
}

QByteArray
BookmarkModel::bookmarks() const
{
    QByteArray ba;
    QDataStream stream(&ba, QIODevice::WriteOnly);
    stream << qint32(VERSION);

    const QModelIndex &root = index(0,0, QModelIndex()).parent();
    for (int i = 0; i < rowCount(root); ++i)
        collectItems(index(i, 0, root), 0, &stream);

    return ba;
}

void
BookmarkModel::setBookmarks(const QByteArray &bookmarks)
{
    beginResetModel();

    delete rootItem;
    folderIcon = QApplication::style()->standardIcon(QStyle::SP_DirClosedIcon);
    bookmarkIcon = QIcon(":/qt-project.org/assistant/images/bookmark.png"_L1);

    rootItem = new BookmarkItem(DataVector() << tr("Name") << tr("Address")
        << true);

    QStack<BookmarkItem*> parents;
    QDataStream stream(bookmarks);

    quint32 version;
    stream >> version;
    if (version < VERSION) {
        stream.device()->seek(0);
        BookmarkItem *toolbar =
                new BookmarkItem(DataVector() << tr("Bookmarks Toolbar") << "Folder"_L1 << true);
        rootItem->addChild(toolbar);

        BookmarkItem *menu =
                new BookmarkItem(DataVector() << tr("Bookmarks Menu") << "Folder"_L1 << true);
        rootItem->addChild(menu);
        parents.push(menu);
    } else {
        parents.push(rootItem);
    }

    qint32 depth;
    bool expanded;
    QString name, url;
    while (!stream.atEnd()) {
        stream >> depth >> name >> url >> expanded;
        while ((parents.size() - 1) != depth)
            parents.pop();

        BookmarkItem *item = new BookmarkItem(DataVector() << name << url << expanded);
        if (url == "Folder"_L1) {
            parents.top()->addChild(item);
            parents.push(item);
        } else {
            parents.top()->addChild(item);
        }
    }

    cache.clear();
    setupCache(index(0,0, QModelIndex().parent()));
    endResetModel();
}

void
BookmarkModel::setItemsEditable(bool editable)
{
    m_editable = editable;
}

void
BookmarkModel::expandFoldersIfNeeeded(QTreeView *treeView)
{
    for (QModelIndex index : std::as_const(cache))
        treeView->setExpanded(index, index.data(UserRoleExpanded).toBool());
}

QModelIndex
BookmarkModel::addItem(const QModelIndex &parent, bool isFolder)
{
    m_folder = isFolder;
    QModelIndex next;
    if (insertRow(rowCount(parent), parent))
        next = index(rowCount(parent) - 1, 0, parent);
    m_folder = false;

    return next;
}

bool
BookmarkModel::removeItem(const QModelIndex &index)
{
    if (!index.isValid())
        return false;

    QModelIndexList indexes;
    if (rowCount(index) > 0)
        indexes = collectItems(index);
    indexes.append(index);

    for (const QModelIndex &itemToRemove : std::as_const(indexes)) {
        if (!removeRow(itemToRemove.row(), itemToRemove.parent()))
            return false;
        cache.remove(itemFromIndex(itemToRemove));
    }
    return true;
}

int
BookmarkModel::rowCount(const QModelIndex &index) const
{
    if (BookmarkItem *item = itemFromIndex(index))
        return item->childCount();
    return 0;
}

int
BookmarkModel::columnCount(const QModelIndex &/*index*/) const
{
    return 2;
}

QModelIndex
BookmarkModel::parent(const QModelIndex &index) const
{
     if (!index.isValid())
         return QModelIndex();

     if (BookmarkItem *childItem = itemFromIndex(index)) {
         if (BookmarkItem *parent = childItem->parent()) {
             if (parent != rootItem)
                 return createIndex(parent->childNumber(), 0, parent);
         }
     }
     return QModelIndex();
}

QModelIndex
BookmarkModel::index(int row, int column, const QModelIndex &index) const
{
    if (index.isValid() && (index.column() != 0 && index.column() != 1))
         return QModelIndex();

    if (BookmarkItem *parent = itemFromIndex(index)) {
        if (BookmarkItem *childItem = parent->child(row))
            return createIndex(row, column, childItem);
    }
    return QModelIndex();
}

Qt::DropActions
BookmarkModel::supportedDropActions () const
{
    return /* Qt::CopyAction | */Qt::MoveAction;
}

Qt::ItemFlags
BookmarkModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    if (m_editable)
        defaultFlags |= Qt::ItemIsEditable;

    if (itemFromIndex(index) && index.data(UserRoleFolder).toBool()) {
        if (index.column() > 0)
            return defaultFlags &~ Qt::ItemIsEditable;
        return defaultFlags | Qt::ItemIsDropEnabled;
    }

    return defaultFlags | Qt::ItemIsDragEnabled;
}

QVariant
BookmarkModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        if (BookmarkItem *item = itemFromIndex(index)) {
            switch (role) {
                case Qt::EditRole:
                case Qt::DisplayRole:
                    if (index.data(UserRoleFolder).toBool() && index.column() == 1)
                        return QString();
                    return item->data(index.column());

                case Qt::DecorationRole:
                    if (index.column() == 0)
                        return index.data(UserRoleFolder).toBool()
                            ? folderIcon : bookmarkIcon;
                    break;

                default:
                    return item->data(role);
            }
        }
    }
    return QVariant();
}

void BookmarkModel::setData(const QModelIndex &index, const DataVector &data)
{
    if (BookmarkItem *item = itemFromIndex(index)) {
        item->setData(data);
        emit dataChanged(index, index);
    }
}

bool
BookmarkModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    bool result = false;
    if (role != Qt::EditRole && role != UserRoleExpanded)
        return result;

    if (BookmarkItem *item = itemFromIndex(index)) {
        if (role == Qt::EditRole) {
            const bool isFolder = index.data(UserRoleFolder).toBool();
            if (!isFolder || (isFolder && index.column() == 0))
                result = item->setData(index.column(), value);
        } else if (role == UserRoleExpanded) {
            result = item->setData(UserRoleExpanded, value);
        }
    }

    if (result)
        emit dataChanged(index, index);
    return result;
}

QVariant
BookmarkModel::headerData(int section, Qt::Orientation orientation,
    int role) const
{
     if (rootItem && orientation == Qt::Horizontal && role == Qt::DisplayRole)
         return rootItem->data(section);
     return QVariant();
}

QModelIndex
BookmarkModel::indexFromItem(BookmarkItem *item) const
{
    return cache.value(item, QModelIndex());
}

BookmarkItem*
BookmarkModel::itemFromIndex(const QModelIndex &index) const
{
    if (index.isValid())
         return static_cast<BookmarkItem*>(index.internalPointer());
     return rootItem;
}

QList<QPersistentModelIndex>
BookmarkModel::indexListFor(const QString &label) const
{
    QList<QPersistentModelIndex> hits;
    const QModelIndexList &list = collectItems(QModelIndex());
    for (const QModelIndex &index : list) {
        if (index.data().toString().contains(label, Qt::CaseInsensitive))
            hits.prepend(index);    // list is reverse sorted
    }
    return hits;
}

bool
BookmarkModel::insertRows(int position, int rows, const QModelIndex &parent)
{
    if (parent.isValid() && !parent.data(UserRoleFolder).toBool())
        return false;

    bool success = false;
    if (BookmarkItem *parentItem = itemFromIndex(parent)) {
        beginInsertRows(parent, position, position + rows - 1);
        success = parentItem->insertChildren(m_folder, position, rows);
        if (success) {
            const QModelIndex &current = index(position, 0, parent);
            cache.insert(itemFromIndex(current), current);
        }
        endInsertRows();
    }
    return success;
}

bool
BookmarkModel::removeRows(int position, int rows, const QModelIndex &index)
{
    bool success = false;
    if (BookmarkItem *parent = itemFromIndex(index)) {
        beginRemoveRows(index, position, position + rows - 1);
        success = parent->removeChildren(position, rows);
        endRemoveRows();
    }
    return success;
}

QStringList
BookmarkModel::mimeTypes() const
{
    return QStringList() << MIMETYPE;
}

QMimeData*
BookmarkModel::mimeData(const QModelIndexList &indexes) const
{
    if (indexes.isEmpty())
        return nullptr;

    QByteArray data;
    QDataStream stream(&data, QIODevice::WriteOnly);

    for (const QModelIndex &index : indexes) {
        if (index.column() == 0)
            collectItems(index, 0, &stream);
    }

    QMimeData *mimeData = new QMimeData();
    mimeData->setData(MIMETYPE, data);
    return mimeData;
}

bool
BookmarkModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
    int row, int column, const QModelIndex &parent)
{
    if (action == Qt::IgnoreAction)
        return true;

    if (!data->hasFormat(MIMETYPE) || column > 0)
        return false;

    QByteArray ba = data->data(MIMETYPE);
    QDataStream stream(&ba, QIODevice::ReadOnly);
    while (stream.atEnd())
        return false;

    qint32 depth;
    bool expanded;
    QString name, url;
    while (!stream.atEnd()) {
        stream >> depth >> name >> url >> expanded;
        if (insertRow(qMax(0, row), parent)) {
            const QModelIndex &current = index(qMax(0, row), 0, parent);
            if (current.isValid()) {
                BookmarkItem* item = itemFromIndex(current);
                item->setData(DataVector() << name << url << expanded);
            }
        }
    }
    return true;
}

void
BookmarkModel::setupCache(const QModelIndex &parent)
{
    const QModelIndexList &list = collectItems(parent);
    for (const QModelIndex &index : list)
        cache.insert(itemFromIndex(index), index);
}

QModelIndexList
BookmarkModel::collectItems(const QModelIndex &parent) const
{
    QModelIndexList list;
    for (int i = rowCount(parent) - 1; i >= 0 ; --i) {
        const QModelIndex &next = index(i, 0, parent);
        if (data(next, UserRoleFolder).toBool())
            list += collectItems(next);
        list.append(next);
    }
    return list;
}

void
BookmarkModel::collectItems(const QModelIndex &parent, qint32 depth,
    QDataStream *stream) const
{
    if (parent.isValid()) {
        *stream << depth;
        *stream << parent.data().toString();
        *stream << parent.data(UserRoleUrl).toString();
        *stream << parent.data(UserRoleExpanded).toBool();

        for (int i = 0; i < rowCount(parent); ++i) {
            if (parent.data(UserRoleFolder).toBool())
                collectItems(index(i, 0 , parent), depth + 1, stream);
        }
    }
}