aboutsummaryrefslogtreecommitdiff
path: root/src/src/savestab.cpp
blob: d757a8352a571072cd19795392a3e14063855eb8 (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
#include "savestab.h"
#include "activatemodsdialog.h"
#include "organizercore.h"
#include "ui_mainwindow.h"
#include <iplugingame.h>
#include <isavegameinfowidget.h>
#include <localsavegames.h>
#include <new>
#include <report.h>

#include <QFile>
#include <QTextStream>

using namespace MOBase;

namespace
{
bool g_disableSaveTooltipsAfterOOM = false;

// Read a value from a Bethesda-style INI file without QSettings.
// QSettings::IniFormat interprets backslashes as line continuations,
// which corrupts values like "sLocalSavePath=__MO_Saves\".
QString readIniValueDirect(const QString& iniFile, const QString& section,
                           const QString& key)
{
  QFile file(iniFile);
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    return {};
  }

  const QString sectionHeader = "[" + section + "]";
  QTextStream in(&file);
  bool inSection = false;

  while (!in.atEnd()) {
    QString line = in.readLine().trimmed();
    if (line.startsWith('[') && line.endsWith(']')) {
      if (inSection)
        break;
      if (line.compare(sectionHeader, Qt::CaseInsensitive) == 0)
        inSection = true;
      continue;
    }

    if (inSection && !line.isEmpty() && !line.startsWith(';') &&
        !line.startsWith('#')) {
      int eqPos = line.indexOf('=');
      if (eqPos > 0) {
        QString existingKey = line.left(eqPos).trimmed();
        if (existingKey.compare(key, Qt::CaseInsensitive) == 0) {
          return line.mid(eqPos + 1).trimmed();
        }
      }
    }
  }

  return {};
}

QString sanitizeText(QString in, int maxLen = 200)
{
  for (int i = 0; i < in.size(); ++i) {
    const QChar c = in.at(i);
    // Replace control chars except common whitespace.
    if (c.unicode() < 0x20 && c != QChar('\n') && c != QChar('\r') && c != QChar('\t')) {
      in[i] = QChar('?');
    }
  }

  if (in.size() > maxLen) {
    in.truncate(maxLen);
    in += "...";
  }

  return in;
}

bool isLikelyCorruptSaveText(QString const& in)
{
  if (in.trimmed().isEmpty()) {
    return true;
  }

  int suspicious = 0;
  for (const QChar c : in) {
    if (c.unicode() == 0xFFFD || c.isNull() ||
        (!c.isPrint() && !c.isSpace())) {
      ++suspicious;
    }
  }

  return suspicious > (in.size() / 8);
}
}  // namespace

SavesTab::SavesTab(QWidget* window, OrganizerCore& core, Ui::MainWindow* mwui)
    : m_window(window), m_core(core), m_CurrentSaveView(nullptr),
      ui{.mainTabs=mwui->tabWidget, .tab=mwui->savesTab, .list=mwui->savegameList}
{
  m_SavesWatcherTimer.setSingleShot(true);
  m_SavesWatcherTimer.setInterval(500);

  ui.list->installEventFilter(this);
  ui.list->setMouseTracking(true);

  connect(&m_SavesWatcher, &QFileSystemWatcher::directoryChanged, [&] {
    m_SavesWatcherTimer.start();
  });

  connect(&m_SavesWatcherTimer, &QTimer::timeout, [&] {
    refreshSavesIfOpen();
  });

  connect(ui.list, &QWidget::customContextMenuRequested, [&](auto pos) {
    onContextMenu(pos);
  });

  connect(ui.list, &QTreeWidget::itemEntered, [&](auto* item) {
    saveSelectionChanged(item);
  });
}

bool SavesTab::eventFilter(QObject* object, QEvent* e)
{
  if (object == ui.list) {
    if (e->type() == QEvent::Leave || e->type() == QEvent::WindowDeactivate) {
      hideSaveGameInfo();
    } else if (e->type() == QEvent::KeyPress) {
      QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
      if (keyEvent->key() == Qt::Key_Delete) {
        deleteSavegame();
      }
    }
  }

  return false;
}

void SavesTab::displaySaveGameInfo(QTreeWidgetItem* newItem)
{
  if (g_disableSaveTooltipsAfterOOM) {
    return;
  }

  // don't display the widget if the main window doesn't have focus
  //
  // this goes against the standard behaviour for tooltips, which are displayed
  // on hover regardless of focus, but this widget is so large and busy that
  // it's probably better this way
  if (!m_window->isActiveWindow()) {
    return;
  }

  if (m_CurrentSaveView == nullptr) {
    auto info = m_core.gameFeatures().gameFeature<SaveGameInfo>();

    if (info != nullptr) {
      m_CurrentSaveView = info->getSaveGameWidget(m_window);
    }

    if (m_CurrentSaveView == nullptr) {
      return;
    }
  }

  try {
    m_CurrentSaveView->setSave(*m_SaveGames[ui.list->indexOfTopLevelItem(newItem)]);
  } catch (const std::bad_alloc&) {
    g_disableSaveTooltipsAfterOOM = true;
    log::error("insufficient memory while rendering save tooltip for '{}'",
               sanitizeText(newItem ? newItem->text(0) : QString()));
    reportError(QObject::tr("Save tooltip rendering was disabled for this session due "
                            "to low memory while parsing save metadata."));
    hideSaveGameInfo();
    return;
  } catch (const std::exception& e) {
    log::error("failed to render save tooltip: {}", e.what());
    hideSaveGameInfo();
    return;
  }

  QWindow* window = m_CurrentSaveView->window()->windowHandle();
  QRect screenRect;
  if (window == nullptr)
    screenRect = QGuiApplication::primaryScreen()->geometry();
  else
    screenRect = window->screen()->geometry();

  QPoint pos = QCursor::pos();
  if (pos.x() + m_CurrentSaveView->width() > screenRect.right()) {
    pos.rx() -= (m_CurrentSaveView->width() + 2);
  } else {
    pos.rx() += 5;
  }

  if (pos.y() + m_CurrentSaveView->height() > screenRect.bottom()) {
    pos.ry() -= (m_CurrentSaveView->height() + 10);
  } else {
    pos.ry() += 20;
  }
  m_CurrentSaveView->move(pos);

  m_CurrentSaveView->show();
  m_CurrentSaveView->setProperty("displayItem",
                                 QVariant::fromValue(static_cast<void*>(newItem)));
}

void SavesTab::saveSelectionChanged(QTreeWidgetItem* newItem)
{
  if (newItem == nullptr) {
    hideSaveGameInfo();
  } else if (m_CurrentSaveView == nullptr ||
             newItem != m_CurrentSaveView->property("displayItem").value<void*>()) {
    displaySaveGameInfo(newItem);
  }
}

void SavesTab::hideSaveGameInfo()
{
  if (m_CurrentSaveView != nullptr) {
    m_CurrentSaveView->deleteLater();
    m_CurrentSaveView = nullptr;
  }
}

void SavesTab::refreshSavesIfOpen()
{
  if (ui.mainTabs->currentWidget() == ui.tab) {
    refreshSaveList();
  }
}

QDir SavesTab::currentSavesDir() const
{
  // TODO: This code should probably be handled by the game plugins
  QDir savesDir;
  if (m_core.currentProfile()->localSavesEnabled()) {
    savesDir.setPath(m_core.currentProfile()->savePath());
  } else {
    auto iniFiles = m_core.managedGame()->iniFiles();

    if (iniFiles.isEmpty() ||
        m_core.gameFeatures().gameFeature<LocalSavegames>() == nullptr) {
      return m_core.managedGame()->savesDirectory();
    }

    QString iniPath = m_core.currentProfile()->absoluteIniFilePath(iniFiles[0]);

    // Read directly without QSettings — QSettings::IniFormat interprets
    // trailing backslashes as line continuations, corrupting values like
    // "sLocalSavePath=__MO_Saves\".
    QString savePath = readIniValueDirect(iniPath, "General", "sLocalSavePath");
    // Strip trailing path separators (Bethesda INIs use "Saves\" with a
    // trailing backslash that is part of the value, not a continuation).
    while (savePath.endsWith('\\') || savePath.endsWith('/')) {
      savePath.chop(1);
    }
    if (!savePath.isEmpty() &&
        savePath.compare("__MO_Saves", Qt::CaseInsensitive) != 0) {
      savesDir.setPath(
          m_core.managedGame()->documentsDirectory().absoluteFilePath(savePath));
    } else {
      savesDir = m_core.managedGame()->savesDirectory();
    }
  }

  return savesDir;
}

void SavesTab::startMonitorSaves()
{
  stopMonitorSaves();

  QDir savesDir = currentSavesDir();

  m_SavesWatcher.addPath(savesDir.absolutePath());
}

void SavesTab::stopMonitorSaves()
{
  if (!m_SavesWatcher.directories().empty()) {
    m_SavesWatcher.removePaths(m_SavesWatcher.directories());
  }
}

void SavesTab::refreshSaveList()
{
  TimeThis tt("MainWindow::refreshSaveList()");

  startMonitorSaves();  // re-starts monitoring

  try {
    QDir savesDir = currentSavesDir();
    MOBase::log::debug("reading save games from {}", savesDir.absolutePath());
    m_SaveGames = m_core.managedGame()->listSaves(savesDir);
    std::sort(m_SaveGames.begin(), m_SaveGames.end(),
              [](auto const& lhs, auto const& rhs) {
                return lhs->getCreationTime() > rhs->getCreationTime();
              });

    ui.list->clear();
    for (auto& save : m_SaveGames) {
      auto relpath = savesDir.relativeFilePath(save->getFilepath());
      const auto rawName = save->getName();
      auto display       = sanitizeText(rawName, 300);
      if (display.trimmed().isEmpty() || isLikelyCorruptSaveText(rawName)) {
        display = sanitizeText(QFileInfo(save->getFilepath()).completeBaseName(), 300);
      }
      ui.list->addTopLevelItem(new QTreeWidgetItem(ui.list, {display, relpath}));
    }
  } catch (std::exception& e) {
    // listSaves() can throw
    log::error("{}", e.what());
  }
}

void SavesTab::deleteSavegame()
{
  auto info = m_core.gameFeatures().gameFeature<SaveGameInfo>();

  QString savesMsgLabel;
  QStringList deleteFiles;

  int count = 0;

  for (const QModelIndex& idx : ui.list->selectionModel()->selectedRows()) {

    auto& saveGame = m_SaveGames[idx.row()];

    if (count < 10) {
      savesMsgLabel +=
          "<li>" + QFileInfo(saveGame->getFilepath()).completeBaseName() + "</li>";
    }
    ++count;

    deleteFiles += saveGame->allFiles();
  }

  if (count > 10) {
    savesMsgLabel += "<li><i>... " + tr("%1 more").arg(count - 10) + "</i></li>";
  }

  if (QMessageBox::question(
          m_window, tr("Confirm"),
          tr("Are you sure you want to remove the following %n save(s)?<br>"
             "<ul>%1</ul><br>"
             "Removed saves will be sent to the Recycle Bin.",
             "", count)
              .arg(savesMsgLabel),
          QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
    shellDelete(deleteFiles, true);  // recycle bin delete.
    refreshSaveList();
  }
}

void SavesTab::onContextMenu(const QPoint& pos)
{
  QItemSelectionModel* selection = ui.list->selectionModel();

  if (!selection->hasSelection()) {
    return;
  }

  QMenu menu;

  auto info = m_core.gameFeatures().gameFeature<SaveGameInfo>();
  if (info != nullptr) {
    QAction* action = menu.addAction(tr("Fix enabled mods..."));
    action->setEnabled(false);
    if (selection->selectedRows().count() == 1) {
      auto& save = m_SaveGames[selection->selectedRows()[0].row()];
      SaveGameInfo::MissingAssets missing = info->getMissingAssets(*save);
      if (!missing.empty()) {
        connect(action, &QAction::triggered, this, [this, missing] {
          fixMods(missing);
        });
        action->setEnabled(true);
      }
    }
  }

  QString deleteMenuLabel =
      tr("Delete %n save(s)", "", selection->selectedRows().count());
  menu.addAction(deleteMenuLabel, [&] {
    deleteSavegame();
  });

  menu.addAction(tr("Open in Explorer..."), [&] {
    openInExplorer();
  });

  menu.exec(ui.list->viewport()->mapToGlobal(pos));
}

void SavesTab::fixMods(SaveGameInfo::MissingAssets const& missingAssets)
{
  ActivateModsDialog dialog(missingAssets, m_window);
  if (dialog.exec() == QDialog::Accepted) {
    // activate the required mods, then enable all esps
    std::set<QString> modsToActivate = dialog.getModsToActivate();
    for (std::set<QString>::iterator iter = modsToActivate.begin();
         iter != modsToActivate.end(); ++iter) {
      if ((*iter != "<data>") && (*iter != "<overwrite>")) {
        unsigned int modIndex = ModInfo::getIndex(*iter);
        m_core.currentProfile()->setModEnabled(modIndex, true);
      }
    }

    m_core.currentProfile()->writeModlist();
    m_core.refreshLists();

    std::set<QString> espsToActivate = dialog.getESPsToActivate();
    for (std::set<QString>::iterator iter = espsToActivate.begin();
         iter != espsToActivate.end(); ++iter) {
      m_core.pluginList()->enableESP(*iter);
    }

    m_core.saveCurrentLists();
  }
}

void SavesTab::openInExplorer()
{
  auto info = m_core.gameFeatures().gameFeature<SaveGameInfo>();

  const auto sel = ui.list->selectionModel()->selectedRows();
  if (sel.empty()) {
    return;
  }

  auto& saveGame = m_SaveGames[sel[0].row()];
  shell::Explore(saveGame->getFilepath());
}