aboutsummaryrefslogtreecommitdiff
path: root/libs/installer_bsplugins/src/BSPluginList/PluginListModel.cpp
blob: b330165f35667bfc82edf2b90d43926b81995ba1 (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
426
427
428
429
430
431
432
433
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
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
777
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
#include "PluginListModel.h"
#include "MOPlugin/Settings.h"
#include "PluginListDropInfo.h"

#include <QGuiApplication>
#include <QMimeData>

#include <algorithm>
#include <iterator>
#include <utility>
#include <vector>

namespace BSPluginList
{

PluginListModel::PluginListModel(TESData::PluginList* plugins) : m_Plugins{plugins} {}

QModelIndex PluginListModel::index(int row, int column,
                                   [[maybe_unused]] const QModelIndex& parent) const
{
  if ((row < 0) || (row >= rowCount()) || (column < 0) || (column >= columnCount())) {
    return QModelIndex();
  }
  return createIndex(row, column, row);
}

QModelIndex PluginListModel::parent([[maybe_unused]] const QModelIndex& index) const
{
  return QModelIndex();
}

Qt::ItemFlags PluginListModel::flags(const QModelIndex& index) const
{
  const int id = index.row();

  Qt::ItemFlags result = QAbstractItemModel::flags(index);

  if (index.isValid()) {
    const auto plugin = m_Plugins->getPlugin(id);
    if (plugin && (!plugin->forceLoaded() && !plugin->forceDisabled())) {
      if (index.column() == COL_PRIORITY)
        result |= Qt::ItemIsEditable;
      result |= Qt::ItemIsUserCheckable;
    }
    result |= Qt::ItemIsDragEnabled;
    result &= ~Qt::ItemIsDropEnabled;
  } else {
    result |= Qt::ItemIsDropEnabled;
  }

  return result;
}

static QVariantList
conflictListData(const TESData::PluginList* pluginList, const TESData::FileInfo* plugin,
                 const QSet<int>& (TESData::FileInfo::*getConflicts)() const)
{
  if (!plugin || !plugin->enabled()) {
    return QVariantList();
  }

  QVariantList list;
  for (const int otherId : (plugin->*getConflicts)()) {
    const auto other = pluginList->getPlugin(otherId);
    if (other && other->enabled()) {
      list.append(otherId);
    }
  }
  return list;
}

QVariant PluginListModel::data(const QModelIndex& index, int role) const
{
  switch (role) {
  case Qt::DisplayRole:
  case Qt::EditRole:
    return displayData(index);
  case Qt::CheckStateRole:
    if (index.column() == 0) {
      return checkstateData(index);
    }
    break;
  case Qt::ForegroundRole:
    return foregroundData(index);
  case Qt::BackgroundRole:
    return backgroundData(index);
  case Qt::FontRole:
    return fontData(index);
  case Qt::TextAlignmentRole:
    return alignmentData(index);
  case Qt::ToolTipRole:
    return tooltipData(index);
  case GroupingRole: {
    const auto id     = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return plugin ? plugin->group() : QVariant();
  }
  case IndexRole:
    return index.row();
  case InfoRole: {
    const auto id     = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return QVariant::fromValue(plugin);
  }
  case ConflictsIconRole:
    return conflictData(index);
  case FlagsIconRole:
    return iconData(index);
  case OriginRole: {
    const int id = index.row();
    return m_Plugins->getOriginName(id);
  }
  case OverridingRole: {
    const int id      = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return conflictListData(m_Plugins, plugin, &TESData::FileInfo::getPluginOverriding);
  }
  case OverriddenRole: {
    const int id      = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return conflictListData(m_Plugins, plugin, &TESData::FileInfo::getPluginOverridden);
  }
  case OverwritingAuxRole: {
    const int id      = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return conflictListData(m_Plugins, plugin,
                            &TESData::FileInfo::getPluginOverwritingArchive);
  }
  case OverwrittenAuxRole: {
    const int id      = index.row();
    const auto plugin = m_Plugins->getPlugin(id);
    return conflictListData(m_Plugins, plugin,
                            &TESData::FileInfo::getPluginOverwrittenArchive);
  }
  }
  return QVariant();
}

QVariant PluginListModel::displayData(const QModelIndex& index) const
{
  const int id      = index.row();
  const auto plugin = m_Plugins->getPlugin(id);

  if (!plugin) {
    return QVariant();
  }

  switch (index.column()) {
  case COL_NAME:
    return plugin->name();
  case COL_PRIORITY:
    return plugin->priority();
  case COL_MODINDEX:
    return plugin->index();
  case COL_FORMVERSION:
    return plugin->formVersion() != 0 ? QString::number(plugin->formVersion())
                                      : QString();
  case COL_HEADERVERSION:
    return QString::number(plugin->headerVersion());
  case COL_AUTHOR:
    return plugin->author();
  case COL_DESCRIPTION:
    return plugin->description();
  default:
    return QVariant();
  }
}

QVariant PluginListModel::checkstateData(const QModelIndex& index) const
{
  const int id      = index.row();
  const auto plugin = m_Plugins->getPlugin(id);

  if (!plugin) {
    return QVariant();
  }

  if (plugin->isAlwaysEnabled()) {
    // HACK: PluginListStyledItemDelegate draws the checkbox separately
    return QVariant();
  } else if (plugin->forceDisabled()) {
    return QVariant();
  } else {
    return plugin->enabled() ? Qt::Checked : Qt::Unchecked;
  }
}

QVariant PluginListModel::foregroundData(const QModelIndex& index) const
{
  const int id      = index.row();
  const auto plugin = m_Plugins->getPlugin(id);

  if (!plugin) {
    return QVariant();
  }

  if (plugin->hasNoRecords()) {
    if (index.column() == COL_NAME) {
      return QBrush(Qt::gray);
    }
  }

  if (plugin->forceDisabled()) {
    if (index.column() == COL_NAME) {
      return QBrush(Qt::darkRed);
    }
  }

  return QVariant();
}

QVariant
PluginListModel::backgroundData([[maybe_unused]] const QModelIndex& index) const
{
  return QVariant();
}

QVariant PluginListModel::fontData(const QModelIndex& index) const
{
  const int id      = index.row();
  const auto plugin = m_Plugins->getPlugin(id);

  QFont result;

  if (index.column() == COL_NAME) {
    if (plugin && plugin->hasNoRecords()) {
      result.setItalic(true);
    }
  }

  return result;
}

QVariant PluginListModel::alignmentData(const QModelIndex& index) const
{
  if (index.column() == 0) {
    return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
  } else {
    return QVariant(Qt::AlignHCenter | Qt::AlignVCenter);
  }
}

static QString truncateString(const QString& text, int length = 1024)
{
  QString new_text = text;

  if (new_text.length() > length) {
    new_text.truncate(length);
    new_text += "...";
  }

  return new_text;
}

static QString makeLootTooltip(const MOTools::Loot::Plugin&)
{
  // LOOT integration removed for Fluorine port — tooltip never built.
  return {};
}

QVariant PluginListModel::tooltipData(const QModelIndex& index) const
{
  const int id        = index.row();
  const auto plugin   = m_Plugins->getPlugin(id);
  const auto lootInfo = m_Plugins->getLootReport(plugin->name());

  if (!plugin) {
    return QVariant();
  }

  switch (index.column()) {
  case COL_NAME: {
    QString toolTip;

    toolTip += "<b>" + tr("Origin") + "</b>: " + m_Plugins->getOriginName(id);

    if (plugin->forceLoaded()) {
      toolTip += "<br><b><i>" +
                 tr("This plugin can't be disabled or moved (enforced by the game).") +
                 "</i></b>";
    } else if (plugin->forceEnabled()) {
      toolTip += "<br><b><i>" +
                 tr("This plugin can't be disabled (enforced by the game).") +
                 "</i></b>";
    }

    if (plugin->formVersion() != 0) {
      // Oblivion-style plugin headers don't have a form version
      toolTip += "<br><b>" + tr("Form Version") +
                 "</b>: " + QString::number(plugin->formVersion());
    }

    toolTip += "<br><b>" + tr("Header Version") +
               "</b>: " + QString::number(plugin->headerVersion());

    if (!plugin->author().isEmpty()) {
      toolTip += "<br><b>" + tr("Author") + "</b>: " + truncateString(plugin->author());
    }

    if (plugin->description().size() > 0) {
      toolTip += "<br><b>" + tr("Description") +
                 "</b>: " + truncateString(plugin->description());
    }

    if (plugin->enabled() && plugin->missingMasters().size() > 0) {
      toolTip += "<br><b>" + tr("Missing Masters") + "</b>: " + "<b>" +
                 truncateString(QStringList(plugin->missingMasters().begin(),
                                            plugin->missingMasters().end())
                                    .join(", ")) +
                 "</b>";
    }

    QStringList enabledMasters;
    std::ranges::remove_copy_if(plugin->masters(), std::back_inserter(enabledMasters),
                                [&](auto&& master) {
                                  return plugin->missingMasters().contains(master);
                                });

    if (!enabledMasters.empty()) {
      toolTip += "<br><b>" + tr("Enabled Masters") +
                 "</b>: " + truncateString(enabledMasters.join(", "));
    }

    if (!plugin->archives().empty()) {
      QString archiveString =
          plugin->archives().size() < 6
              ? truncateString(
                    QStringList(plugin->archives().begin(), plugin->archives().end())
                        .join(", "))
              : "";
      toolTip += "<br><b>" + tr("Loads Archives") + "</b>: " + archiveString;
    }

    if (plugin->hasIni()) {
      toolTip += "<br><b>" + tr("Loads INI settings") +
                 "</b>: " + QFileInfo(plugin->name()).baseName() + ".ini";
    }

    if (plugin->hasNoRecords()) {
      toolTip +=
          "<br><br>" + tr("This is a dummy plugin. It contains no records and is "
                          "typically used to load a paired archive file.");
    }

    return toolTip;
  }
  case COL_CONFLICTS: {
    const uint conflictFlags = data(index, ConflictsIconRole).toUInt();
    using enum TESData::FileInfo::EConflictFlag;

    QString toolTip;
    if ((conflictFlags & CONFLICT_MIXED) == CONFLICT_MIXED) {
      toolTip += tr("Overrides & has overridden records");
    } else if (conflictFlags & CONFLICT_OVERRIDE) {
      toolTip += tr("Overrides records");
    } else if (conflictFlags & CONFLICT_OVERRIDDEN) {
      toolTip += tr("Has overridden records");
    }

    if ((conflictFlags & CONFLICT_MIXED) && (conflictFlags & CONFLICT_ARCHIVE_MIXED)) {
      toolTip += "<br>";
    }

    if ((conflictFlags & CONFLICT_ARCHIVE_MIXED) == CONFLICT_ARCHIVE_MIXED) {
      toolTip += tr("Overwrites & has overwritten archive files");
    } else if (conflictFlags & CONFLICT_ARCHIVE_OVERWRITE) {
      toolTip += tr("Overwrites another archive file");
    } else if (conflictFlags & CONFLICT_ARCHIVE_OVERWRITTEN) {
      toolTip += tr("Overwritten by another archive file");
    }
    return toolTip;
  }
  case COL_FLAGS: {
    // HACK: insert some HTML to enable multiline tooltips
    QString toolTip       = "<nobr/>";
    const QString spacing = "<br><br>";

    if (plugin->enabled() && plugin->missingMasters().size() > 0) {
      toolTip += "<b>" + tr("Missing Masters") + "</b>: " + "<b>" +
                 truncateString(QStringList(plugin->missingMasters().begin(),
                                            plugin->missingMasters().end())
                                    .join(", ")) +
                 "</b>" + spacing;
    }

    if (plugin->hasIni()) {
      toolTip +=
          tr("There is an ini file connected to this plugin. Its settings will "
             "be added to your game settings, overwriting in case of conflicts.") +
          "<br><br>";
    }

    if (!plugin->archives().empty()) {
      toolTip +=
          tr("There are Archives connected to this plugin. Their assets will be "
             "added to your game, overwriting in case of conflicts following the "
             "plugin order. Loose files will always overwrite assets from "
             "Archives.") +
          spacing;
    }

    if (plugin->isMasterFile()) {
      toolTip += tr("This file is flagged as a master plugin (ESM). It will load "
                    "before any non-ESM "
                    "files in the load order.") +
                 spacing;
    }

    if (plugin->isSmallFile()) {
      toolTip +=
          tr("This file is flagged as a light plugin (ESL). It will adhere to its "
             "position in "
             "the load order but the records will be loaded in ESL space (FE/FF). You "
             "can have up to 4096 light plugins in addition to other plugin types.") +
          spacing;
    } else if (plugin->isMediumFile()) {
      toolTip += tr("This file is flagged as a medium plugin (ESH). It will adhere to "
                    "its position in the load order but the records will be loaded in "
                    "ESH space (FD). You can have 256 medium plugins in addition to "
                    "other plugin types.") +
                 spacing;
    }

    if (plugin->isBlueprintFile()) {
      toolTip += tr("This plugin has the blueprint flag. This forces it to load after "
                    "every other non-blueprint plugin. Blueprint plugins will adhere "
                    "to standard load order rules with other blueprint plugins.") +
                 spacing;
    }

    if (plugin->isLightFlagged() && plugin->isMediumFlagged()) {
      toolTip += tr("WARNING: This plugin is both light and medium flagged. This could "
                    "indicate that the file was saved improperly and may have "
                    "mismatched record references. Use it at your own risk.") +
                 spacing;
    }

    if (plugin->forceDisabled()) {
      toolTip += tr("This game does not currently permit custom plugin "
                    "loading. There may be manual workarounds.");
    }

    if (toolTip.endsWith(spacing)) {
      toolTip.chop(spacing.length());
    }

    if (lootInfo) {
      const auto lootToolTip = makeLootTooltip(*lootInfo);
      if (toolTip.length() > 7 && !lootToolTip.isEmpty()) {
        toolTip += "<hr>";
      }
      toolTip += lootToolTip;
    }

    return toolTip;
  }
  default:
    return QVariant();
  }
}

QVariant PluginListModel::conflictData(const QModelIndex& index) const
{
  const int id      = index.row();
  const auto plugin = m_Plugins->getPlugin(id);
  return plugin->conflictState();
}

static bool isProblematic(const TESData::FileInfo* plugin,
                          const MOTools::Loot::Plugin* lootInfo)
{
  if (plugin && plugin->enabled() && plugin->hasMissingMasters()) {
    return true;
  }

  if (lootInfo && Settings::instance()->lootShowProblems()) {
    if (!lootInfo->incompatibilities.empty()) {
      return true;
    }

    if (!lootInfo->missingMasters.empty()) {
      return true;
    }
  }

  return false;
}

QVariant PluginListModel::iconData(const QModelIndex& index) const
{
  const int id        = index.row();
  const auto plugin   = m_Plugins->getPlugin(id);
  const auto lootInfo = m_Plugins->getLootReport(plugin->name());

  if (!plugin) {
    return QVariant();
  }

  using enum TESData::FileInfo::EFlag;
  uint flag = 0;

  if (isProblematic(plugin, lootInfo)) {
    flag |= FLAG_PROBLEMATIC;
  }

  if (lootInfo && !lootInfo->messages.empty() &&
      Settings::instance()->lootShowMessages()) {
    flag |= FLAG_INFORMATION;
  }

  if (plugin->hasIni()) {
    flag |= FLAG_INI;
  }

  if (!plugin->archives().empty()) {
    flag |= FLAG_BSA;
  }

  if (plugin->isMasterFile()) {
    flag |= FLAG_MASTER;
  }

  if (plugin->isMediumFile()) {
    flag |= FLAG_MEDIUM;
  }

  if (plugin->isSmallFile()) {
    flag |= FLAG_LIGHT;
  }

  if (plugin->isBlueprintFile()) {
    flag |= FLAG_BLUEPRINT;
  }

  if (lootInfo && !lootInfo->dirty.empty() && Settings::instance()->lootShowDirty()) {
    flag |= FLAG_CLEAN;
  }

  return flag;
}

QVariant PluginListModel::headerData(int section, Qt::Orientation orientation,
                                     int role) const
{
  if (orientation == Qt::Horizontal) {
    if (role == Qt::DisplayRole) {
      switch (section) {
      case COL_NAME:
        return tr("Name");
      case COL_CONFLICTS:
        return tr("Conflicts");
      case COL_FLAGS:
        return tr("Flags");
      case COL_PRIORITY:
        return tr("Priority");
      case COL_MODINDEX:
        return tr("Mod Index");
      case COL_FORMVERSION:
        return tr("Form Version");
      case COL_HEADERVERSION:
        return tr("Header Version");
      case COL_AUTHOR:
        return tr("Author");
      case COL_DESCRIPTION:
        return tr("Description");
      default:
        return tr("unknown");
      }
    }
  }
  return QAbstractItemModel::headerData(section, orientation, role);
}

int PluginListModel::rowCount([[maybe_unused]] const QModelIndex& parent) const
{
  return m_Plugins->pluginCount();
}

int PluginListModel::columnCount([[maybe_unused]] const QModelIndex& parent) const
{
  return COL_COUNT;
}

bool PluginListModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
  if (role == Qt::CheckStateRole) {
    const int id = index.row();
    m_Plugins->setEnabled(id, value.toInt() == Qt::Checked);
    emit dataChanged(this->index(0, 0), this->index(rowCount() - 1, COL_MODINDEX),
                     {Qt::EditRole, Qt::CheckStateRole});
    emit pluginStatesChanged({index});
    return true;
  } else if (role == Qt::EditRole) {
    if (index.column() == COL_PRIORITY) {
      bool ok;
      const int newPriority = value.toInt(&ok);
      if (ok) {
        int destination = newPriority;
        if (newPriority > index.data(Qt::EditRole).toInt()) {
          ++destination;
        }
        m_Plugins->moveToPriority({index.row()}, destination);
        emit dataChanged(this->index(0, 0),
                         this->index(rowCount() - 1, columnCount() - 1),
                         {Qt::EditRole, GroupingRole});
        emit pluginOrderChanged();
        return true;
      }
    }
  }

  return false;
}

Qt::DropActions PluginListModel::supportedDropActions() const
{
  return Qt::MoveAction;
}

bool PluginListModel::canDropMimeData(const QMimeData* data, Qt::DropAction action,
                                      int row, [[maybe_unused]] int column,
                                      const QModelIndex& parent) const
{
  if (action == Qt::IgnoreAction) {
    return true;
  }

  if (action != Qt::MoveAction) {
    return false;
  }

  PluginListDropInfo dropInfo{data, row, parent, m_Plugins};
  return m_Plugins->canMoveToPriority(dropInfo.sourceRows(), dropInfo.destination());
}

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

  if (action != Qt::MoveAction) {
    return false;
  }

  PluginListDropInfo dropInfo{data, row, parent, m_Plugins};
  m_Plugins->moveToPriority(dropInfo.sourceRows(), dropInfo.destination());
  emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
                   {Qt::DisplayRole, GroupingRole});
  emit pluginOrderChanged();

  return true;
}

QStringList
PluginListModel::groups(std::function<bool(const TESData::FileInfo*)> pred) const
{
  boost::container::flat_set<QString> groupSet;
  QStringList groups;
  QString lastGroup;

  for (int priority = 0, count = m_Plugins->pluginCount(); priority < count;
       ++priority) {
    const auto plugin = m_Plugins->getPluginByPriority(priority);

    if (pred && !pred(plugin)) {
      continue;
    }

    const auto& group = plugin ? plugin->group() : QString();
    if (group.isEmpty() || group == lastGroup) {
      continue;
    }

    auto [it, inserted] = groupSet.insert(group);
    if (inserted) {
      groups.append(group);
    }
    lastGroup = group;
  }

  return groups;
}

QStringList PluginListModel::masterGroups() const
{
  return groups([](auto&& plugin) {
    return !plugin->forceLoaded() && plugin->isMasterFile();
  });
}

QStringList PluginListModel::regularGroups() const
{
  return groups([](auto&& plugin) {
    return !plugin->forceLoaded() && !plugin->isMasterFile();
  });
}

void PluginListModel::refresh()
{
  emit beginResetModel();
  m_Plugins->refresh();
  emit endResetModel();
}

void PluginListModel::invalidate()
{
  emit beginResetModel();
  m_Plugins->refresh(true);
  emit endResetModel();
}

void PluginListModel::invalidateConflicts()
{
  for (int i = 0, count = m_Plugins->pluginCount(); i < count; ++i) {
    const auto plugin = m_Plugins->getPlugin(i);
    plugin->invalidateConflicts();
  }

  emit dataChanged(index(0, COL_CONFLICTS), index(rowCount() - 1, COL_CONFLICTS),
                   {PluginListModel::ConflictsIconRole});
}

void PluginListModel::movePlugin(const QString& name, [[maybe_unused]] int oldPriority,
                                 int newPriority)
{
  m_Plugins->setPriority(name, newPriority);
  emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
                   {Qt::DisplayRole, GroupingRole});
  emit pluginOrderChanged();
}

void PluginListModel::changePluginStates(
    const std::map<QString, MOBase::IPluginList::PluginStates>& infos)
{
  QModelIndexList indices;
  for (auto& [name, state] : infos) {
    m_Plugins->setState(name, state);

    const auto idx = m_Plugins->getIndex(name);
    if (idx != -1) {
      indices.append(index(idx, 0));
    }
  }

  emit dataChanged(index(0, 0), index(rowCount() - 1, COL_MODINDEX),
                   {Qt::DisplayRole, Qt::CheckStateRole});
  emit pluginStatesChanged(indices);
}

void PluginListModel::setEnabledAll(bool enabled)
{
  QModelIndexList indices;
  indices.reserve(rowCount());
  std::generate_n(std::back_inserter(indices), rowCount(), [this, i = 0]() mutable {
    return index(i++, 0);
  });
  setEnabled(indices, enabled);
}

void PluginListModel::setEnabled(const QModelIndexList& indices, bool enabled)
{
  if (indices.empty()) {
    return;
  }

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->setEnabled(std::move(ids), enabled);
  emit pluginStatesChanged(indices);
}

void PluginListModel::sendToPriority(const QModelIndexList& indices, int priority,
                                     bool disjoint)
{
  if (indices.empty()) {
    return;
  }

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->moveToPriority(std::move(ids), priority, disjoint);
  emit dataChanged(index(0, COL_PRIORITY), index(rowCount() - 1, COL_MODINDEX),
                   {Qt::DisplayRole});
  emit pluginOrderChanged();
}

void PluginListModel::shiftPluginsPriority(const QModelIndexList& indices, int offset)
{
  if (indices.empty()) {
    return;
  }

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->shiftPriority(std::move(ids), offset);
  emit dataChanged(index(0, COL_PRIORITY), index(rowCount() - 1, COL_MODINDEX),
                   {Qt::DisplayRole});
  emit pluginOrderChanged();
}

void PluginListModel::toggleState(const QModelIndexList& indices)
{
  if (indices.empty()) {
    return;
  }

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->toggleState(std::move(ids));
  emit pluginStatesChanged(indices);
}

void PluginListModel::setGroup(const QModelIndexList& indices, const QString& group)
{
  if (indices.empty()) {
    return;
  }

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->setGroup(std::move(ids), group);
  emit dataChanged(this->index(0, 0), this->index(rowCount() - 1, COL_MODINDEX),
                   {GroupingRole});
}

void PluginListModel::sendToGroup(const QModelIndexList& indices, const QString& group,
                                  bool isESM)
{
  int destination = -1;
  for (int priority = 0, count = m_Plugins->pluginCount(); priority < count;
       ++priority) {
    const auto plugin = m_Plugins->getPluginByPriority(priority);
    if (plugin && plugin->isMasterFile() == isESM && plugin->group() == group) {
      destination = priority + 1;
    }
  }

  if (destination == -1)
    return;

  std::vector<int> ids;
  ids.reserve(indices.size());
  std::ranges::transform(indices, std::back_inserter(ids), [](const QModelIndex& idx) {
    return idx.row();
  });
  m_Plugins->setGroup(ids, group);
  m_Plugins->moveToPriority(std::move(ids), destination);
  emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
                   {Qt::DisplayRole, GroupingRole});
  emit pluginOrderChanged();
}

}  // namespace BSPluginList