summaryrefslogtreecommitdiff
path: root/src/modinfodialogtextfiles.cpp
blob: 50174ec57cb3a79ceac1db87533a9cb0e48d5201 (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
#include "modinfodialogtextfiles.h"
#include "ui_modinfodialog.h"
#include <QMessageBox>

class TextFileItem : public QListWidgetItem
{
public:
  TextFileItem(const QString& rootPath, QString fullPath)
    : m_fullPath(std::move(fullPath))
  {
    setText(m_fullPath.mid(rootPath.length() + 1));
  }

  const QString& fullPath() const
  {
    return m_fullPath;
  }

private:
  QString m_fullPath;
};


TextFilesTab::TextFilesTab(Ui::ModInfoDialog* ui)
  : ui(ui)
{
  ui->textFileView->setupToolbar();

  ui->tabTextSplitter->setSizes({200, 1});
  ui->tabTextSplitter->setStretchFactor(0, 0);
  ui->tabTextSplitter->setStretchFactor(1, 1);

  QObject::connect(
    ui->textFileList, &QListWidget::currentItemChanged,
    [&](auto* current, auto* previous){ onSelection(current, previous); });
}

void TextFilesTab::clear()
{
  ui->textFileList->clear();
  select(nullptr);
}

bool TextFilesTab::feedFile(const QString& rootPath, const QString& fullPath)
{
  if (fullPath.endsWith(".txt", Qt::CaseInsensitive)) {
    ui->textFileList->addItem(new TextFileItem(rootPath, fullPath));
    return true;
  }

  return false;
}

bool TextFilesTab::canClose()
{
  if (!ui->textFileView->dirty()) {
    return true;
  }

  const int res = QMessageBox::question(
    ui->tabText,
    QObject::tr("Save changes?"),
    QObject::tr("Save changes to \"%1\"?").arg(ui->textFileView->filename()),
    QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

  if (res == QMessageBox::Cancel) {
    return false;
  }

  if (res == QMessageBox::Yes) {
      ui->textFileView->save();
  }

  return true;
}

void TextFilesTab::onSelection(
  QListWidgetItem* current, QListWidgetItem* previous)
{
  auto* item = dynamic_cast<TextFileItem*>(current);
  if (!item) {
    qCritical("TextFilesTab: item is not a TextFileItem");
    return;
  }

  if (!canClose()) {
    ui->textFileList->setCurrentItem(previous, QItemSelectionModel::Current);
    return;
  }

  select(item);
}

void TextFilesTab::select(TextFileItem* item)
{
  if (item) {
    ui->textFileView->setEnabled(true);
    ui->textFileView->load(item->fullPath());
  } else {
    ui->textFileView->setEnabled(false);
  }
}