summaryrefslogtreecommitdiff
path: root/src/profilesdialog.cpp
blob: 24eddc2047ac730011da8edfc7fd26f60809b770 (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
/*
Copyright (C) 2012 Sebastian Herbord. All rights reserved.

This file is part of Mod Organizer.

Mod Organizer is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Mod Organizer is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mod Organizer.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "profilesdialog.h"
#include "ui_profilesdialog.h"

#include "bsainvalidation.h"
#include "filesystemutilities.h"
#include "game_features.h"
#include "iplugingame.h"
#include "localsavegames.h"
#include "organizercore.h"
#include "profile.h"
#include "profileinputdialog.h"
#include "report.h"
#include "settings.h"
#include "shared/appconfig.h"
#include "transfersavesdialog.h"

#include <QDir>
#include <QDirIterator>
#include <QInputDialog>
#include <QLineEdit>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QWhatsThis>

#include <Windows.h>

#include <exception>

using namespace MOBase;
using namespace MOShared;

Q_DECLARE_METATYPE(Profile::Ptr)

ProfilesDialog::ProfilesDialog(const QString& profileName, OrganizerCore& organizer,
                               QWidget* parent)
    : TutorableDialog("Profiles", parent), ui(new Ui::ProfilesDialog),
      m_GameFeatures(organizer.gameFeatures()), m_FailState(false),
      m_Game(organizer.managedGame()), m_ActiveProfileName("")
{
  ui->setupUi(this);

  QDir profilesDir(Settings::instance().paths().profiles());
  profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);

  QDirIterator profileIter(profilesDir);

  while (profileIter.hasNext()) {
    profileIter.next();
    QListWidgetItem* item = addItem(profileIter.filePath());
    if (profileName == profileIter.fileName()) {
      ui->profilesList->setCurrentItem(item);
      m_ActiveProfileName = profileName;
    }
  }

  auto invalidation = m_GameFeatures.gameFeature<BSAInvalidation>();
  if (invalidation == nullptr) {
    ui->invalidationBox->setToolTip(
        tr("Archive invalidation isn't required for this game."));
    ui->invalidationBox->setEnabled(false);
  }

  if (!m_GameFeatures.gameFeature<LocalSavegames>()) {
    ui->localSavesBox->setToolTip(
        tr("This game does not support profile-specific game saves."));
    ui->localSavesBox->setEnabled(false);
  }

  connect(this, &ProfilesDialog::profileCreated, &organizer,
          &OrganizerCore::profileCreated);
  connect(this, &ProfilesDialog::profileRenamed, &organizer,
          &OrganizerCore::profileRenamed);
  connect(this, &ProfilesDialog::profileRemoved, &organizer,
          &OrganizerCore::profileRemoved);
}

ProfilesDialog::~ProfilesDialog()
{
  delete ui;
}

int ProfilesDialog::exec()
{
  GeometrySaver gs(Settings::instance(), this);
  return QDialog::exec();
}

void ProfilesDialog::showEvent(QShowEvent* event)
{
  TutorableDialog::showEvent(event);

  if (ui->profilesList->count() == 0) {
    QPoint pos = ui->profilesList->mapToGlobal(QPoint(0, 0));
    pos.rx() += ui->profilesList->width() / 2;
    pos.ry() += (ui->profilesList->height() / 2) - 20;
    QWhatsThis::showText(
        pos,
        QObject::tr(
            "Before you can use ModOrganizer, you need to create at least one profile. "
            "ATTENTION: Run the game at least once before creating a profile!"),
        ui->profilesList);
  }
}

void ProfilesDialog::on_close_clicked()
{
  close();
}

void ProfilesDialog::on_select_clicked()
{
  const Profile::Ptr currentProfile =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();

  if (!currentProfile) {
    return;
  }

  m_Selected = currentProfile->name();
  close();
}

std::optional<QString> ProfilesDialog::selectedProfile() const
{
  return m_Selected;
}

QListWidgetItem* ProfilesDialog::addItem(const QString& name)
{
  QDir profileDir(name);
  QListWidgetItem* newItem =
      new QListWidgetItem(profileDir.dirName(), ui->profilesList);
  try {
    newItem->setData(Qt::UserRole, QVariant::fromValue(Profile::Ptr(new Profile(
                                       profileDir, m_Game, m_GameFeatures))));
    m_FailState = false;
  } catch (const std::exception& e) {
    reportError(tr("failed to create profile: %1").arg(e.what()));
  }
  return newItem;
}

void ProfilesDialog::createProfile(const QString& name, bool useDefaultSettings)
{
  try {
    auto profile =
        Profile::Ptr(new Profile(name, m_Game, m_GameFeatures, useDefaultSettings));
    QListWidgetItem* newItem = new QListWidgetItem(name, ui->profilesList);
    newItem->setData(Qt::UserRole, QVariant::fromValue(profile));
    ui->profilesList->addItem(newItem);
    m_FailState = false;
    ui->profilesList->setCurrentItem(newItem);
    emit profileCreated(profile.get());
  } catch (const std::exception&) {
    m_FailState = true;
    throw;
  }
}

void ProfilesDialog::createProfile(const QString& name, const Profile& reference)
{
  try {
    auto profile = Profile::Ptr(Profile::createPtrFrom(name, reference, m_Game));
    QListWidgetItem* newItem = new QListWidgetItem(name, ui->profilesList);
    newItem->setData(Qt::UserRole, QVariant::fromValue(profile));
    ui->profilesList->addItem(newItem);
    m_FailState = false;
    ui->profilesList->setCurrentItem(newItem);
    emit profileCreated(profile.get());
  } catch (const std::exception&) {
    m_FailState = true;
    throw;
  }
}

void ProfilesDialog::on_addProfileButton_clicked()
{
  ProfileInputDialog dialog(this);
  bool okClicked = dialog.exec();
  QString name   = dialog.getName();

  if (okClicked && (name.size() > 0)) {
    try {
      createProfile(name, dialog.getPreferDefaultSettings());
    } catch (const std::exception& e) {
      reportError(tr("failed to create profile: %1").arg(e.what()));
    }
  }
}

void ProfilesDialog::on_copyProfileButton_clicked()
{
  bool okClicked;
  QString name = QInputDialog::getText(this, tr("Name"),
                                       tr("Please enter a name for the new profile"),
                                       QLineEdit::Normal, QString(), &okClicked);
  if (okClicked) {
    if (fixDirectoryName(name)) {
      try {
        const Profile::Ptr currentProfile =
            ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();
        createProfile(name, *currentProfile);
      } catch (const std::exception& e) {
        reportError(tr("failed to copy profile: %1").arg(e.what()));
      }
    } else {
      QMessageBox::warning(this, tr("Invalid name"), tr("Invalid profile name"));
    }
  }
}

void ProfilesDialog::on_removeProfileButton_clicked()
{
  Profile::Ptr profileToDelete =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();
  if (profileToDelete->name() == m_ActiveProfileName) {
    QMessageBox::warning(this, tr("Deleting active profile"),
                         tr("Unable to delete active profile.  Please change to a "
                            "different profile first."));
    return;
  }

  QMessageBox confirmBox(QMessageBox::Question, tr("Confirm"),
                         tr("Are you sure you want to remove this profile (including "
                            "profile-specific save games, if any)?"),
                         QMessageBox::Yes | QMessageBox::No, this);

  if (confirmBox.exec() == QMessageBox::Yes) {
    QString profilePath;
    if (profileToDelete.get() == nullptr) {
      profilePath = Settings::instance().paths().profiles() + "/" +
                    ui->profilesList->currentItem()->text();
      if (QMessageBox::question(
              this, tr("Profile broken"),
              tr("This profile you're about to delete seems to be broken or the path "
                 "is invalid. "
                 "I'm about to delete the following folder: \"%1\". Proceed?")
                  .arg(profilePath),
              QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
        return;
      }
    } else {
      // on destruction, the profile object would write the profile.ini file again, so
      // we have to get rid of the it before deleting the directory
      profilePath = profileToDelete->absolutePath();
    }
    QListWidgetItem* item = ui->profilesList->takeItem(ui->profilesList->currentRow());
    if (item != nullptr) {
      delete item;
    }
    if (!shellDelete(QStringList(profilePath))) {
      log::warn("Failed to shell-delete \"{}\" (errorcode {}), trying regular delete",
                profilePath, ::GetLastError());
      if (!removeDir(profilePath)) {
        log::warn("regular delete failed too");
      }
    }

    emit profileRemoved(profileToDelete->name());
  }
}

void ProfilesDialog::on_renameButton_clicked()
{
  Profile::Ptr currentProfile =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();

  if (currentProfile->name() == m_ActiveProfileName) {
    QMessageBox::warning(this, tr("Renaming active profile"),
                         tr("The active profile cannot be renamed. Please change to a "
                            "different profile first."));
    return;
  }

  bool valid = false;
  QString name;

  while (!valid) {
    bool ok = false;
    name    = QInputDialog::getText(this, tr("Rename Profile"), tr("New Name"),
                                    QLineEdit::Normal, currentProfile->name(), &ok);
    valid   = fixDirectoryName(name);
    if (!ok) {
      return;
    }
  }

  ui->profilesList->currentItem()->setText(name);

  QString oldName = currentProfile->name();
  currentProfile->rename(name);

  emit profileRenamed(currentProfile.get(), oldName, name);
}

void ProfilesDialog::on_invalidationBox_stateChanged(int state)
{
  QListWidgetItem* currentItem = ui->profilesList->currentItem();
  if (currentItem == nullptr) {
    return;
  }
  if (!ui->invalidationBox->isEnabled()) {
    return;
  }
  try {
    QVariant currentProfileVariant = currentItem->data(Qt::UserRole);
    if (!currentProfileVariant.isValid() || currentProfileVariant.isNull()) {
      return;
    }
    const Profile::Ptr currentProfile =
        currentItem->data(Qt::UserRole).value<Profile::Ptr>();
    if (state == Qt::Unchecked) {
      currentProfile->deactivateInvalidation();
    } else {
      currentProfile->activateInvalidation();
    }
  } catch (const std::exception& e) {
    reportError(tr("failed to change archive invalidation state: %1").arg(e.what()));
  }
}

void ProfilesDialog::on_profilesList_currentItemChanged(QListWidgetItem* current,
                                                        QListWidgetItem*)
{
  if (current != nullptr) {
    if (!current->data(Qt::UserRole).isValid())
      return;
    const Profile::Ptr currentProfile =
        current->data(Qt::UserRole).value<Profile::Ptr>();

    try {
      bool invalidationSupported = false;
      ui->invalidationBox->blockSignals(true);
      ui->invalidationBox->setChecked(
          currentProfile->invalidationActive(&invalidationSupported));
      ui->invalidationBox->setEnabled(invalidationSupported);
      ui->invalidationBox->blockSignals(false);

      bool localSaves = currentProfile->localSavesEnabled();
      ui->transferButton->setEnabled(localSaves);
      // prevent the stateChanged-event for the saves-box from triggering, otherwise it
      // may think local saves were disabled and delete the files/rename the dir
      ui->localSavesBox->blockSignals(true);
      ui->localSavesBox->setChecked(localSaves);
      ui->localSavesBox->blockSignals(false);

      ui->copyProfileButton->setEnabled(true);
      ui->removeProfileButton->setEnabled(true);
      ui->renameButton->setEnabled(true);

      ui->localIniFilesBox->blockSignals(true);
      ui->localIniFilesBox->setChecked(currentProfile->localSettingsEnabled());
      ui->localIniFilesBox->blockSignals(false);
    } catch (const std::exception& E) {
      reportError(
          tr("failed to determine if invalidation is active: %1").arg(E.what()));
      ui->copyProfileButton->setEnabled(false);
      ui->removeProfileButton->setEnabled(false);
      ui->renameButton->setEnabled(false);
      ui->invalidationBox->setChecked(false);
    }
  } else {
    ui->invalidationBox->setChecked(false);
    ui->copyProfileButton->setEnabled(false);
    ui->removeProfileButton->setEnabled(false);
    ui->renameButton->setEnabled(false);
  }
}

void ProfilesDialog::on_profilesList_itemActivated(QListWidgetItem* item)
{
  on_select_clicked();
}

void ProfilesDialog::on_localSavesBox_stateChanged(int state)
{
  Profile::Ptr currentProfile =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();

  if (currentProfile->enableLocalSaves(state == Qt::Checked)) {
    ui->transferButton->setEnabled(state == Qt::Checked);
  } else {
    // revert checkbox-state
    ui->localSavesBox->setChecked(state != Qt::Checked);
  }
}

void ProfilesDialog::on_transferButton_clicked()
{
  const Profile::Ptr currentProfile =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();
  TransferSavesDialog transferDialog(*currentProfile, m_Game, this);
  transferDialog.exec();
}

void ProfilesDialog::on_localIniFilesBox_stateChanged(int state)
{
  Profile::Ptr currentProfile =
      ui->profilesList->currentItem()->data(Qt::UserRole).value<Profile::Ptr>();

  if (!currentProfile->enableLocalSettings(state == Qt::Checked)) {
    // revert checkbox-state
    ui->localIniFilesBox->setChecked(state != Qt::Checked);
  }
}