summaryrefslogtreecommitdiff
path: root/src/instancemanager.cpp
blob: 849cdb5e88dfe1931704d37aac2a59229d4ae105 (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
/*
Copyright (C) 2016 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 "instancemanager.h"
#include "selectiondialog.h"
#include "settings.h"
#include "shared/appconfig.h"
#include "plugincontainer.h"
#include "env.h"
#include <report.h>
#include <iplugingame.h>
#include <utility.h>
#include <log.h>

#include <QCoreApplication>
#include <QDir>
#include <QStandardPaths>
#include <QInputDialog>
#include <QMessageBox>
#include <cstdint>

using namespace MOBase;

const QString Organization = "Mod Organizer Team";
const QString Application = "Mod Organizer";
const QString InstanceValue = "CurrentInstance";


InstanceManager::InstanceManager()
  : m_AppSettings(Organization, Application)
{
  updateRegistryKey();
}

InstanceManager &InstanceManager::instance()
{
  static InstanceManager s_Instance;
  return s_Instance;
}

void InstanceManager::updateRegistryKey()
{
  const QString OldOrganization = "Tannin";
  const QString OldApplication = "Mod Organizer";
  const QString OldInstanceValue = "CurrentInstance";

  const QString OldRootKey = "Software\\" + OldOrganization;

  if (env::registryValueExists(OldRootKey + "\\" + OldApplication, OldInstanceValue)) {
    QSettings old(OldOrganization, OldApplication);
    setCurrentInstance(old.value(OldInstanceValue).toString());
    old.remove(OldInstanceValue);
  }

  env::deleteRegistryKeyIfEmpty(OldRootKey);
}

void InstanceManager::overrideInstance(const QString& instanceName)
{
  m_overrideInstanceName = instanceName;
  m_overrideInstance = true;
}

void InstanceManager::overrideProfile(const QString& profileName)
{
  m_overrideProfileName = profileName;
  m_overrideProfile = true;
}

QString InstanceManager::currentInstance() const
{
  if (m_overrideInstance)
    return m_overrideInstanceName;
  else
    return m_AppSettings.value(InstanceValue, "").toString();
}

void InstanceManager::clearCurrentInstance()
{
  setCurrentInstance("");
  m_Reset = true;
  m_overrideInstance = false;
}

void InstanceManager::setCurrentInstance(const QString &name)
{
  m_AppSettings.setValue(InstanceValue, name);
}

bool InstanceManager::deleteLocalInstance(const QString& instanceId) const
{
  QString dir = instancePath(instanceId);

  const auto Recycle = QMessageBox::Save;
  const auto Delete = QMessageBox::Yes;
  const auto Cancel = QMessageBox::Cancel;

  const auto r = MOBase::TaskDialog()
    .title(QObject::tr("Deleting instance folder"))
    .main(QObject::tr("This will delete the instance folder."))
    .content(dir)
    .icon(QMessageBox::Warning)
    .button({QObject::tr("Move the folder to the recycle bin"), Recycle})
    .button({QObject::tr("Delete the folder permanently"), Delete})
    .button({QObject::tr("Cancel"), Cancel})
    .exec();

  std::wstring error;

  switch (r)
  {
    case Recycle:
    {
      if (MOBase::shellDelete(QStringList(dir), true)) {
        return true;
      }

      const auto e = GetLastError();
      error = formatSystemMessage(e);
      log::warn("failed to move to trash '{}', {}", dir, error);

      break;
    }

    case Delete:
    {
      if (MOBase::shellDelete(QStringList(dir), false)) {
        return true;
      }

      const auto e = GetLastError();
      error = formatSystemMessage(e);
      log::warn("failed to delete '{}', {}", dir, error);

      break;
    }

    default:
    {
      return true;
    }
  }

  QMessageBox::critical(
    nullptr, QObject::tr("Error"), QObject::tr(
      "Could not delete instance folder \"%1\".\n\n%2")
        .arg(dir).arg(error),
    QMessageBox::Ok);

  return false;
}

QString InstanceManager::manageInstances(const QStringList &instanceList) const
{
  SelectionDialog selection(QString("<h3>%1</h3><br>%2")
    .arg(QObject::tr("Select an instance to delete"))
    .arg(QObject::tr(
      "Deleting an instance will delete all the mods, downloads, profiles "
      "(including profile-specific saves) and anything in the overwrite "
      "folder.<br><br>"
      "Custom paths outside of the instance folder will not be deleted.")));

  for (const QString &instance : instanceList) {
    selection.addChoice(QIcon(":/MO/gui/multiply_red"), instance, "", instance);
  }

  if (selection.exec() == QDialog::Rejected) {
    return (chooseInstance(instanceNames()));
  }
  else {
    QString choice = selection.getChoiceData().toString();
    deleteLocalInstance(choice);
  }

  return(manageInstances(instanceNames()));
}

QString InstanceManager::queryInstanceName(const QStringList &instanceList) const
{
  QString instanceId;
  QString dialogText;
  while (instanceId.isEmpty()) {
    QInputDialog dialog;

	  dialog.setWindowTitle(QObject::tr("Enter a Name for the new Instance"));
    dialog.setLabelText(QObject::tr("Enter a new name or select one from the suggested list: \n"
                                    "(This is just a name for the Instance and can be whatever you wish,\n"
                                    " the actual game selection will happen on the next screen regardless of chosen name)"));
    // would be neat if we could take the names from the game plugins but
    // the required initialization order requires the ini file to be
    // available *before* we load plugins
    dialog.setComboBoxItems({ "NewName", "Fallout 4", "SkyrimSE", "Skyrim", "SkyrimVR", "Fallout 3",
                              "Fallout NV", "TTW", "FO4VR", "Oblivion", "Morrowind", "Enderal" });
    dialog.setComboBoxEditable(true);

    if (dialog.exec() == QDialog::Rejected) {
      throw MOBase::MyException(QObject::tr("Canceled"));
    }
    dialogText = dialog.textValue();
    instanceId = sanitizeInstanceName(dialogText);
    if (instanceId != dialogText) {
      if (QMessageBox::question( nullptr,
                                QObject::tr("Invalid instance name"),
                                QObject::tr("The instance name \"%1\" is invalid.  Use the name \"%2\" instead?").arg(dialogText,instanceId),
                                QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
        instanceId="";
        continue;
        }
    }

    bool alreadyExists=false;
    for (const QString &instance : instanceList) {
      if(instanceId==instance)
        alreadyExists=true;
    }
    if(alreadyExists)
    {
      QMessageBox msgBox;
      msgBox.setText( QObject::tr("The instance \"%1\" already exists.").arg(instanceId) );
      msgBox.setInformativeText(QObject::tr("Please choose a different instance name, like: \"%1 1\" .").arg(instanceId));
      msgBox.exec();
      instanceId="";
    }
  }
  return instanceId;
}


QString InstanceManager::chooseInstance(const QStringList &instanceList) const
{
  if (portableInstallIsLocked()) {
    return QString();
  }

  enum class Special : uint8_t {
    NewInstance,
    Portable,
    Manage
  };

  SelectionDialog selection(
      QString("<h3>%1</h3><br>%2")
          .arg(QObject::tr("Choose Instance"))
          .arg(QObject::tr(
              "Each Instance is a full set of MO data files (mods, "
              "downloads, profiles, configuration, ...). You can use multiple "
			  "instances for different games. Instances are stored in Appdata and can be accessed by all MO installations. "
			  "If your MO folder is writable, you can also store a single instance locally (called "
              "a Portable install, and all the MO data files will be inside the installation folder).")),
      nullptr);
  selection.disableCancel();
  for (const QString &instance : instanceList) {
    selection.addChoice(instance, "", instance);
  }

  selection.addChoice(QIcon(":/MO/gui/add"), QObject::tr("New"),
                      QObject::tr("Create a new instance."),
                      static_cast<uint8_t>(Special::NewInstance));

  if (QFileInfo(qApp->applicationDirPath()).isWritable()) {
    selection.addChoice(QIcon(":/MO/gui/package"), QObject::tr("Portable"),
                        QObject::tr("Use MO folder for data."),
                        static_cast<uint8_t>(Special::Portable));
  }

  selection.addChoice(QIcon(":/MO/gui/remove"), QObject::tr("Manage Instances"),
                        QObject::tr("Delete an Instance."),
                        static_cast<uint8_t>(Special::Manage));

  selection.setWindowFlags(selection.windowFlags() | Qt::WindowStaysOnTopHint);

  if (selection.exec() == QDialog::Rejected) {
    log::debug("rejected");
    throw MOBase::MyException(QObject::tr("Canceled"));
  }

  QVariant choice = selection.getChoiceData();

  if (choice.type() == QVariant::String) {
    return choice.toString();
  } else {
    switch (static_cast<Special>(choice.value<uint8_t>())) {
      case Special::NewInstance: return queryInstanceName(instanceList);
      case Special::Portable: return QString();
      case Special::Manage: {

        return(manageInstances(instanceNames()));
      }
      default: throw std::runtime_error("invalid selection");
    }
  }
}

QString InstanceManager::instancePath(const QString& instanceName) const
{
  return QDir::fromNativeSeparators(instancesPath() + "/" + instanceName);
}

QString InstanceManager::instancesPath() const
{
  return QDir::fromNativeSeparators(
        QStandardPaths::writableLocation(QStandardPaths::DataLocation));
}

std::vector<QDir> InstanceManager::instancePaths() const
{
  const std::set<QString> ignore = {
    "cache", "qtwebengine",
  };

  const QDir root(instancesPath());
  const auto dirs = root.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

  std::vector<QDir> list;

  for (auto&& d : dirs) {
    if (!ignore.contains(QFileInfo(d).fileName().toLower())) {
      list.push_back(root.filePath(d));
    }
  }

  return list;
}

QStringList InstanceManager::instanceNames() const
{
  QStringList list;

  for (auto&& d : instancePaths()) {
    list.push_back(d.dirName());
  }

  return list;
}


bool InstanceManager::isPortablePath(const QString& dataPath)
{
  return (dataPath == portablePath());
}

QString InstanceManager::portablePath()
{
  return qApp->applicationDirPath();
}

bool InstanceManager::portableInstall() const
{
  return QFile::exists(qApp->applicationDirPath() + "/" +
                       QString::fromStdWString(AppConfig::iniFileName()));
}


bool InstanceManager::portableInstallIsLocked() const
{
  return QFile::exists(qApp->applicationDirPath() + "/" +
                       QString::fromStdWString(AppConfig::portableLockFileName()));
}


bool InstanceManager::allowedToChangeInstance() const
{
  return !portableInstallIsLocked();
}


void InstanceManager::createDataPath(const QString &dataPath) const
{
  if (!QDir(dataPath).exists()) {
    if (!QDir().mkpath(dataPath)) {
      throw MOBase::MyException(
            QObject::tr("failed to create %1").arg(dataPath));
    } else {
      QMessageBox::information(
          nullptr, QObject::tr("Data directory created"),
          QObject::tr("New data directory created at %1. If you don't want to "
                      "store a lot of data there, reconfigure the storage "
                      "directories via settings.").arg(dataPath));
    }
  }
}


QString InstanceManager::determineDataPath()
{
  QString instanceId = currentInstance();
  if (portableInstallIsLocked())
  {
    instanceId.clear();
  }
  if (instanceId.isEmpty() && !m_Reset && (m_overrideInstance || portableInstall()))
  {
    // startup, apparently using portable mode before
    return qApp->applicationDirPath();
  }

  QString dataPath = QDir::fromNativeSeparators(
        QStandardPaths::writableLocation(QStandardPaths::DataLocation)
        + "/" + instanceId);


  if (!m_overrideInstance && (instanceId.isEmpty() || !QFileInfo::exists(dataPath))) {
    instanceId = chooseInstance(instanceNames());
    setCurrentInstance(instanceId);
    if (!instanceId.isEmpty()) {
      dataPath = QDir::fromNativeSeparators(
        QStandardPaths::writableLocation(QStandardPaths::DataLocation)
        + "/" + instanceId);
    }
  }

  if (instanceId.isEmpty()) {
    return qApp->applicationDirPath();
  } else {
    createDataPath(dataPath);

    return dataPath;
  }
}

QString InstanceManager::determineProfile(const Settings &settings)
{
  auto selectedProfileName = settings.game().selectedProfileName();

  if (m_overrideProfile) {
    log::debug("profile overwritten on command line");
    selectedProfileName = m_overrideProfileName;
  }

  if (!selectedProfileName) {
    log::debug("no configured profile");
    selectedProfileName = "Default";
  }

  return *selectedProfileName;
}

bool InstanceManager::determineGameEdition(
  Settings& settings, IPluginGame* game)
{
  QString edition;

  if (auto v=settings.game().edition()) {
    edition = *v;
  } else {
    QStringList editions = game->gameVariants();
    if (editions.size() < 2) {
      edition = "";
      return true;
    }

    SelectionDialog selection(
      QObject::tr("Please select the game edition you have (MO can't "
        "start the game correctly if this is set "
        "incorrectly!)"),
      nullptr);

    selection.setWindowFlag(Qt::WindowStaysOnTopHint, true);

    int index = 0;
    for (const QString &edition : editions) {
      selection.addChoice(edition, "", index++);
    }

    if (selection.exec() == QDialog::Rejected) {
      return false;
    }

    edition = selection.getChoiceString();
    settings.game().setEdition(edition);
  }

  game->setGameVariant(edition);

  return true;
}

MOBase::IPluginGame *selectGame(
  Settings &settings, QDir const &gamePath, MOBase::IPluginGame *game)
{
  settings.game().setName(game->gameName());

  QString gameDir = gamePath.absolutePath();
  game->setGamePath(gameDir);

  settings.game().setDirectory(gameDir);

  return game;
}

MOBase::IPluginGame* InstanceManager::determineCurrentGame(
  const QString& moPath, Settings& settings, const PluginContainer &plugins)
{
  //Determine what game we are running where. Be very paranoid in case the
  //user has done something odd.

  //If the game name has been set up, try to use that.
  const auto gameName = settings.game().name();
  const bool gameConfigured = (gameName.has_value() && *gameName != "");

  if (gameConfigured) {
    MOBase::IPluginGame *game = plugins.managedGame(*gameName);
    if (game == nullptr) {
      reportError(
        QObject::tr("Plugin to handle %1 no longer installed. An antivirus might have deleted files.")
        .arg(*gameName));

      return nullptr;
    }

    auto gamePath = settings.game().directory();
    if (!gamePath || *gamePath == "") {
      gamePath = game->gameDirectory().absolutePath();
    }

    QDir gameDir(*gamePath);
    QFileInfo directoryInfo(gameDir.path());

    if (directoryInfo.isSymLink()) {
      reportError(QObject::tr("The configured path to the game directory (%1) appears to be a symbolic (or other) link. "
        "This setup is incompatible with MO2's VFS and will not run correctly.").arg(*gamePath));
    }

    if (game->looksValid(gameDir)) {
      return selectGame(settings, gameDir, game);
    }
  }

  //If we've made it this far and the instance is already configured for a game, something has gone wrong.
  //Tell the user about it.
  if (gameConfigured) {
    const auto gamePath = settings.game().directory();

    reportError(
      QObject::tr("Could not use configuration settings for game \"%1\", path \"%2\".")
      .arg(*gameName).arg(gamePath ? *gamePath : ""));
  }

  SelectionDialog selection(gameConfigured ?
    QObject::tr("Please select the installation of %1 to manage").arg(*gameName) :
    QObject::tr("Please select the game to manage"), nullptr, QSize(32, 32));

  for (IPluginGame *game : plugins.plugins<IPluginGame>()) {
    //If a game is already configured, skip any plugins that are not for that game
    if (gameConfigured && gameName->compare(game->gameName(), Qt::CaseInsensitive) != 0)
      continue;

    //Only add games that are installed
    if (game->isInstalled()) {
      QString path = game->gameDirectory().absolutePath();
      selection.addChoice(game->gameIcon(), game->gameName(), path, QVariant::fromValue(game));
    }
  }

  selection.addChoice(QString("Browse..."), QString(), QVariant::fromValue(static_cast<IPluginGame *>(nullptr)));

  while (selection.exec() != QDialog::Rejected) {
    IPluginGame * game = selection.getChoiceData().value<IPluginGame *>();
    QString gamePath = selection.getChoiceDescription();
    QFileInfo directoryInfo(gamePath);
    if (directoryInfo.isSymLink()) {
      reportError(QObject::tr("The configured path to the game directory (%1) appears to be a symbolic (or other) link. "
        "This setup is incompatible with MO2's VFS and will not run correctly.").arg(gamePath));
    }
    if (game != nullptr) {
      return selectGame(settings, game->gameDirectory(), game);
    }

    gamePath = QFileDialog::getExistingDirectory(nullptr, gameConfigured ?
      QObject::tr("Please select the installation of %1 to manage").arg(*gameName) :
      QObject::tr("Please select the game to manage"),
      QString(), QFileDialog::ShowDirsOnly);

    if (!gamePath.isEmpty()) {
      QDir gameDir(gamePath);
      QFileInfo directoryInfo(gamePath);
      if (directoryInfo.isSymLink()) {
        reportError(QObject::tr("The configured path to the game directory (%1) appears to be a symbolic (or other) link. "
          "This setup is incompatible with MO2's VFS and will not run correctly.").arg(gamePath));
      }
      QList<IPluginGame *> possibleGames;
      for (IPluginGame * const game : plugins.plugins<IPluginGame>()) {
        //If a game is already configured, skip any plugins that are not for that game
        if (gameConfigured && gameName->compare(game->gameName(), Qt::CaseInsensitive) != 0)
          continue;

        //Only try plugins that look valid for this directory
        if (game->looksValid(gameDir)) {
          possibleGames.append(game);
        }
      }

      if (possibleGames.count() > 1) {
        SelectionDialog browseSelection(gameConfigured ?
          QObject::tr("Please select the installation of %1 to manage").arg(*gameName) :
          QObject::tr("Please select the game to manage"),
          nullptr, QSize(32, 32));

        for (IPluginGame *game : possibleGames) {
          browseSelection.addChoice(game->gameIcon(), game->gameName(), gamePath, QVariant::fromValue(game));
        }

        if (browseSelection.exec() == QDialog::Accepted) {
          return selectGame(settings, gameDir, browseSelection.getChoiceData().value<IPluginGame *>());
        } else {
          reportError(gameConfigured ?
            QObject::tr("Canceled finding %1 in \"%2\".").arg(*gameName).arg(gamePath) :
            QObject::tr("Canceled finding game in \"%1\".").arg(gamePath));
        }
      } else if(possibleGames.count() == 1) {
        return selectGame(settings, gameDir, possibleGames[0]);
      } else {
        if (gameConfigured) {
          reportError(
            QObject::tr("%1 not identified in \"%2\". The directory is required to contain the game binary.")
            .arg(*gameName).arg(gamePath));
        } else {
          QString supportedGames;

          for (IPluginGame * const game : plugins.plugins<IPluginGame>()) {
            supportedGames += "<li>" + game->gameName() + "</li>";
          }

          QString text = QObject::tr(
            "No game identified in \"%1\". The directory is required to "
            "contain the game binary.<br><br>"
            "<b>These are the games supported by Mod Organizer:</b>"
            "<ul>%2</ul>")
            .arg(gamePath)
            .arg(supportedGames);

          reportError(text);
        }
      }
    }
  }

  return nullptr;
}

QString InstanceManager::makeUniqueName(const QString& instanceName) const
{
  const QString sanitized = sanitizeInstanceName(instanceName);

  QString name = sanitized;
  for (int i=2; i<100; ++i) {
    if (!instanceExists(name)) {
      return name;
    }

    name = QString("%1 (%2)").arg(sanitized).arg(i);
  }

  return {};
}

bool InstanceManager::instanceExists(const QString& instanceName) const
{
  const QDir root = instancesPath();
  return root.exists(instanceName);
}

QString InstanceManager::sanitizeInstanceName(const QString &name) const
{
  QString new_name = name;

  // Restrict the allowed characters
  new_name = new_name.remove(QRegExp("[^A-Za-z0-9 _=+;!@#$%^'\\-\\.\\[\\]\\{\\}\\(\\)]"));

  // Don't end in spaces and periods
  new_name = new_name.remove(QRegExp("\\.*$"));
  new_name = new_name.remove(QRegExp(" *$"));

  // Recurse until stuff stops changing
  if (new_name != name) {
    return sanitizeInstanceName(new_name);
  }
  return new_name;
}