summaryrefslogtreecommitdiff
path: root/src/modlistbypriorityproxy.cpp
blob: ba53ee7495c4437bd1458609ba2838cb215b755d (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
#include "modlistbypriorityproxy.h"

#include "log.h"
#include "modinfo.h"
#include "modlist.h"
#include "modlistdropinfo.h"
#include "organizercore.h"
#include "profile.h"

ModListByPriorityProxy::ModListByPriorityProxy(Profile* profile, OrganizerCore& core,
                                               QObject* parent)
    : QAbstractProxyModel(parent), m_core(core), m_profile(profile)
{}

ModListByPriorityProxy::~ModListByPriorityProxy() {}

void ModListByPriorityProxy::setSourceModel(QAbstractItemModel* model)
{
  if (sourceModel()) {
    disconnect(sourceModel(), nullptr, this, nullptr);
  }

  QAbstractProxyModel::setSourceModel(model);

  if (sourceModel()) {
    connect(sourceModel(), &QAbstractItemModel::layoutChanged, this,
            &ModListByPriorityProxy::onModelLayoutChanged, Qt::UniqueConnection);
    connect(sourceModel(), &QAbstractItemModel::rowsRemoved, this,
            &ModListByPriorityProxy::onModelRowsRemoved, Qt::UniqueConnection);
    connect(sourceModel(), &QAbstractItemModel::modelReset, this,
            &ModListByPriorityProxy::onModelReset, Qt::UniqueConnection);
    connect(sourceModel(), &QAbstractItemModel::dataChanged, this,
            &ModListByPriorityProxy::onModelDataChanged, Qt::UniqueConnection);

    onModelReset();
  }
}

void ModListByPriorityProxy::setProfile(Profile* profile)
{
  m_profile = profile;
}

void ModListByPriorityProxy::setSortOrder(Qt::SortOrder order)
{
  if (m_sortOrder != order) {
    m_sortOrder = order;
    onModelLayoutChanged();
  }
}

void ModListByPriorityProxy::buildMapping()
{
  m_IndexToItem.clear();
  for (unsigned int index = 0; index < ModInfo::getNumMods(); ++index) {
    m_IndexToItem[index] =
        std::make_unique<TreeItem>(ModInfo::getByIndex(index), index);
  }
}

void ModListByPriorityProxy::buildTree()
{
  if (!sourceModel())
    return;

  // reset the root
  m_Root = {};

  // clear all children
  for (auto& [index, item] : m_IndexToItem) {
    item->children.clear();
  }

  TreeItem* root = &m_Root;
  TreeItem* overwrite;
  std::vector<TreeItem*> backups;

  auto fn = [&](const auto& p) {
    auto& [priority, index] = p;
    ModInfo::Ptr modInfo    = ModInfo::getByIndex(index);
    TreeItem* item          = m_IndexToItem[index].get();

    if (modInfo->isSeparator()) {
      item->parent = &m_Root;
      m_Root.children.push_back(item);
      root = item;
    } else if (modInfo->isOverwrite()) {
      // do not push here, because the overwrite is usually not at the right position
      item->parent = &m_Root;
      overwrite    = item;
    } else if (modInfo->isBackup()) {
      // do not push here, because backups are usually not at the right position
      item->parent = &m_Root;
      backups.push_back(item);
    } else {
      item->parent = root;
      root->children.push_back(item);
    }
  };

  auto& ibp = m_profile->getAllIndexesByPriority();
  if (m_sortOrder == Qt::AscendingOrder) {
    std::for_each(ibp.begin(), ibp.end(), fn);
    m_Root.children.insert(m_Root.children.begin(),
                           std::make_move_iterator(backups.begin()),
                           std::make_move_iterator(backups.end()));
    m_Root.children.push_back(std::move(overwrite));
  } else {
    std::for_each(ibp.rbegin(), ibp.rend(), fn);
    m_Root.children.insert(m_Root.children.begin(), std::move(overwrite));
    m_Root.children.insert(m_Root.children.end(),
                           std::make_move_iterator(backups.begin()),
                           std::make_move_iterator(backups.end()));
  }
}

void ModListByPriorityProxy::onModelRowsRemoved(const QModelIndex& parent, int first,
                                                int last)
{
  onModelReset();
}

void ModListByPriorityProxy::onModelLayoutChanged(const QList<QPersistentModelIndex>&,
                                                  LayoutChangeHint hint)
{
  emit layoutAboutToBeChanged();
  auto persistent = persistentIndexList();
  buildTree();

  QModelIndexList toPersistent;
  for (auto& idx : persistent) {
    // we can still access the TreeItem* because we did not destroy them
    auto* item = static_cast<TreeItem*>(idx.internalPointer());
    toPersistent.append(
        createIndex(item->parent->childIndex(item), idx.column(), item));
  }
  changePersistentIndexList(persistent, toPersistent);

  emit layoutChanged({}, hint);
}

void ModListByPriorityProxy::onModelReset()
{
  beginResetModel();
  buildMapping();
  buildTree();
  endResetModel();
}

void ModListByPriorityProxy::onModelDataChanged(const QModelIndex& topLeft,
                                                const QModelIndex& bottomRight,
                                                const QVector<int>& roles)
{
  QModelIndex proxyTopLeft = mapFromSource(topLeft);
  if (!proxyTopLeft.isValid()) {
    return;
  }

  if (topLeft == bottomRight) {
    emit dataChanged(proxyTopLeft, proxyTopLeft);
  } else {
    QModelIndex proxyBottomRight = mapFromSource(bottomRight);
    emit dataChanged(proxyTopLeft, proxyBottomRight);
  }
}

QModelIndex ModListByPriorityProxy::mapFromSource(const QModelIndex& sourceIndex) const
{
  if (!sourceIndex.isValid()) {
    return QModelIndex();
  }

  auto* item = m_IndexToItem.at(sourceIndex.row()).get();
  return createIndex(item->parent->childIndex(item), sourceIndex.column(), item);
}

QModelIndex ModListByPriorityProxy::mapToSource(const QModelIndex& proxyIndex) const
{
  if (!proxyIndex.isValid()) {
    return QModelIndex();
  }
  auto* item = static_cast<TreeItem*>(proxyIndex.internalPointer());

  return sourceModel()->index(item->index, proxyIndex.column());
}

int ModListByPriorityProxy::rowCount(const QModelIndex& parent) const
{
  if (!parent.isValid()) {
    return m_Root.children.size();
  }

  auto* item = static_cast<TreeItem*>(parent.internalPointer());

  if (item->mod->isSeparator()) {
    return item->children.size();
  }

  return 0;
}

int ModListByPriorityProxy::columnCount(const QModelIndex& index) const
{
  return sourceModel()->columnCount(mapToSource(index));
}

QModelIndex ModListByPriorityProxy::parent(const QModelIndex& child) const
{
  if (!child.isValid()) {
    return QModelIndex();
  }

  auto* item = static_cast<TreeItem*>(child.internalPointer());

  if (!item->parent || item->parent == &m_Root) {
    return QModelIndex();
  }

  return createIndex(item->parent->parent->childIndex(item->parent), 0, item->parent);
}

bool ModListByPriorityProxy::hasChildren(const QModelIndex& parent) const
{
  if (!parent.isValid()) {
    return m_Root.children.size() > 0;
  }
  auto* item = static_cast<TreeItem*>(parent.internalPointer());
  return item->children.size() > 0;
}

bool ModListByPriorityProxy::canDropMimeData(const QMimeData* data,
                                             Qt::DropAction action, int row, int column,
                                             const QModelIndex& parent) const
{
  ModListDropInfo dropInfo(data, m_core);

  if (!dropInfo.isValid() || dropInfo.isLocalFileDrop()) {
    return QAbstractProxyModel::canDropMimeData(data, action, row, column, parent);
  }

  if (dropInfo.isModDrop()) {
    bool hasSeparator          = false;
    unsigned int firstRowIndex = -1;

    int firstRowPriority = Profile::MaximumPriority;
    for (auto sourceRow : dropInfo.rows()) {
      hasSeparator = hasSeparator || ModInfo::getByIndex(sourceRow)->isSeparator();
      if (m_sortOrder == Qt::AscendingOrder &&
              m_profile->getModPriority(sourceRow) < firstRowPriority ||
          m_sortOrder == Qt::DescendingOrder &&
              m_profile->getModPriority(sourceRow) > firstRowPriority) {
        firstRowIndex    = sourceRow;
        firstRowPriority = m_profile->getModPriority(sourceRow);
      }
    }

    bool firstRowSeparator =
        firstRowIndex != -1 && ModInfo::getByIndex(firstRowIndex)->isSeparator();

    // row = -1 and valid parent means we're dropping onto an item, we don't want to
    // drop separators onto items or items into their own separator
    if (row == -1 && parent.isValid()) {
      auto* parentItem = static_cast<TreeItem*>(parent.internalPointer());
      if (hasSeparator) {
        return !parentItem->mod->isSeparator();
      }

      for (auto row : dropInfo.rows()) {
        auto it = m_IndexToItem.find(row);
        if (it != m_IndexToItem.end() && it->second->parent == parentItem) {
          return false;
        }
      }
    }

    // first row is a separator, we can drop it anywhere
    if (firstRowSeparator) {
      return QAbstractProxyModel::canDropMimeData(data, action, row, column, parent);
    }
  }

  // the row may be outside of the children list if we insert at the end
  if (!parent.isValid() && row >= m_Root.children.size()) {
    return false;
  }

  return QAbstractProxyModel::canDropMimeData(data, action, row, column, parent);
}

bool ModListByPriorityProxy::dropMimeData(const QMimeData* data, Qt::DropAction action,
                                          int row, int column,
                                          const QModelIndex& parent)
{
  // we need to fix the source model row if we are dropping at a
  // given priority (not a local file)
  const ModListDropInfo dropInfo(data, m_core);
  int sourceRow = -1;

  if (dropInfo.isLocalFileDrop()) {
    if (parent.isValid()) {
      sourceRow = static_cast<TreeItem*>(parent.internalPointer())->index;
    }
  } else {

    if (row >= 0) {
      if (!parent.isValid()) {
        if (row < m_Root.children.size()) {

          if (m_sortOrder == Qt::AscendingOrder) {
            sourceRow = m_Root.children[row]->index;

            // fix bug when dropping a mod just below an expanded separator
            //
            // by default, Qt consider it's a drop at the end of that separator
            // but we want to make it a drop at the beginning
            if (row > 0 && m_sortOrder == Qt::AscendingOrder &&
                m_Root.children[row - 1]->mod->isSeparator() &&
                !m_Root.children[row - 1]->children.empty() && m_dropExpanded &&
                m_dropPosition == ModListView::DropPosition::BelowItem) {
              sourceRow = m_Root.children[row - 1]->children[0]->index;
            }
          } else {
            sourceRow = m_Root.children[row - 1]->index;

            // fix drop below a collapsed separator or at the end of an expanded
            // separator, above the next item
            if (row > 0 && m_sortOrder == Qt::DescendingOrder &&
                m_Root.children[row - 1]->mod->isSeparator() &&
                !m_Root.children[row - 1]->children.empty() &&
                (!m_dropExpanded ||
                 m_dropPosition == ModListView::DropPosition::AboveItem)) {
              sourceRow = m_Root.children[row - 1]->children.back()->index;
            }
          }
        } else {
          sourceRow = ModInfo::getNumMods();
        }
      }

      // the parent is valid, we are dropping in a separator
      else {
        auto* item = static_cast<TreeItem*>(parent.internalPointer());

        // we usually need to decrement the row in descending priority, but if
        // it's the first row, we need to go back to the separator itself
        if (m_sortOrder == Qt::DescendingOrder && row == 0 &&
            m_dropPosition == ModListView::DropPosition::AboveItem) {
          sourceRow = item->index;
        } else {

          // in descending priority, we decrement the row to fix the drop position
          // because this is not done by the sort proxy for us
          if (m_sortOrder == Qt::DescendingOrder) {
            row--;
          }

          if (row < item->children.size()) {
            sourceRow = item->children[row]->index;
          } else if (parent.row() + 1 < m_Root.children.size()) {
            sourceRow = m_Root.children[parent.row() + 1]->index;
          }
        }
      }
    }

    // row < 0 and valid parent means we are dropping into an item,
    // which can only be a separator since dropping into non-separators
    // is disabled
    //
    // we want to drop at the end of the separator, so we need to find
    // the right priority
    else if (parent.isValid()) {

      // in ascending priority, we take the priority of the next top-level
      // item, which can be a separator or the overwrite mod, but is guaranteed
      // to exist
      if (m_sortOrder == Qt::AscendingOrder) {
        sourceRow = m_Root.children[parent.row() + 1]->index;
      }

      // in descending priority, we take the separator itself if it's empty or
      // its last children
      else {
        auto* item = m_Root.children[parent.row()];
        sourceRow = item->children.empty() ? item->index : item->children.back()->index;
      }
    }
  }

  return sourceModel()->dropMimeData(data, action, sourceRow, column, QModelIndex());
}

QModelIndex ModListByPriorityProxy::index(int row, int column,
                                          const QModelIndex& parent) const
{
  if (!hasIndex(row, column, parent)) {
    return QModelIndex();
  }

  const TreeItem* parentItem;
  if (!parent.isValid()) {
    parentItem = &m_Root;
  } else {
    parentItem = static_cast<TreeItem*>(parent.internalPointer());
  }

  return createIndex(row, column, parentItem->children[row]);
}

void ModListByPriorityProxy::onDropEnter(const QMimeData*, bool dropExpanded,
                                         ModListView::DropPosition dropPosition)
{
  m_dropExpanded = dropExpanded;
  m_dropPosition = dropPosition;
}