summaryrefslogtreecommitdiff
path: root/src/editexecutablesdialog.cpp
blob: 8a01b9f0337a1f7a5573f13ddb74421b31a3bf67 (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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
/*
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 "editexecutablesdialog.h"
#include "filedialogmemory.h"
#include "forcedloaddialog.h"
#include "modlist.h"
#include "organizercore.h"
#include "spawn.h"
#include "ui_editexecutablesdialog.h"

#include <QMessageBox>
#include <Shellapi.h>
#include <algorithm>
#include <utility.h>

using namespace MOBase;
using namespace MOShared;

class IgnoreChanges
{
public:
  IgnoreChanges(EditExecutablesDialog* d) : m_dialog(d)
  {
    m_dialog->m_settingUI = true;
  }

  ~IgnoreChanges() { m_dialog->m_settingUI = false; }

  IgnoreChanges(const IgnoreChanges&)            = delete;
  IgnoreChanges& operator=(const IgnoreChanges&) = delete;

private:
  EditExecutablesDialog* m_dialog;
};

EditExecutablesDialog::EditExecutablesDialog(OrganizerCore& oc, int sel,
                                             QWidget* parent)
    : TutorableDialog("EditExecutables", parent), ui(new Ui::EditExecutablesDialog),
      m_organizerCore(oc), m_originalExecutables(*oc.executablesList()),
      m_executablesList(*oc.executablesList()), m_settingUI(false)
{
  ui->setupUi(this);
  ui->splitter->setSizes({200, 1});
  ui->splitter->setStretchFactor(0, 0);
  ui->splitter->setStretchFactor(1, 1);

  loadCustomOverwrites();
  loadForcedLibraries();

  QStringList modNames;

  for (auto&& m : m_organizerCore.modList()->allMods()) {
    auto mod = ModInfo::getByName(m);
    if (!mod->hasAnyOfTheseFlags({ModInfo::FLAG_FOREIGN, ModInfo::FLAG_BACKUP,
                                  ModInfo::FLAG_OVERWRITE, ModInfo::FLAG_SEPARATOR})) {
      ui->mods->addItem(m);
      modNames.push_back(m);
    }
  }

  auto* c = new QCompleter(modNames);
  c->setCaseSensitivity(Qt::CaseInsensitive);
  c->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
  ui->mods->setCompleter(c);

  fillList();
  setDirty(false);

  if (sel >= 0 && sel < ui->list->count()) {
    selectIndex(sel);
  }

  auto* m = new QMenu;
  m->addAction(tr("Add from file..."), [&] {
    addFromFile();
  });
  m->addAction(tr("Add empty"), [&] {
    addEmpty();
  });
  m->addAction(tr("Clone selected"), [&] {
    clone();
  });
  ui->add->setMenu(m);

  // some widgets need to do more than just save() and have their own handler
  connect(ui->binary, &QLineEdit::textChanged, [&] {
    save();
  });
  connect(ui->workingDirectory, &QLineEdit::textChanged, [&] {
    save();
  });
  connect(ui->arguments, &QLineEdit::textChanged, [&] {
    save();
  });
  connect(ui->steamAppID, &QLineEdit::textChanged, [&] {
    save();
  });
  connect(ui->mods, &QComboBox::currentTextChanged, [&] {
    save();
  });
  connect(ui->useApplicationIcon, &QCheckBox::toggled, [&] {
    save();
  });
  connect(ui->hide, &QCheckBox::toggled, [&] {
    save();
  });
  connect(ui->list->model(), &QAbstractItemModel::rowsMoved, [&] {
    saveOrder();
  });
}

EditExecutablesDialog::~EditExecutablesDialog() = default;

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

void EditExecutablesDialog::loadCustomOverwrites()
{
  const auto* p = m_organizerCore.currentProfile();

  for (const auto& e : m_executablesList) {
    const auto s = p->setting("custom_overwrites", e.title()).toString();

    if (!s.isEmpty()) {
      m_customOverwrites.set(e.title(), true, s);
    }
  }
}

void EditExecutablesDialog::loadForcedLibraries()
{
  const auto* p = m_organizerCore.currentProfile();

  for (const auto& e : m_executablesList) {
    m_forcedLibraries.set(e.title(), p->forcedLibrariesEnabled(e.title()),
                          p->determineForcedLibraries(e.title()));
  }
}

ExecutablesList EditExecutablesDialog::getExecutablesList() const
{
  ExecutablesList newList;

  // make sure the executables are in the same order as in the list
  for (int i = 0; i < ui->list->count(); ++i) {
    const auto& title = ui->list->item(i)->text();

    auto itor = m_executablesList.find(title);

    if (itor == m_executablesList.end()) {
      log::warn("getExecutablesList(): executable '{}' not found", title);
      continue;
    }

    newList.setExecutable(*itor);
  }

  return newList;
}

const EditExecutablesDialog::CustomOverwrites&
EditExecutablesDialog::getCustomOverwrites() const
{
  return m_customOverwrites;
}

const EditExecutablesDialog::ForcedLibraries&
EditExecutablesDialog::getForcedLibraries() const
{
  return m_forcedLibraries;
}

bool EditExecutablesDialog::checkOutputMods(const ExecutablesList& exes)
{
  // make sure the output mods for exes exist since the combobox is editable
  //
  // it'd be convenient for users to automatically create mods here if they're
  // not found, but this is a can of worms: it would require a refresh
  // because getIndex() still won't find it after calling
  // OrganizerCore::createMod(), which is a problem if the user just clicked
  // Apply and continued doing things
  //
  // triggering a refresh while this dialog is up doesn't sound like a very
  // smart thing to do for now, so this just shows an error

  for (const auto& e : exes) {
    auto modName = m_customOverwrites.find(e.title());

    if (modName && modName->enabled) {
      if (modName->value.isEmpty()) {
        QMessageBox::critical(this, tr("Empty output mod"),
                              tr("The output mod for %2 is empty.").arg(e.title()));

        return false;
      } else if (ModInfo::getIndex(modName->value) == UINT_MAX) {
        QMessageBox::critical(this, tr("Output mod not found"),
                              tr("The output mod '%1' for %2 does not exist.")
                                  .arg(modName->value)
                                  .arg(e.title()));

        return false;
      }
    }
  }

  return true;
}

bool EditExecutablesDialog::commitChanges()
{
  const auto newExecutables = getExecutablesList();

  if (!checkOutputMods(newExecutables)) {
    return false;
  }

  auto* profile = m_organizerCore.currentProfile();

  // remove all the custom overwrites and forced libraries
  for (const auto& e : m_originalExecutables) {
    profile->removeSetting("custom_overwrites", e.title());
    profile->removeForcedLibraries(e.title());
  }

  // set the new custom overwrites and forced libraries
  for (const auto& e : newExecutables) {
    if (auto modName = m_customOverwrites.find(e.title())) {
      if (modName && modName->enabled) {
        profile->storeSetting("custom_overwrites", e.title(), modName->value);
      }
    }

    if (auto libraryList = m_forcedLibraries.find(e.title())) {
      if (libraryList && !libraryList->value.empty()) {
        profile->setForcedLibrariesEnabled(e.title(), libraryList->enabled);
        profile->storeForcedLibraries(e.title(), libraryList->value);
      }
    }
  }

  // set the new executables list
  m_organizerCore.setExecutablesList(newExecutables);

  setDirty(false);

  return true;
}

void EditExecutablesDialog::setDirty(bool b)
{
  if (auto* button = ui->buttons->button(QDialogButtonBox::Apply)) {
    button->setEnabled(b);
  }
}

void EditExecutablesDialog::selectIndex(int i)
{
  if (i >= 0 && i < ui->list->count()) {
    ui->list->selectionModel()->setCurrentIndex(ui->list->model()->index(i, 0),
                                                QItemSelectionModel::ClearAndSelect);
  }
}

QListWidgetItem* EditExecutablesDialog::selectedItem()
{
  const auto selection = ui->list->selectedItems();

  if (selection.empty()) {
    return nullptr;
  }

  return selection[0];
}

Executable* EditExecutablesDialog::selectedExe()
{
  auto* item = selectedItem();
  if (!item) {
    return nullptr;
  }

  const auto& title = item->text();
  auto itor         = m_executablesList.find(title);

  if (itor == m_executablesList.end()) {
    return nullptr;
  }

  return &*itor;
}

void EditExecutablesDialog::fillList()
{
  ui->list->clear();

  for (const auto& exe : m_executablesList) {
    ui->list->addItem(createListItem(exe));
  }

  // select the first one in the list, if any
  if (ui->list->count() > 0) {
    selectIndex(0);
  } else {
    updateUI(nullptr, nullptr);
  }
}

QListWidgetItem* EditExecutablesDialog::createListItem(const Executable& exe)
{
  return new QListWidgetItem(exe.title());
}

void EditExecutablesDialog::updateUI(const QListWidgetItem* item, const Executable* e)
{
  // the ui is currently being set, ignore changes
  IgnoreChanges c(this);

  if (e) {
    setEdits(*e);
  } else {
    clearEdits();
  }

  setButtons(item, e);
}

void EditExecutablesDialog::setButtons(const QListWidgetItem* item, const Executable* e)
{
  // add and remove are always enabled

  if (item) {
    ui->up->setEnabled(canMove(item, -1));
    ui->down->setEnabled(canMove(item, +1));
  } else {
    ui->up->setEnabled(false);
    ui->down->setEnabled(false);
  }
}

void EditExecutablesDialog::clearEdits()
{
  ui->title->clear();
  ui->title->setEnabled(false);
  ui->binary->clear();
  ui->binary->setEnabled(false);
  ui->browseBinary->setEnabled(false);
  ui->workingDirectory->clear();
  ui->workingDirectory->setEnabled(false);
  ui->browseWorkingDirectory->setEnabled(false);
  ui->arguments->clear();
  ui->arguments->setEnabled(false);
  ui->overwriteSteamAppID->setEnabled(false);
  ui->overwriteSteamAppID->setChecked(false);
  ui->steamAppID->setEnabled(false);
  ui->steamAppID->clear();
  ui->createFilesInMod->setEnabled(false);
  ui->createFilesInMod->setChecked(false);
  ui->mods->setEnabled(false);
  ui->mods->setCurrentIndex(-1);
  ui->forceLoadLibraries->setEnabled(false);
  ui->forceLoadLibraries->setChecked(false);
  ui->configureLibraries->setEnabled(false);
  ui->useApplicationIcon->setEnabled(false);
  ui->useApplicationIcon->setChecked(false);
  ui->hide->setEnabled(false);
  ui->hide->setChecked(false);

  m_lastGoodTitle = "";
}

void EditExecutablesDialog::setEdits(const Executable& e)
{
  ui->title->setText(e.title());
  ui->binary->setText(QDir::toNativeSeparators(e.binaryInfo().filePath()));
  ui->workingDirectory->setText(QDir::toNativeSeparators(e.workingDirectory()));
  ui->arguments->setText(e.arguments());
  ui->overwriteSteamAppID->setChecked(!e.steamAppID().isEmpty());
  ui->steamAppID->setEnabled(!e.steamAppID().isEmpty());
  ui->steamAppID->setText(e.steamAppID());
  ui->useApplicationIcon->setChecked(e.usesOwnIcon());
  ui->hide->setChecked(e.hide());

  m_lastGoodTitle = e.title();

  {
    int modIndex = -1;

    const auto modName = m_customOverwrites.find(e.title());

    if (modName && !modName->value.isEmpty()) {
      modIndex = ui->mods->findText(modName->value);

      if (modIndex == -1) {
        log::warn("executable '{}' uses mod '{}' as a custom overwrite, but that mod "
                  "doesn't exist",
                  e.title(), modName->value);
      }
    }

    const bool hasCustomOverwrites = (modName && modName->enabled);

    ui->createFilesInMod->setChecked(hasCustomOverwrites);
    ui->mods->setEnabled(hasCustomOverwrites);
    ui->mods->setCurrentIndex(modIndex);
  }

  {
    const auto libraryList        = m_forcedLibraries.find(e.title());
    const bool hasForcedLibraries = (libraryList && libraryList->enabled);

    ui->forceLoadLibraries->setChecked(hasForcedLibraries);
    ui->configureLibraries->setEnabled(hasForcedLibraries);
  }

  // always enabled
  ui->title->setEnabled(true);
  ui->binary->setEnabled(true);
  ui->browseBinary->setEnabled(true);
  ui->workingDirectory->setEnabled(true);
  ui->browseWorkingDirectory->setEnabled(true);
  ui->arguments->setEnabled(true);
  ui->overwriteSteamAppID->setEnabled(true);
  ui->useApplicationIcon->setEnabled(true);
  ui->createFilesInMod->setEnabled(true);
  ui->forceLoadLibraries->setEnabled(true);
  ui->hide->setEnabled(true);
}

void EditExecutablesDialog::save()
{
  if (m_settingUI) {
    return;
  }

  auto* e = selectedExe();
  if (!e) {
    log::warn("trying to save but nothing is selected");
    return;
  }

  // title may have changed, start with the stuff using it

  // custom overwrites
  if (ui->createFilesInMod->isChecked()) {
    m_customOverwrites.set(e->title(), true, ui->mods->currentText());
  } else {
    m_customOverwrites.setEnabled(e->title(), false);
  }

  // forced libraries
  m_forcedLibraries.setEnabled(e->title(), ui->forceLoadLibraries->isChecked());

  // get the new title, but ignore it if it's conflicting with an already
  // existing executable
  QString newTitle = ui->title->text().trimmed();
  if (isTitleConflicting(newTitle)) {
    newTitle = e->title();
  }

  if (e->title() != newTitle) {
    // now rename both the custom overwrites and forced libraries if the title
    // is being changed
    m_customOverwrites.rename(e->title(), newTitle);
    m_forcedLibraries.rename(e->title(), newTitle);

    // save the new title
    e->title(newTitle);
  }

  e->binaryInfo(QFileInfo(ui->binary->text()));
  e->workingDirectory(ui->workingDirectory->text());
  e->arguments(ui->arguments->text());

  if (ui->overwriteSteamAppID->isChecked()) {
    e->steamAppID(ui->steamAppID->text());
  } else {
    e->steamAppID("");
  }

  if (ui->useApplicationIcon->isChecked()) {
    e->flags(e->flags() | Executable::UseApplicationIcon);
  } else {
    e->flags(e->flags() & (~Executable::UseApplicationIcon));
  }

  if (ui->hide->isChecked()) {
    e->flags(e->flags() | Executable::Hide);
  } else {
    e->flags(e->flags() & (~Executable::Hide));
  }

  setDirty(true);
}

void EditExecutablesDialog::saveOrder()
{
  m_executablesList = getExecutablesList();
  setDirty(true);
}

bool EditExecutablesDialog::canMove(const QListWidgetItem* item, int direction)
{
  if (!item) {
    return false;
  }

  if (direction < 0) {
    // moving up
    return (ui->list->row(item) > 0);

  } else if (direction > 0) {
    // moving down
    return (ui->list->row(item) < (ui->list->count() - 1));
  }

  return false;
}

void EditExecutablesDialog::move(QListWidgetItem* item, int direction)
{
  if (!canMove(item, direction)) {
    return;
  }

  const auto oldRow = ui->list->row(item);
  const auto newRow = oldRow + (direction > 0 ? 1 : -1);

  // removing item
  ui->list->takeItem(oldRow);
  ui->list->insertItem(newRow, item);

  selectIndex(newRow);
  setDirty(true);
}

void EditExecutablesDialog::on_list_itemSelectionChanged()
{
  updateUI(selectedItem(), selectedExe());
}

void EditExecutablesDialog::on_reset_clicked()
{
  const auto title = tr("Reset plugin executables");

  const auto text =
      tr("This will restore all the executables provided by the game plugin. If "
         "there are existing executables with the same names, they will be "
         "automatically renamed and left unchanged.");

  const auto buttons = QMessageBox::Ok | QMessageBox::Cancel;

  if (QMessageBox::question(this, title, text, buttons) != QMessageBox::Ok) {
    return;
  }

  m_executablesList.resetFromPlugin(m_organizerCore.managedGame());
  fillList();

  setDirty(true);
}

void EditExecutablesDialog::on_add_clicked()
{
  addFromFile();
}

void EditExecutablesDialog::on_remove_clicked()
{
  auto* item = selectedItem();
  if (!item) {
    log::warn("trying to remove entry but nothing is selected");
    return;
  }

  auto* exe = selectedExe();
  if (!exe) {
    log::warn("trying to remove entry but nothing is selected");
    return;
  }

  const int currentRow = ui->list->row(item);
  delete item;

  m_customOverwrites.remove(exe->title());
  m_forcedLibraries.remove(exe->title());

  // removing from main list, must be done last because it invalidates the
  // exe pointer
  m_executablesList.remove(exe->title());

  // reselecting the same row as before, or the last one
  if (currentRow >= ui->list->count()) {
    // that was the last item, select the new list item, if any
    if (ui->list->count() > 0) {
      selectIndex(ui->list->count() - 1);
    }
  } else {
    selectIndex(currentRow);
  }

  setDirty(true);
}

void EditExecutablesDialog::on_up_clicked()
{
  auto* item = selectedItem();
  if (!item) {
    return;
  }

  move(item, -1);
}

void EditExecutablesDialog::on_down_clicked()
{
  auto* item = selectedItem();
  if (!item) {
    return;
  }

  move(item, +1);
}

bool EditExecutablesDialog::isTitleConflicting(const QString& s)
{
  for (const auto& exe : m_executablesList) {
    if (exe.title() == s) {
      if (&exe != selectedExe()) {
        // found an executable that's not the current one with the same title
        return true;
      }
    }
  }

  return false;
}

void EditExecutablesDialog::on_title_textChanged(const QString& original)
{
  if (m_settingUI) {
    return;
  }

  auto s = original.trimmed();

  // disallow empty names
  if (s.isEmpty()) {
    return;
  }

  // disallow changing the title to something that already exists
  if (isTitleConflicting(s)) {
    return;
  }

  m_lastGoodTitle = s;

  // must save before modifying the item in the list widget because saving
  // relies on the item's text being the same as an item in m_executablesList
  save();

  // once the executable is saved, the list item must be changed to match the
  // new name
  if (auto* i = selectedItem()) {
    i->setText(s);
  }
}

void EditExecutablesDialog::on_title_editingFinished()
{
  ui->title->setText(m_lastGoodTitle);
}

void EditExecutablesDialog::on_overwriteSteamAppID_toggled(bool checked)
{
  if (m_settingUI) {
    return;
  }

  ui->steamAppID->setEnabled(checked);
  save();
}

void EditExecutablesDialog::on_createFilesInMod_toggled(bool checked)
{
  if (m_settingUI) {
    return;
  }

  ui->mods->setEnabled(checked);
  save();

  if (checked) {
    ui->mods->lineEdit()->selectAll();
    ui->mods->setFocus();
  }
}

void EditExecutablesDialog::on_forceLoadLibraries_toggled(bool checked)
{
  if (m_settingUI) {
    return;
  }

  ui->configureLibraries->setEnabled(ui->forceLoadLibraries->isChecked());
  save();
}

void EditExecutablesDialog::on_browseBinary_clicked()
{
  const auto binaryName = browseBinary(ui->binary->text());
  if (binaryName.fileName().isEmpty()) {
    return;
  }

  setBinary(binaryName);
  save();
}

void EditExecutablesDialog::addFromFile()
{
  const auto binary = browseBinary(ui->binary->text());
  if (binary.fileName().isEmpty()) {
    return;
  }

  addNew(Executable(binary.completeBaseName()));
  setBinary(binary);
}

void EditExecutablesDialog::addEmpty()
{
  addNew(Executable(tr("New Executable")));
}

void EditExecutablesDialog::clone()
{
  auto* e = selectedExe();
  if (!e) {
    return;
  }

  addNew(*e);
}

void EditExecutablesDialog::addNew(Executable e)
{
  const auto fixedTitle = m_executablesList.makeNonConflictingTitle(e.title());
  if (!fixedTitle) {
    return;
  }

  e.title(*fixedTitle);

  m_executablesList.setExecutable(e);

  auto* item = createListItem(e);
  ui->list->addItem(item);

  selectIndex(ui->list->count() - 1);
  setDirty(true);
}

void EditExecutablesDialog::setBinary(const QFileInfo& binary)
{
  // setting binary
  if (binary.suffix().compare("jar", Qt::CaseInsensitive) == 0) {
    // special case for jar files, uses the system java installation
    setJarBinary(binary);
  } else {
    ui->binary->setText(QDir::toNativeSeparators(binary.absoluteFilePath()));
  }

  // setting title if some variation of "New Executable"
  if (ui->title->text().startsWith(tr("New Executable"), Qt::CaseInsensitive)) {
    const auto prefix   = binary.completeBaseName();
    const auto newTitle = m_executablesList.makeNonConflictingTitle(prefix);

    if (newTitle) {
      ui->title->setText(*newTitle);
    }
  }
}

void EditExecutablesDialog::on_browseWorkingDirectory_clicked()
{
  QString dirName = FileDialogMemory::getExistingDirectory(
      "editExecutableDirectory", this, tr("Select a directory"),
      ui->workingDirectory->text());

  if (dirName.isNull()) {
    // cancelled
    return;
  }

  ui->workingDirectory->setText(dirName);
}

void EditExecutablesDialog::on_configureLibraries_clicked()
{
  auto* e = selectedExe();
  if (!e) {
    log::warn("trying to configure libraries but nothing is selected");
    return;
  }

  ForcedLoadDialog dialog(m_organizerCore.managedGame(), this);

  if (auto libraryList = m_forcedLibraries.find(e->title())) {
    dialog.setValues(libraryList->value);
  }

  if (dialog.exec() == QDialog::Accepted) {
    m_forcedLibraries.setValue(e->title(), dialog.values());
    save();
  }
}

void EditExecutablesDialog::on_buttons_clicked(QAbstractButton* b)
{
  if (b == ui->buttons->button(QDialogButtonBox::Ok)) {
    if (commitChanges()) {
      accept();
    }
  } else if (b == ui->buttons->button(QDialogButtonBox::Apply)) {
    commitChanges();
  } else {
    reject();
  }
}

QFileInfo EditExecutablesDialog::browseBinary(const QString& initial)
{
  const QString Filters =
      tr("Executables (*.exe *.bat *.jar)") + ";;" + tr("All Files (*.*)");

  const auto f = FileDialogMemory::getOpenFileName(
      "editExecutableBinary", this, tr("Select an executable"), initial, Filters);

  if (f.isNull()) {
    return {};
  }

  return QFileInfo(f);
}

void EditExecutablesDialog::setJarBinary(const QFileInfo& binary)
{
  auto java = spawn::findJavaInstallation(binary.absoluteFilePath());

  if (java.isEmpty()) {
    QMessageBox::information(
        this, tr("Java required"),
        tr("MO requires Java to run this application. If you already "
           "have it installed, select javaw.exe from that installation as "
           "the binary."));
  }

  {
    // only save once
    IgnoreChanges c(this);

    ui->binary->setText(java);
    ui->workingDirectory->setText(QDir::toNativeSeparators(binary.absolutePath()));
    ui->arguments->setText("-jar \"" +
                           QDir::toNativeSeparators(binary.absoluteFilePath()) + "\"");
  }

  save();
}