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

#include <QMimeData>
#include <QUrl>

#include <report.h>
#include <widgetutility.h>

#include "copyeventfilter.h"
#include "gameplugins.h"
#include "genericicondelegate.h"
#include "mainwindow.h"
#include "modelutils.h"
#include "modlistview.h"
#include "modlistviewactions.h"
#include "organizercore.h"
#include "pluginlistcontextmenu.h"
#include "pluginlistsortproxy.h"
#include "shared/directoryentry.h"
#include "shared/fileentry.h"
#include "shared/filesorigin.h"
#include "ui_mainwindow.h"

using namespace MOBase;

PluginListView::PluginListView(QWidget* parent)
    : QTreeView(parent), m_sortProxy(nullptr),
      m_Scrollbar(new ViewMarkingScrollBar(this, Qt::BackgroundRole)),
      m_didUpdateMasterList(false)
{
  setVerticalScrollBar(m_Scrollbar);
  MOBase::setCustomizableColumns(this);
  installEventFilter(new CopyEventFilter(this));
}

void PluginListView::activated()
{
  // update highlighted mods
  selectionModel()->selectionChanged({}, {});
}

int PluginListView::sortColumn() const
{
  return m_sortProxy ? m_sortProxy->sortColumn() : -1;
}

QModelIndex PluginListView::indexModelToView(const QModelIndex& index) const
{
  return MOShared::indexModelToView(index, this);
}

QModelIndexList PluginListView::indexModelToView(const QModelIndexList& index) const
{
  return MOShared::indexModelToView(index, this);
}

QModelIndex PluginListView::indexViewToModel(const QModelIndex& index) const
{
  return MOShared::indexViewToModel(index, m_core->pluginList());
}

QModelIndexList PluginListView::indexViewToModel(const QModelIndexList& index) const
{
  return MOShared::indexViewToModel(index, m_core->pluginList());
}

void PluginListView::updatePluginCount()
{
  int activeMasterCount       = 0;
  int activeMediumMasterCount = 0;
  int activeLightMasterCount  = 0;
  int activeBlueprintCount    = 0;
  int activeRegularCount      = 0;
  int masterCount             = 0;
  int mediumMasterCount       = 0;
  int lightMasterCount        = 0;
  int blueprintCount          = 0;
  int regularCount            = 0;
  int activeVisibleCount      = 0;

  PluginList* list = m_core->pluginList();
  QString filter   = ui.filter->text();

  for (QString plugin : list->pluginNames()) {
    bool active  = list->isEnabled(plugin);
    bool visible = m_sortProxy->filterMatchesPlugin(plugin);
    if (list->isMediumFlagged(plugin)) {
      mediumMasterCount++;
      activeMediumMasterCount += active;
      activeVisibleCount += visible && active;
    } else if (list->hasLightExtension(plugin) || list->isLightFlagged(plugin)) {
      lightMasterCount++;
      activeLightMasterCount += active;
      activeVisibleCount += visible && active;
    } else if (list->hasMasterExtension(plugin) || list->isMasterFlagged(plugin)) {
      masterCount++;
      activeMasterCount += active;
      activeVisibleCount += visible && active;
    } else {
      regularCount++;
      activeRegularCount += active;
      activeVisibleCount += visible && active;
    }

    if (list->isBlueprintFlagged(plugin)) {
      // separate if-statement because blueprint masters are also counted as
      // (medium/light) masters
      blueprintCount++;
      activeBlueprintCount += active;
    }
  }

  int activeCount = activeMasterCount + activeMediumMasterCount +
                    activeLightMasterCount + activeRegularCount;
  int totalCount = masterCount + mediumMasterCount + lightMasterCount + regularCount;

  auto toolTip =
      tr("<table cellspacing=\"6\">"
         "<tr><th>Type</th><th>Active      </th><th>Total</th></tr>"
         "<tr><td>All plugins:</td><td align=right>%1    </td><td "
         "align=right>%2</td></tr>"
         "<tr><td>ESMs:</td><td align=right>%3    </td><td align=right>%4</td></tr>"
         "<tr><td>ESPs:</td><td align=right>%5    </td><td align=right>%6</td></tr>"
         "<tr><td>ESMs+ESPs:</td><td align=right>%7    </td><td "
         "align=right>%8</td></tr>")
          .arg(activeCount)
          .arg(totalCount)
          .arg(activeMasterCount)
          .arg(masterCount)
          .arg(activeRegularCount)
          .arg(regularCount)
          .arg(activeMasterCount + activeRegularCount)
          .arg(masterCount + regularCount);

  auto gamePlugins = m_core->gameFeatures().gameFeature<GamePlugins>();
  const bool lightPluginsAreSupported =
      gamePlugins ? gamePlugins->lightPluginsAreSupported() : false;
  const bool mediumPluginsAreSupported =
      gamePlugins ? gamePlugins->mediumPluginsAreSupported() : false;
  const bool blueprintPluginsAreSupported =
      gamePlugins ? gamePlugins->blueprintPluginsAreSupported() : false;

  if (mediumPluginsAreSupported) {
    toolTip +=
        tr("<tr><td>ESHs:</td><td align=right>%1   </td><td align=right>%2</td></tr>")
            .arg(activeMediumMasterCount)
            .arg(mediumMasterCount);
  }
  if (lightPluginsAreSupported) {
    toolTip +=
        tr("<tr><td>ESLs:</td><td align=right>%1    </td><td align=right>%2</td></tr>")
            .arg(activeLightMasterCount)
            .arg(lightMasterCount);
  }
  if (blueprintPluginsAreSupported) {
    toolTip += tr("<tr><td>Blueprint masters:</td><td align=right>%1    </td><td "
                  "align=right>%2</td></tr>")
                   .arg(activeBlueprintCount)
                   .arg(blueprintCount);
  }

  toolTip += "</table>";

  ui.counter->display(activeVisibleCount);
  ui.counter->setToolTip(toolTip);
}

void PluginListView::onFilterChanged(const QString& filter)
{
  if (!filter.isEmpty()) {
    setStyleSheet("QTreeView { border: 2px ridge #f00; }");
    ui.counter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }");
  } else {
    setStyleSheet("");
    ui.counter->setStyleSheet("");
  }
  updatePluginCount();
}

void PluginListView::onSortButtonClicked()
{
  const bool offline = m_core->settings().network().offlineMode();

  auto r = QMessageBox::No;

  if (offline) {
    r = QMessageBox::question(topLevelWidget(), tr("Sorting plugins"),
                              tr("Are you sure you want to sort your plugins list?") +
                                  "\r\n\r\n" +
                                  tr("Note: You are currently in offline mode and LOOT "
                                     "will not update the master list."),
                              QMessageBox::Yes | QMessageBox::No);
  } else {
    r = QMessageBox::question(topLevelWidget(), tr("Sorting plugins"),
                              tr("Are you sure you want to sort your plugins list?"),
                              QMessageBox::Yes | QMessageBox::No);
  }

  if (r != QMessageBox::Yes) {
    return;
  }

  m_core->savePluginList();

  topLevelWidget()->setEnabled(false);
  Guard g([=]() {
    topLevelWidget()->setEnabled(true);
  });

  // don't try to update the master list in offline mode
  const bool didUpdateMasterList = offline ? true : m_didUpdateMasterList;

  if (runLoot(topLevelWidget(), *m_core, didUpdateMasterList)) {
    // don't assume the master list was updated in offline mode
    if (!offline) {
      m_didUpdateMasterList = true;
    }

    m_core->refreshESPList(false);
    m_core->savePluginList();
  }
}

std::pair<QModelIndex, QModelIndexList> PluginListView::selected() const
{
  return {indexViewToModel(currentIndex()),
          indexViewToModel(selectionModel()->selectedRows())};
}

void PluginListView::setSelected(const QModelIndex& current,
                                 const QModelIndexList& selected)
{
  setCurrentIndex(indexModelToView(current));
  for (auto idx : selected) {
    selectionModel()->select(indexModelToView(idx),
                             QItemSelectionModel::Select | QItemSelectionModel::Rows);
  }
}

void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* mwui)
{
  m_core       = &core;
  ui           = {mwui->activePluginsCounter, mwui->espFilterEdit};
  m_modActions = &mwui->modList->actions();

  m_sortProxy = new PluginListSortProxy(&core);
  m_sortProxy->setSourceModel(core.pluginList());
  setModel(m_sortProxy);

  sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder);
  setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(this));

  // counter
  connect(core.pluginList(), &PluginList::writePluginsList, [=] {
    updatePluginCount();
  });
  connect(core.pluginList(), &PluginList::esplist_changed, [=] {
    updatePluginCount();
  });

  // sort
  connect(mwui->sortButton, &QPushButton::clicked, [=] {
    onSortButtonClicked();
  });

  // filter
  connect(ui.filter, &QLineEdit::textChanged, m_sortProxy,
          &PluginListSortProxy::updateFilter);
  connect(ui.filter, &QLineEdit::textChanged, this, &PluginListView::onFilterChanged);

  // highlight mod list when selected
  connect(selectionModel(), &QItemSelectionModel::selectionChanged, [=] {
    std::set<QString> mods;
    auto& directoryEntry = *m_core->directoryStructure();
    auto pluginIndices   = indexViewToModel(selectionModel()->selectedRows());
    for (auto& idx : pluginIndices) {
      QString pluginName = m_core->pluginList()->getName(idx.row());

      const MOShared::FileEntryPtr fileEntry =
          directoryEntry.findFile(pluginName.toStdWString());
      if (fileEntry.get() != nullptr) {
        QString originName = QString::fromStdWString(
            directoryEntry.getOriginByID(fileEntry->getOrigin()).getName());
        mods.insert(originName);
      }
    }
    mwui->modList->setHighlightedMods(mods);
    m_core->pluginList()->highlightMasters(pluginIndices);
    repaint();
    verticalScrollBar()->repaint();
  });

  // using a lambda here to avoid storing the mod list actions
  connect(this, &QTreeView::customContextMenuRequested, [=](auto&& pos) {
    onCustomContextMenuRequested(pos);
  });
  connect(this, &QTreeView::doubleClicked, [=](auto&& index) {
    onDoubleClicked(index);
  });
}

void PluginListView::onCustomContextMenuRequested(const QPoint& pos)
{
  try {
    PluginListContextMenu menu(indexViewToModel(indexAt(pos)), *m_core, this);
    connect(&menu, &PluginListContextMenu::openModInformation, [=](auto&& modIndex) {
      m_modActions->displayModInformation(modIndex);
    });
    menu.exec(viewport()->mapToGlobal(pos));
  } catch (const std::exception& e) {
    reportError(tr("Exception: ").arg(e.what()));
  } catch (...) {
    reportError(tr("Unknown exception"));
  }
}

void PluginListView::onDoubleClicked(const QModelIndex& index)
{
  if (!index.isValid()) {
    return;
  }

  if (m_core->pluginList()->timeElapsedSinceLastChecked() <=
      QApplication::doubleClickInterval()) {
    // don't interpret double click if we only just checked a plugin
    return;
  }

  try {
    if (selectionModel()->hasSelection() &&
        selectionModel()->selectedRows().count() == 1) {

      QModelIndex idx  = selectionModel()->currentIndex();
      QString fileName = idx.data().toString();

      if (ModInfo::getIndex(m_core->pluginList()->origin(fileName)) == UINT_MAX) {
        return;
      }

      auto modIndex        = ModInfo::getIndex(m_core->pluginList()->origin(fileName));
      ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);

      if (modInfo->isRegular() || modInfo->isOverwrite()) {

        Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers();
        if (modifiers.testFlag(Qt::ControlModifier)) {
          m_modActions->openExplorer({m_core->modList()->index(modIndex, 0)});
        } else {
          m_modActions->displayModInformation(
              ModInfo::getIndex(m_core->pluginList()->origin(fileName)));
        }

        // workaround to cancel the editor that might have opened because of
        // selection-click
        closePersistentEditor(index);
      }
    }
  } catch (const std::exception& e) {
    reportError(e.what());
  }
}

bool PluginListView::moveSelection(int key)
{
  auto [cindex, sourceRows] = selected();

  int offset = key == Qt::Key_Up ? -1 : 1;
  if (m_sortProxy->sortOrder() == Qt::DescendingOrder) {
    offset = -offset;
  }

  m_core->pluginList()->shiftPluginsPriority(sourceRows, offset);

  // reset the selection and the index
  setSelected(cindex, sourceRows);

  return true;
}

bool PluginListView::toggleSelectionState()
{
  if (!selectionModel()->hasSelection()) {
    return true;
  }
  m_core->pluginList()->toggleState(indexViewToModel(selectionModel()->selectedRows()));
  return true;
}

bool PluginListView::event(QEvent* event)
{
  if (event->type() == QEvent::KeyPress) {
    QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);

    if (keyEvent->modifiers() == Qt::ControlModifier &&
        (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)) {
      if (selectionModel()->hasSelection() &&
          selectionModel()->selectedRows().count() == 1) {
        QModelIndex idx  = selectionModel()->currentIndex();
        QString fileName = idx.data().toString();

        if (ModInfo::getIndex(m_core->pluginList()->origin(fileName)) == UINT_MAX) {
          return false;
        }

        auto modIndex = ModInfo::getIndex(m_core->pluginList()->origin(fileName));
        m_modActions->openExplorer({m_core->modList()->index(modIndex, 0)});
        return true;
      }
    } else if (keyEvent->modifiers() == Qt::ControlModifier &&
               (sortColumn() == PluginList::COL_PRIORITY ||
                sortColumn() == PluginList::COL_MODINDEX) &&
               (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) {
      return moveSelection(keyEvent->key());
    } else if (keyEvent->key() == Qt::Key_Space) {
      return toggleSelectionState();
    }
    return QTreeView::event(event);
  }
  return QTreeView::event(event);
}