keylistmodel.cpp 39 KB
Newer Older
1
2
3
/* -*- mode: c++; c-basic-offset:4 -*-
    models/keylistmodel.cpp

4
    This file is part of libkleopatra, the KDE keymanagement library
5
    SPDX-FileCopyrightText: 2007 Klarälvdalens Datakonsult AB
6
7
    SPDX-FileCopyrightText: 2021 g10 Code GmbH
    SPDX-FileContributor: Ingo Klöcker <dev@ingo-kloecker.de>
8

9
    SPDX-License-Identifier: GPL-2.0-or-later
10
11
12
*/

#include "keylistmodel.h"
13

14
#include "keycache.h"
15
#include "keylist.h"
16
#include "kleo/keygroup.h"
17
18
19
20
21
22
#include "kleo/predicates.h"
#include "kleo/keyfiltermanager.h"
#include "kleo/keyfilter.h"
#include "utils/formatting.h"

#ifdef KLEO_MODEL_TEST
23
# include <QAbstractItemModelTester>
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#endif

#include <Libkleo/KeyFilterManager>
#include <Libkleo/KeyFilter>

#include <KLocalizedString>

#include <QFont>
#include <QColor>
#include <QHash>
#include <QIcon>
#include <QDate>
#include <gpgme++/key.h>

#ifndef Q_MOC_RUN // QTBUG-22829
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/adjacency_list.hpp>
#endif

#include <algorithm>
#include <map>
#include <set>
#include <iterator>

48
49
50
51
52
#include <gpgme++/gpgmepp_version.h>
#if GPGMEPP_VERSION >= 0x10E00 // 1.14.0
# define GPGME_HAS_REMARKS
#endif

53
54
using namespace GpgME;
using namespace Kleo;
55
using namespace Kleo::KeyList;
56

57
Q_DECLARE_METATYPE(GpgME::Key)
58
Q_DECLARE_METATYPE(KeyGroup)
59
60
61

class AbstractKeyListModel::Private
{
62
63
64
65
66
67
    AbstractKeyListModel *const q;
public:
    explicit Private(AbstractKeyListModel *qq);

    void updateFromKeyCache();

68
public:
Laurent Montel's avatar
Laurent Montel committed
69
    int m_toolTipOptions = Formatting::Validity;
70
    mutable QHash<const char *, QVariant> prettyEMailCache;
71
    mutable QHash<const char *, QVariant> remarksCache;
Laurent Montel's avatar
Laurent Montel committed
72
    bool m_useKeyCache = false;
73
    KeyList::Options m_keyListOptions = AllKeys;
74
    std::vector<GpgME::Key> m_remarkKeys;
75
};
76
77
78
79
80
81
82
83
84

AbstractKeyListModel::Private::Private(Kleo::AbstractKeyListModel *qq)
    : q(qq)
{
}

void AbstractKeyListModel::Private::updateFromKeyCache()
{
    if (m_useKeyCache) {
85
        q->setKeys(m_keyListOptions == SecretKeysOnly ? KeyCache::instance()->secretKeys() : KeyCache::instance()->keys());
86
87
88
        if (m_keyListOptions == IncludeGroups) {
            q->setGroups(KeyCache::instance()->groups());
        }
89
90
91
    }
}

92
AbstractKeyListModel::AbstractKeyListModel(QObject *p)
93
    : QAbstractItemModel(p), KeyListModelInterface(), d(new Private(this))
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
{

}

AbstractKeyListModel::~AbstractKeyListModel() {}

void AbstractKeyListModel::setToolTipOptions(int opts)
{
    d->m_toolTipOptions = opts;
}

int AbstractKeyListModel::toolTipOptions() const
{
    return d->m_toolTipOptions;
}

110
111
112
113
114
115
116
117
118
119
void AbstractKeyListModel::setRemarkKeys(const std::vector<GpgME::Key> &keys)
{
    d->m_remarkKeys = keys;
}

std::vector<GpgME::Key> AbstractKeyListModel::remarkKeys() const
{
    return d->m_remarkKeys;
}

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
Key AbstractKeyListModel::key(const QModelIndex &idx) const
{
    if (idx.isValid()) {
        return doMapToKey(idx);
    } else {
        return Key::null;
    }
}

std::vector<Key> AbstractKeyListModel::keys(const QList<QModelIndex> &indexes) const
{
    std::vector<Key> result;
    result.reserve(indexes.size());
    std::transform(indexes.begin(), indexes.end(),
                   std::back_inserter(result),
135
136
137
                   [this](const QModelIndex &idx) {
                       return this->key(idx);
                   });
138
    result.erase(std::remove_if(result.begin(), result.end(), std::mem_fn(&GpgME::Key::isNull)), result.end());
139
    _detail::remove_duplicates_by_fpr(result);
140
141
142
    return result;
}

143
144
145
146
147
148
149
150
151
KeyGroup AbstractKeyListModel::group(const QModelIndex &idx) const
{
    if (idx.isValid()) {
        return doMapToGroup(idx);
    } else {
        return KeyGroup();
    }
}

152
153
154
155
156
QModelIndex AbstractKeyListModel::index(const Key &key) const
{
    return index(key, 0);
}

157
158
159
QModelIndex AbstractKeyListModel::index(const Key &key, int col) const
{
    if (key.isNull() || col < 0 || col >= NumColumns) {
Laurent Montel's avatar
Laurent Montel committed
160
        return {};
161
162
163
164
165
166
167
168
    } else {
        return doMapFromKey(key, col);
    }
}

QList<QModelIndex> AbstractKeyListModel::indexes(const std::vector<Key> &keys) const
{
    QList<QModelIndex> result;
169
    result.reserve(keys.size());
170
171
    std::transform(keys.begin(), keys.end(),
                   std::back_inserter(result),
172
173
174
                   [this](const Key &key) {
                       return this->index(key);
                   });
175
176
177
    return result;
}

178
179
180
181
182
183
184
185
186
187
188
189
190
191
QModelIndex AbstractKeyListModel::index(const KeyGroup &group) const
{
    return index(group, 0);
}

QModelIndex AbstractKeyListModel::index(const KeyGroup &group, int col) const
{
    if (group.isNull() || col < 0 || col >= NumColumns) {
        return {};
    } else {
        return doMapFromGroup(group, col);
    }
}

192
193
void AbstractKeyListModel::setKeys(const std::vector<Key> &keys)
{
194
    clear(Keys);
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    addKeys(keys);
}

QModelIndex AbstractKeyListModel::addKey(const Key &key)
{
    const std::vector<Key> vec(1, key);
    const QList<QModelIndex> l = doAddKeys(vec);
    return l.empty() ? QModelIndex() : l.front();
}

void AbstractKeyListModel::removeKey(const Key &key)
{
    if (key.isNull()) {
        return;
    }
    doRemoveKey(key);
    d->prettyEMailCache.remove(key.primaryFingerprint());
212
    d->remarksCache.remove(key.primaryFingerprint());
213
214
215
216
217
218
219
220
}

QList<QModelIndex> AbstractKeyListModel::addKeys(const std::vector<Key> &keys)
{
    std::vector<Key> sorted;
    sorted.reserve(keys.size());
    std::remove_copy_if(keys.begin(), keys.end(),
                        std::back_inserter(sorted),
221
                        std::mem_fn(&Key::isNull));
222
223
224
225
    std::sort(sorted.begin(), sorted.end(), _detail::ByFingerprint<std::less>());
    return doAddKeys(sorted);
}

Ingo Klöcker's avatar
Ingo Klöcker committed
226
227
228
229
230
231
void AbstractKeyListModel::setGroups(const std::vector<KeyGroup> &groups)
{
    clear(Groups);
    doSetGroups(groups);
}

232
void AbstractKeyListModel::clear(ItemTypes types)
233
234
{
    beginResetModel();
235
236
237
238
239
    doClear(types);
    if (types & Keys) {
        d->prettyEMailCache.clear();
        d->remarksCache.clear();
    }
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    endResetModel();
}

int AbstractKeyListModel::columnCount(const QModelIndex &) const
{
    return NumColumns;
}

QVariant AbstractKeyListModel::headerData(int section, Qt::Orientation o, int role) const
{
    if (o == Qt::Horizontal)
        if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::ToolTipRole)
            switch (section) {
            case PrettyName:       return i18n("Name");
            case PrettyEMail:      return i18n("E-Mail");
255
            case Validity:         return i18n("User-IDs");
256
257
            case ValidFrom:        return i18n("Valid From");
            case ValidUntil:       return i18n("Valid Until");
258
            case TechnicalDetails: return i18n("Protocol");
259
            case ShortKeyID:       return i18n("Key-ID");
260
            case KeyID:            return i18n("Key-ID");
261
262
263
264
265
266
            case Fingerprint:      return i18n("Fingerprint");
            case Issuer:           return i18n("Issuer");
            case SerialNumber:     return i18n("Serial Number");
            case Origin:           return i18n("Origin");
            case LastUpdate:       return i18n("Last Update");
            case OwnerTrust:       return i18n("Certification Trust");
267
            case Remarks:          return i18n("Tags");
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
            case NumColumns:;
            }
    return QVariant();
}

static QVariant returnIfValid(const QColor &t)
{
    if (t.isValid()) {
        return t;
    } else {
        return QVariant();
    }
}

static QVariant returnIfValid(const QIcon &t)
{
    if (!t.isNull()) {
        return t;
    } else {
        return QVariant();
    }
}

QVariant AbstractKeyListModel::data(const QModelIndex &index, int role) const
{
    const Key key = this->key(index);
294
295
    if (!key.isNull()) {
        return data(key, index.column(), role);
296
297
    }

298
299
300
301
    const KeyGroup group = this->group(index);
    if (!group.isNull()) {
        return data(group, index.column(), role);
    }
302

303
304
305
306
307
308
    return QVariant();
}

QVariant AbstractKeyListModel::data(const Key &key, int column, int role) const
{
   if (role == Qt::DisplayRole || role == Qt::EditRole) {
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        switch (column) {
        case PrettyName:
            return Formatting::prettyName(key);
        case PrettyEMail:
            if (const char *const fpr = key.primaryFingerprint()) {
                const QHash<const char *, QVariant>::const_iterator it = d->prettyEMailCache.constFind(fpr);
                if (it != d->prettyEMailCache.constEnd()) {
                    return *it;
                } else {
                    return d->prettyEMailCache[fpr] = Formatting::prettyEMail(key);
                }
            } else {
                return QVariant();
            }
323
324
        case Validity:
            return Formatting::complianceStringShort(key);
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        case ValidFrom:
            if (role == Qt::EditRole) {
                return Formatting::creationDate(key);
            } else {
                return Formatting::creationDateString(key);
            }
        case ValidUntil:
            if (role == Qt::EditRole) {
                return Formatting::expirationDate(key);
            } else {
                return Formatting::expirationDateString(key);
            }
        case TechnicalDetails:
            return Formatting::type(key);
        case ShortKeyID:
            return QString::fromLatin1(key.shortKeyID());
341
342
        case KeyID:
            return Formatting::prettyID(key.keyID());
343
344
        case Summary:
            return Formatting::summaryLine(key);
345
346
347
348
349
350
351
352
353
354
355
356
        case Fingerprint:
            return Formatting::prettyID(key.primaryFingerprint());
        case Issuer:
            return QString::fromUtf8(key.issuerName());
        case Origin:
            return Formatting::origin(key.origin());
        case LastUpdate:
            return Formatting::dateString(key.lastUpdate());
        case SerialNumber:
            return QString::fromUtf8(key.issuerSerial());
        case OwnerTrust:
            return Formatting::ownerTrustShort(key.ownerTrust());
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        case Remarks:
#ifdef GPGME_HAS_REMARKS
            {
                const char *const fpr = key.primaryFingerprint();
                if (fpr && key.protocol() == GpgME::OpenPGP && key.numUserIDs() &&
                        d->m_remarkKeys.size()) {
                    if (!(key.keyListMode() & GpgME::SignatureNotations)) {
                        return i18n("Loading...");
                    }
                    const QHash<const char *, QVariant>::const_iterator it = d->remarksCache.constFind(fpr);
                    if (it != d->remarksCache.constEnd()) {
                        return *it;
                    } else {
                        GpgME::Error err;
                        const auto remarks = key.userID(0).remarks(d->m_remarkKeys, err);
                        if (remarks.size() == 1) {
                            const auto remark = QString::fromStdString(remarks[0]);
                            return d->remarksCache[fpr] = remark;
                        } else {
                            QStringList remarkList;
Laurent Montel's avatar
Laurent Montel committed
377
                            remarkList.reserve(remarks.size());
378
379
380
381
382
383
384
385
386
387
388
389
390
                            for (const auto &rem: remarks) {
                                remarkList << QString::fromStdString(rem);
                            }
                            const auto remark = remarkList.join(QStringLiteral("; "));
                            return d->remarksCache[fpr] = remark;
                        }
                    }
                } else {
                    return QVariant();
                }
            }
#endif
            return QVariant();
391
392
393
394
395
396
        case NumColumns:
            break;
        }
    } else if (role == Qt::ToolTipRole) {
        return Formatting::toolTip(key, toolTipOptions());
    } else if (role == Qt::FontRole) {
397
        return KeyFilterManager::instance()->font(key, (column == ShortKeyID || column == KeyID || column == Fingerprint) ? QFont(QStringLiteral("monospace")) : QFont());
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    } else if (role == Qt::DecorationRole) {
        return column == Icon ? returnIfValid(KeyFilterManager::instance()->icon(key)) : QVariant();
    } else if (role == Qt::BackgroundRole) {
        return returnIfValid(KeyFilterManager::instance()->bgColor(key));
    } else if (role == Qt::ForegroundRole) {
        return returnIfValid(KeyFilterManager::instance()->fgColor(key));
    } else if (role == FingerprintRole) {
        return QString::fromLatin1(key.primaryFingerprint());
    } else if (role == KeyRole) {
        return QVariant::fromValue(key);
    }
    return QVariant();
}

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
QVariant AbstractKeyListModel::data(const KeyGroup &group, int column, int role) const
{
    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        switch (column) {
        case PrettyName:
            return group.name();
        case PrettyEMail:
            return QVariant();
        case Validity:
            return QString();
        case ValidFrom:
            return QString();
        case ValidUntil:
            return QString();
        case TechnicalDetails:
            return i18nc("a group of keys/certificates", "Group");
        case ShortKeyID:
            return QString();
        case KeyID:
            return QString();
        case Summary:
433
            return Formatting::summaryLine(group);  // used for filtering
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        case Fingerprint:
            return QString();
        case Issuer:
            return QString();
        case Origin:
            return QString();
        case LastUpdate:
            return QString();
        case SerialNumber:
            return QString();
        case OwnerTrust:
            return QString();
        case Remarks:
            return QVariant();
        case NumColumns:
            break;
        }
    } else if (role == Qt::ToolTipRole) {
        return QString();
    } else if (role == Qt::FontRole) {
        return QFont();
    } else if (role == Qt::DecorationRole) {
        return column == Icon ? QIcon::fromTheme("group") : QVariant();
    } else if (role == Qt::BackgroundRole) {
    } else if (role == Qt::ForegroundRole) {
    } else if (role == GroupRole) {
        return QVariant::fromValue(group);
    }
    return QVariant();
}

465
466
467
468
469
470
namespace
{
template <typename Base>
class TableModelMixin : public Base
{
public:
Laurent Montel's avatar
Laurent Montel committed
471
    explicit TableModelMixin(QObject *p = nullptr) : Base(p) {}
472
473
474
    ~TableModelMixin() {}

    using Base::index;
475
    QModelIndex index(int row, int column, const QModelIndex &pidx = QModelIndex()) const override
476
    {
Laurent Montel's avatar
Laurent Montel committed
477
        return this->hasIndex(row, column, pidx) ? this->createIndex(row, column, nullptr) : QModelIndex();
478
479
480
    }

private:
481
    QModelIndex parent(const QModelIndex &) const override
482
483
484
    {
        return QModelIndex();
    }
485
    bool hasChildren(const QModelIndex &pidx) const override
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    {
        return (pidx.model() == this || !pidx.isValid()) && this->rowCount(pidx) > 0 && this->columnCount(pidx) > 0;
    }
};

class FlatKeyListModel
#ifndef Q_MOC_RUN
    : public TableModelMixin<AbstractKeyListModel>
#else
    : public AbstractKeyListModel
#endif
{
    Q_OBJECT
public:
Laurent Montel's avatar
Laurent Montel committed
500
    explicit FlatKeyListModel(QObject *parent = nullptr);
Laurent Montel's avatar
Laurent Montel committed
501
    ~FlatKeyListModel() override;
502

503
    int rowCount(const QModelIndex &pidx) const override
504
    {
505
        return pidx.isValid() ? 0 : mKeysByFingerprint.size() + mGroups.size();
506
507
508
    }

private:
509
510
511
512
    Key doMapToKey(const QModelIndex &index) const override;
    QModelIndex doMapFromKey(const Key &key, int col) const override;
    QList<QModelIndex> doAddKeys(const std::vector<Key> &keys) override;
    void doRemoveKey(const Key &key) override;
513
514
515

    KeyGroup doMapToGroup(const QModelIndex &index) const override;
    QModelIndex doMapFromGroup(const KeyGroup &group, int column) const override;
Ingo Klöcker's avatar
Ingo Klöcker committed
516
    void doSetGroups(const std::vector<KeyGroup> &groups) override;
517

518
519
520
521
522
    void doClear(ItemTypes types) override
    {
        if (types & Keys) {
            mKeysByFingerprint.clear();
        }
523
524
525
        if (types & Groups) {
            mGroups.clear();
        }
526
527
528
529
    }

private:
    std::vector<Key> mKeysByFingerprint;
530
    std::vector<KeyGroup> mGroups;
531
532
533
534
535
536
};

class HierarchicalKeyListModel : public AbstractKeyListModel
{
    Q_OBJECT
public:
Laurent Montel's avatar
Laurent Montel committed
537
    explicit HierarchicalKeyListModel(QObject *parent = nullptr);
Laurent Montel's avatar
Laurent Montel committed
538
    ~HierarchicalKeyListModel() override;
539

540
    int rowCount(const QModelIndex &pidx) const override;
541
    using AbstractKeyListModel::index;
542
543
    QModelIndex index(int row, int col, const QModelIndex &pidx) const override;
    QModelIndex parent(const QModelIndex &idx) const override;
544

545
    bool hasChildren(const QModelIndex &pidx) const override
546
547
548
549
550
    {
        return rowCount(pidx) > 0;
    }

private:
551
552
553
554
    Key doMapToKey(const QModelIndex &index) const override;
    QModelIndex doMapFromKey(const Key &key, int col) const override;
    QList<QModelIndex> doAddKeys(const std::vector<Key> &keys) override;
    void doRemoveKey(const Key &key) override;
555
556
557

    KeyGroup doMapToGroup(const QModelIndex &index) const override;
    QModelIndex doMapFromGroup(const KeyGroup &group, int column) const override;
Ingo Klöcker's avatar
Ingo Klöcker committed
558
    void doSetGroups(const std::vector<KeyGroup> &groups) override;
559

560
561
562
563
564
565
566
567
    void doClear(ItemTypes types) override
    {
        if (types & Keys) {
            mTopLevels.clear();
            mKeysByFingerprint.clear();
            mKeysByExistingParent.clear();
            mKeysByNonExistingParent.clear();
        }
568
569
570
        if (types & Groups) {
            mGroups.clear();
        }
571
572
573
574
575
576
577
578
579
580
581
582
    }

private:
    void addTopLevelKey(const Key &key);
    void addKeyWithParent(const char *issuer_fpr, const Key &key);
    void addKeyWithoutParent(const char *issuer_fpr, const Key &key);

private:
    typedef std::map< std::string, std::vector<Key> > Map;
    std::vector<Key> mKeysByFingerprint; // all keys
    Map mKeysByExistingParent, mKeysByNonExistingParent; // parent->child map
    std::vector<Key> mTopLevels; // all roots + parent-less
583
    std::vector<KeyGroup> mGroups;
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
};

static const char *cleanChainID(const Key &key)
{
    if (key.isRoot()) {
        return "";
    }
    if (const char *chid = key.chainID()) {
        return chid;
    }
    return "";
}

}

FlatKeyListModel::FlatKeyListModel(QObject *p)
600
    : TableModelMixin<AbstractKeyListModel>(p)
601
602
603
604
605
606
607
{
}

FlatKeyListModel::~FlatKeyListModel() {}

Key FlatKeyListModel::doMapToKey(const QModelIndex &idx) const
{
Daniel Vrátil's avatar
Daniel Vrátil committed
608
    Q_ASSERT(idx.isValid());
609
610
611
612
613
614
615
616
617
    if (static_cast<unsigned>(idx.row()) < mKeysByFingerprint.size() && idx.column() < NumColumns) {
        return mKeysByFingerprint[ idx.row() ];
    } else {
        return Key::null;
    }
}

QModelIndex FlatKeyListModel::doMapFromKey(const Key &key, int col) const
{
Daniel Vrátil's avatar
Daniel Vrátil committed
618
    Q_ASSERT(!key.isNull());
619
620
621
622
    const std::vector<Key>::const_iterator it
        = std::lower_bound(mKeysByFingerprint.begin(), mKeysByFingerprint.end(),
                           key, _detail::ByFingerprint<std::less>());
    if (it == mKeysByFingerprint.end() || !_detail::ByFingerprint<std::equal_to>()(*it, key)) {
Laurent Montel's avatar
Laurent Montel committed
623
        return {};
624
625
626
627
628
629
630
    } else {
        return createIndex(it - mKeysByFingerprint.begin(), col);
    }
}

QList<QModelIndex> FlatKeyListModel::doAddKeys(const std::vector<Key> &keys)
{
Daniel Vrátil's avatar
Daniel Vrátil committed
631
    Q_ASSERT(std::is_sorted(keys.begin(), keys.end(), _detail::ByFingerprint<std::less>()));
632

633
634
635
636
    if (keys.empty()) {
        return QList<QModelIndex>();
    }

Laurent Montel's avatar
Laurent Montel committed
637
    for (auto it = keys.begin(), end = keys.end(); it != end; ++it) {
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672

        // find an insertion point:
        const std::vector<Key>::iterator pos = std::upper_bound(mKeysByFingerprint.begin(), mKeysByFingerprint.end(), *it, _detail::ByFingerprint<std::less>());
        const unsigned int idx = std::distance(mKeysByFingerprint.begin(), pos);

        if (idx > 0 && qstrcmp(mKeysByFingerprint[idx - 1].primaryFingerprint(), it->primaryFingerprint()) == 0) {
            // key existed before - replace with new one:
            mKeysByFingerprint[idx - 1] = *it;
            Q_EMIT dataChanged(createIndex(idx - 1, 0), createIndex(idx - 1, NumColumns - 1));
        } else {
            // new key - insert:
            beginInsertRows(QModelIndex(), idx, idx);
            mKeysByFingerprint.insert(pos, *it);
            endInsertRows();
        }
    }

    return indexes(keys);
}

void FlatKeyListModel::doRemoveKey(const Key &key)
{
    const std::vector<Key>::iterator it
        = qBinaryFind(mKeysByFingerprint.begin(), mKeysByFingerprint.end(),
                      key, _detail::ByFingerprint<std::less>());
    if (it == mKeysByFingerprint.end()) {
        return;
    }

    const unsigned int row = std::distance(mKeysByFingerprint.begin(), it);
    beginRemoveRows(QModelIndex(), row, row);
    mKeysByFingerprint.erase(it);
    endRemoveRows();
}

673
674
KeyGroup FlatKeyListModel::doMapToGroup(const QModelIndex &idx) const
{
675
676
677
678
679
680
681
682
    Q_ASSERT(idx.isValid());
    if (static_cast<unsigned>(idx.row()) >= mKeysByFingerprint.size()
            && static_cast<unsigned>(idx.row()) < mKeysByFingerprint.size() + mGroups.size()
            && idx.column() < NumColumns) {
        return mGroups[ idx.row() - mKeysByFingerprint.size() ];
    } else {
        return KeyGroup();
    }
683
684
685
686
}

QModelIndex FlatKeyListModel::doMapFromGroup(const KeyGroup &group, int column) const
{
687
688
689
690
691
692
693
694
    Q_ASSERT(!group.isNull());
    const QString name = group.name();
    const auto it = std::find_if(mGroups.begin(), mGroups.end(), [name](const KeyGroup &g) { return g.name() == name; });
    if (it == mGroups.end()) {
        return QModelIndex();
    } else {
        return createIndex(it - mGroups.begin() + mKeysByFingerprint.size(), column);
    }
695
696
}

Ingo Klöcker's avatar
Ingo Klöcker committed
697
698
void FlatKeyListModel::doSetGroups(const std::vector<KeyGroup> &groups)
{
699
700
701
702
703
704
    Q_ASSERT(mGroups.empty());  // ensure that groups have been cleared
    const int first = mKeysByFingerprint.size();
    const int last = first + groups.size() - 1;
    beginInsertRows(QModelIndex(), first, last);
    mGroups = groups;
    endInsertRows();
Ingo Klöcker's avatar
Ingo Klöcker committed
705
706
}

707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
HierarchicalKeyListModel::HierarchicalKeyListModel(QObject *p)
    : AbstractKeyListModel(p),
      mKeysByFingerprint(),
      mKeysByExistingParent(),
      mKeysByNonExistingParent(),
      mTopLevels()
{

}

HierarchicalKeyListModel::~HierarchicalKeyListModel() {}

int HierarchicalKeyListModel::rowCount(const QModelIndex &pidx) const
{

    // toplevel item:
    if (!pidx.isValid()) {
724
        return mTopLevels.size() + mGroups.size();
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    }

    if (pidx.column() != 0) {
        return 0;
    }

    // non-toplevel item - find the number of subjects for this issuer:
    const Key issuer = this->key(pidx);
    const char *const fpr = issuer.primaryFingerprint();
    if (!fpr || !*fpr) {
        return 0;
    }
    const Map::const_iterator it = mKeysByExistingParent.find(fpr);
    if (it == mKeysByExistingParent.end()) {
        return 0;
    }
    return it->second.size();
}

QModelIndex HierarchicalKeyListModel::index(int row, int col, const QModelIndex &pidx) const
{

    if (row < 0 || col < 0 || col >= NumColumns) {
Laurent Montel's avatar
Laurent Montel committed
748
        return {};
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    }

    // toplevel item:
    if (!pidx.isValid()) {
        if (static_cast<unsigned>(row) < mTopLevels.size()) {
            return index(mTopLevels[row], col);
        } else {
            return QModelIndex();
        }
    }

    // non-toplevel item - find the row'th subject of this key:
    const Key issuer = this->key(pidx);
    const char *const fpr = issuer.primaryFingerprint();
    if (!fpr || !*fpr) {
        return QModelIndex();
    }
    const Map::const_iterator it = mKeysByExistingParent.find(fpr);
    if (it == mKeysByExistingParent.end() || static_cast<unsigned>(row) >= it->second.size()) {
        return QModelIndex();
    }
    return index(it->second[row], col);
}

QModelIndex HierarchicalKeyListModel::parent(const QModelIndex &idx) const
{
    const Key key = this->key(idx);
    if (key.isNull() || key.isRoot()) {
Laurent Montel's avatar
Laurent Montel committed
777
        return {};
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
    }
    const std::vector<Key>::const_iterator it
        = qBinaryFind(mKeysByFingerprint.begin(), mKeysByFingerprint.end(),
                      cleanChainID(key), _detail::ByFingerprint<std::less>());
    return it != mKeysByFingerprint.end() ? index(*it) : QModelIndex();
}

Key HierarchicalKeyListModel::doMapToKey(const QModelIndex &idx) const
{

    if (!idx.isValid()) {
        return Key::null;
    }

    const char *const issuer_fpr = static_cast<const char *>(idx.internalPointer());
    if (!issuer_fpr || !*issuer_fpr) {
        // top-level:
        if (static_cast<unsigned>(idx.row()) >= mTopLevels.size()) {
            return Key::null;
        } else {
            return mTopLevels[idx.row()];
        }
    }

    // non-toplevel:
    const Map::const_iterator it
        = mKeysByExistingParent.find(issuer_fpr);
    if (it == mKeysByExistingParent.end() || static_cast<unsigned>(idx.row()) >= it->second.size()) {
        return Key::null;
    }
    return it->second[idx.row()];
}

QModelIndex HierarchicalKeyListModel::doMapFromKey(const Key &key, int col) const
{

    if (key.isNull()) {
Laurent Montel's avatar
Laurent Montel committed
815
        return {};
816
817
818
819
820
821
822
823
824
825
826
827
828
    }

    const char *issuer_fpr = cleanChainID(key);

    // we need to look in the toplevels list,...
    const std::vector<Key> *v = &mTopLevels;
    if (issuer_fpr && *issuer_fpr) {
        const std::map< std::string, std::vector<Key> >::const_iterator it
            = mKeysByExistingParent.find(issuer_fpr);
        // ...unless we find an existing parent:
        if (it != mKeysByExistingParent.end()) {
            v = &it->second;
        } else {
Laurent Montel's avatar
Laurent Montel committed
829
            issuer_fpr = nullptr;    // force internalPointer to zero for toplevels
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        }
    }

    const std::vector<Key>::const_iterator it
        = std::lower_bound(v->begin(), v->end(), key, _detail::ByFingerprint<std::less>());
    if (it == v->end() || !_detail::ByFingerprint<std::equal_to>()(*it, key)) {
        return QModelIndex();
    }

    const unsigned int row = std::distance(v->begin(), it);
    return createIndex(row, col, const_cast<char * /* thanks, Trolls :/ */ >(issuer_fpr));
}

void HierarchicalKeyListModel::addKeyWithParent(const char *issuer_fpr, const Key &key)
{

Daniel Vrátil's avatar
Daniel Vrátil committed
846
    Q_ASSERT(issuer_fpr); Q_ASSERT(*issuer_fpr); Q_ASSERT(!key.isNull());
847
848
849
850
851
852
853
854
855
856
857
858
859
860

    std::vector<Key> &subjects = mKeysByExistingParent[issuer_fpr];

    // find insertion point:
    const std::vector<Key>::iterator it = std::lower_bound(subjects.begin(), subjects.end(), key, _detail::ByFingerprint<std::less>());
    const int row = std::distance(subjects.begin(), it);

    if (it != subjects.end() && qstricmp(it->primaryFingerprint(), key.primaryFingerprint()) == 0) {
        // exists -> replace
        *it = key;
        Q_EMIT dataChanged(createIndex(row, 0, const_cast<char *>(issuer_fpr)), createIndex(row, NumColumns - 1, const_cast<char *>(issuer_fpr)));
    } else {
        // doesn't exist -> insert
        const std::vector<Key>::const_iterator pos = qBinaryFind(mKeysByFingerprint.begin(), mKeysByFingerprint.end(), issuer_fpr, _detail::ByFingerprint<std::less>());
Daniel Vrátil's avatar
Daniel Vrátil committed
861
        Q_ASSERT(pos != mKeysByFingerprint.end());
862
863
864
865
866
867
868
869
870
        beginInsertRows(index(*pos), row, row);
        subjects.insert(it, key);
        endInsertRows();
    }
}

void HierarchicalKeyListModel::addKeyWithoutParent(const char *issuer_fpr, const Key &key)
{

Daniel Vrátil's avatar
Daniel Vrátil committed
871
    Q_ASSERT(issuer_fpr); Q_ASSERT(*issuer_fpr); Q_ASSERT(!key.isNull());
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934

    std::vector<Key> &subjects = mKeysByNonExistingParent[issuer_fpr];

    // find insertion point:
    const std::vector<Key>::iterator it = std::lower_bound(subjects.begin(), subjects.end(), key, _detail::ByFingerprint<std::less>());

    if (it != subjects.end() && qstricmp(it->primaryFingerprint(), key.primaryFingerprint()) == 0)
        // exists -> replace
    {
        *it = key;
    } else
        // doesn't exist -> insert
    {
        subjects.insert(it, key);
    }

    addTopLevelKey(key);
}

void HierarchicalKeyListModel::addTopLevelKey(const Key &key)
{

    // find insertion point:
    const std::vector<Key>::iterator it = std::lower_bound(mTopLevels.begin(), mTopLevels.end(), key, _detail::ByFingerprint<std::less>());
    const int row = std::distance(mTopLevels.begin(), it);

    if (it != mTopLevels.end() && qstricmp(it->primaryFingerprint(), key.primaryFingerprint()) == 0) {
        // exists -> replace
        *it = key;
        Q_EMIT dataChanged(createIndex(row, 0), createIndex(row, NumColumns - 1));
    } else {
        // doesn't exist -> insert
        beginInsertRows(QModelIndex(), row, row);
        mTopLevels.insert(it, key);
        endInsertRows();
    }

}

// sorts 'keys' such that parent always come before their children:
static std::vector<Key> topological_sort(const std::vector<Key> &keys)
{

    boost::adjacency_list<> graph(keys.size());

    // add edges from children to parents:
    for (unsigned int i = 0, end = keys.size(); i != end; ++i) {
        const char *const issuer_fpr = cleanChainID(keys[i]);
        if (!issuer_fpr || !*issuer_fpr) {
            continue;
        }
        const std::vector<Key>::const_iterator it
            = qBinaryFind(keys.begin(), keys.end(), issuer_fpr, _detail::ByFingerprint<std::less>());
        if (it == keys.end()) {
            continue;
        }
        add_edge(i, std::distance(keys.begin(), it), graph);
    }

    std::vector<int> order;
    order.reserve(keys.size());
    topological_sort(graph, std::back_inserter(order));

Daniel Vrátil's avatar
Daniel Vrátil committed
935
    Q_ASSERT(order.size() == keys.size());
936
937
938

    std::vector<Key> result;
    result.reserve(keys.size());
Laurent Montel's avatar
Laurent Montel committed
939
    for (int i : qAsConst(order)) {
940
941
942
943
944
945
946
        result.push_back(keys[i]);
    }
    return result;
}

QList<QModelIndex> HierarchicalKeyListModel::doAddKeys(const std::vector<Key> &keys)
{
Daniel Vrátil's avatar
Daniel Vrátil committed
947
    Q_ASSERT(std::is_sorted(keys.begin(), keys.end(), _detail::ByFingerprint<std::less>()));
948

949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
    if (keys.empty()) {
        return QList<QModelIndex>();
    }

    const std::vector<Key> oldKeys = mKeysByFingerprint;

    std::vector<Key> merged;
    merged.reserve(keys.size() + mKeysByFingerprint.size());
    std::set_union(keys.begin(), keys.end(),
                   mKeysByFingerprint.begin(), mKeysByFingerprint.end(),
                   std::back_inserter(merged), _detail::ByFingerprint<std::less>());

    mKeysByFingerprint = merged;

    std::set<Key, _detail::ByFingerprint<std::less> > changedParents;

Laurent Montel's avatar
Laurent Montel committed
965
966
    const auto topologicalSortedList = topological_sort(keys);
    for (const Key &key : topologicalSortedList) {
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984

        // check to see whether this key is a parent for a previously parent-less group:
        const char *const fpr = key.primaryFingerprint();
        if (!fpr || !*fpr) {
            continue;
        }

        const bool keyAlreadyExisted = qBinaryFind(oldKeys.begin(), oldKeys.end(), key, _detail::ByFingerprint<std::less>()) != oldKeys.end();

        const Map::iterator it = mKeysByNonExistingParent.find(fpr);
        const std::vector<Key> children = it != mKeysByNonExistingParent.end() ? it->second : std::vector<Key>();
        if (it != mKeysByNonExistingParent.end()) {
            mKeysByNonExistingParent.erase(it);
        }

        // Step 1: For new keys, remove children from toplevel:

        if (!keyAlreadyExisted) {
Laurent Montel's avatar
Laurent Montel committed
985
986
            auto last = mTopLevels.begin();
            auto lastFP = mKeysByFingerprint.begin();
987

Laurent Montel's avatar
Laurent Montel committed
988
            for (const Key &k : qAsConst(children)) {
989
                last = qBinaryFind(last, mTopLevels.end(), k, _detail::ByFingerprint<std::less>());
Daniel Vrátil's avatar
Daniel Vrátil committed
990
                Q_ASSERT(last != mTopLevels.end());
991
992
993
                const int row = std::distance(mTopLevels.begin(), last);

                lastFP = qBinaryFind(lastFP, mKeysByFingerprint.end(), k, _detail::ByFingerprint<std::less>());
Daniel Vrátil's avatar
Daniel Vrátil committed
994
                Q_ASSERT(lastFP != mKeysByFingerprint.end());
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014

                Q_EMIT rowAboutToBeMoved(QModelIndex(), row);
                beginRemoveRows(QModelIndex(), row, row);
                last = mTopLevels.erase(last);
                lastFP = mKeysByFingerprint.erase(lastFP);
                endRemoveRows();
            }
        }
        // Step 2: add/update key

        const char *const issuer_fpr = cleanChainID(key);
        if (!issuer_fpr || !*issuer_fpr)
            // root or something...
        {
            addTopLevelKey(key);
        } else if (std::binary_search(mKeysByFingerprint.begin(), mKeysByFingerprint.end(), issuer_fpr, _detail::ByFingerprint<std::less>()))
            // parent exists...
        {
            addKeyWithParent(issuer_fpr, key);
        } else
Yuri Chornoivan's avatar
Yuri Chornoivan committed
1015
            // parent doesn't exist yet...
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
        {
            addKeyWithoutParent(issuer_fpr, key);
        }

        const QModelIndex key_idx = index(key);
        QModelIndex key_parent = key_idx.parent();
        while (key_parent.isValid()) {
            changedParents.insert(doMapToKey(key_parent));
            key_parent = key_parent.parent();
        }

        // Step 3: Add children to new parent ( == key )

        if (!keyAlreadyExisted && !children.empty()) {
            addKeys(children);
            const QModelIndex new_parent = index(key);
            // Q_EMIT the rowMoved() signals in reversed direction, so the
            // implementation can use a stack for mapping.
            for (int i = children.size() - 1; i >= 0; --i) {
                Q_EMIT rowMoved(new_parent, i);
            }
        }
    }
    //Q_EMIT dataChanged for all parents with new children. This triggers KeyListSortFilterProxyModel to
    //show a parent node if it just got children matching the proxy's filter
Laurent Montel's avatar
Laurent Montel committed
1041
    for (const Key &i : qAsConst(changedParents)) {
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
        const QModelIndex idx = index(i);
        if (idx.isValid()) {
            Q_EMIT dataChanged(idx.sibling(idx.row(), 0), idx.sibling(idx.row(), NumColumns - 1));
        }
    }
    return indexes(keys);
}

void HierarchicalKeyListModel::doRemoveKey(const Key &key)
{
    const QModelIndex idx = index(key);
    if (!idx.isValid()) {
        return;
    }

    const char *const fpr = key.primaryFingerprint();
    if (mKeysByExistingParent.find(fpr) != mKeysByExistingParent.end()) {
        //handle non-leave nodes:
        std::vector<Key> keys = mKeysByFingerprint;
        const std::vector<Key>::iterator it = qBinaryFind(keys.begin(), keys.end(),
                                              key, _detail::ByFingerprint<std::less>());
        if (it == keys.end()) {
            return;
        }
        keys.erase(it);
        // FIXME for simplicity, we just clear the model and re-add all keys minus the removed one. This is suboptimal,
        // but acceptable given that deletion of non-leave nodes is rather rare.
1069
        clear(Keys);
1070
1071
1072
1073
1074
1075
1076
1077
1078
        addKeys(keys);
        return;
    }

    //handle leave nodes:

    const std::vector<Key>::iterator it = qBinaryFind(mKeysByFingerprint.begin(), mKeysByFingerprint.end(),
                                          key, _detail::ByFingerprint<std::less>());

Daniel Vrátil's avatar
Daniel Vrátil committed
1079
1080
1081
    Q_ASSERT(it != mKeysByFingerprint.end());
    Q_ASSERT(mKeysByNonExistingParent.find(fpr) == mKeysByNonExistingParent.end());
    Q_ASSERT(mKeysByExistingParent.find(fpr) == mKeysByExistingParent.end());
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

    beginRemoveRows(parent(idx), idx.row(), idx.row());
    mKeysByFingerprint.erase(it);

    const char *const issuer_fpr = cleanChainID(key);

    const std::vector<Key>::iterator tlIt = qBinaryFind(mTopLevels.begin(), mTopLevels.end(), key, _detail::ByFingerprint<std::less>());
    if (tlIt != mTopLevels.end()) {
        mTopLevels.erase(tlIt);
    }

    if (issuer_fpr && *issuer_fpr) {
        const Map::iterator nexIt = mKeysByNonExistingParent.find(issuer_fpr);
        if (nexIt != mKeysByNonExistingParent.end()) {
            const std::vector<Key>::iterator eit = qBinaryFind(nexIt->second.begin(), nexIt->second.end(), key, _detail::ByFingerprint<std::less>());
            if (eit != nexIt->second.end()) {
                nexIt->second.erase(eit);
            }
            if (nexIt->second.empty()) {
                mKeysByNonExistingParent.erase(nexIt);
            }
        }

        const Map::iterator exIt = mKeysByExistingParent.find(issuer_fpr);
        if (exIt != mKeysByExistingParent.end()) {
            const std::vector<Key>::iterator eit = qBinaryFind(exIt->second.begin(), exIt->second.end(), key, _detail::ByFingerprint<std::less>());
            if (eit != exIt->second.end()) {
                exIt->second.erase(eit);
            }
            if (exIt->second.empty()) {
                mKeysByExistingParent.erase(exIt);
            }
        }
    }
    endRemoveRows();
}

1119
1120
KeyGroup HierarchicalKeyListModel::doMapToGroup(const QModelIndex &idx) const
{
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
    Q_ASSERT(idx.isValid());
    if (idx.parent().isValid()) {
        // groups are always top-level
        return KeyGroup();
    }

    if (static_cast<unsigned>(idx.row()) >= mTopLevels.size()
            && static_cast<unsigned>(idx.row()) < mTopLevels.size() + mGroups.size()
            && idx.column() < NumColumns) {
        return mGroups[ idx.row() - mTopLevels.size() ];
    } else {
        return KeyGroup();
    }
1134
1135
1136
1137
}

QModelIndex HierarchicalKeyListModel::doMapFromGroup(const KeyGroup &group, int column) const
{
1138
1139
1140
1141
1142
1143
1144
1145
    Q_ASSERT(!group.isNull());
    const QString name = group.name();
    const auto it = std::find_if(mGroups.begin(), mGroups.end(), [name](const KeyGroup &g) { return g.name() == name; });
    if (it == mGroups.end()) {
        return QModelIndex();
    } else {
        return createIndex(it - mGroups.begin() + mTopLevels.size(), column);
    }
1146
1147
}

Ingo Klöcker's avatar
Ingo Klöcker committed
1148
1149
void HierarchicalKeyListModel::doSetGroups(const std::vector<KeyGroup> &groups)
{
1150
1151
1152
1153
1154
1155
    Q_ASSERT(mGroups.empty());  // ensure that groups have been cleared
    const int first = mTopLevels.size();
    const int last = first + groups.size() - 1;
    beginInsertRows(QModelIndex(), first, last);
    mGroups = groups;
    endInsertRows();
Ingo Klöcker's avatar
Ingo Klöcker committed
1156
1157
}

1158
void AbstractKeyListModel::useKeyCache(bool value, KeyList::Options options)
1159
{
1160
    d->m_keyListOptions = options;
1161
    d->m_useKeyCache = value;
1162
1163
    if (!d->m_useKeyCache) {
        clear(All);
1164
    } else {
1165
        d->updateFromKeyCache();
1166
    }
1167
1168
    connect(KeyCache::instance().get(), &KeyCache::keysMayHaveChanged,
            this, [this] { d->updateFromKeyCache(); });
1169
1170
1171
1172
1173
1174
1175
}

// static
AbstractKeyListModel *AbstractKeyListModel::createFlatKeyListModel(QObject *p)
{
    AbstractKeyListModel *const m = new FlatKeyListModel(p);
#ifdef KLEO_MODEL_TEST
1176
    new QAbstractItemModelTester(m, p);
1177
1178
1179
1180
1181
1182
1183
1184
1185
#endif
    return m;
}

// static
AbstractKeyListModel *AbstractKeyListModel::createHierarchicalKeyListModel(QObject *p)
{
    AbstractKeyListModel *const m = new HierarchicalKeyListModel(p);
#ifdef KLEO_MODEL_TEST
1186
    new QAbstractItemModelTester(m, p);
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
#endif
    return m;
}

#include "keylistmodel.moc"

/*!
  \fn AbstractKeyListModel::rowAboutToBeMoved( const QModelIndex & old_parent, int old_row )

  Emitted before the removal of a row from that model. It will later
  be added to the model again, in response to which rowMoved() will be
  emitted. If multiple rows are moved in one go, multiple
  rowAboutToBeMoved() signals are emitted before the corresponding
  number of rowMoved() signals is emitted - in reverse order.

  This works around the absence of move semantics in
  QAbstractItemModel. Clients can maintain a stack to perform the
  QModelIndex-mapping themselves, or, e.g., to preserve the selection
  status of the row:

  \code
  std::vector<bool> mMovingRowWasSelected; // transient, used when rows are moved
  // ...
  void slotRowAboutToBeMoved( const QModelIndex & p, int row ) {
      mMovingRowWasSelected.push_back( selectionModel()->isSelected( model()->index( row, 0, p ) ) );
  }
  void slotRowMoved( const QModelIndex & p, int row ) {
      const bool wasSelected = mMovingRowWasSelected.back();
      mMovingRowWasSelected.pop_back();
      if ( wasSelected )
          selectionModel()->select( model()->index( row, 0, p ), Select|Rows );
  }
  \endcode

  A similar mechanism could be used to preserve the current item during moves.
*/

/*!
  \fn AbstractKeyListModel::rowMoved( const QModelIndex & new_parent, int new_parent )

  See rowAboutToBeMoved()
*/