File: editor.cpp

package info (click to toggle)
fcitx5-qt 5.1.10-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,340 kB
  • sloc: cpp: 11,697; xml: 243; ansic: 46; makefile: 14; sh: 9
file content (288 lines) | stat: -rw-r--r-- 9,426 bytes parent folder | download
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
/*
 * SPDX-FileCopyrightText: 2012~2017 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 */
#include "editor.h"
#include "batchdialog.h"
#include "editordialog.h"
#include "filelistmodel.h"
#include "model.h"
#include <QCloseEvent>
#include <QDebug>
#include <QFileDialog>
#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QtConcurrentRun>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/standardpaths.h>
#include <filesystem>

namespace fcitx {

ListEditor::ListEditor(QWidget *parent)
    : FcitxQtConfigUIWidget(parent), model_(new QuickPhraseModel(this)),
      fileListModel_(new FileListModel(this)) {
    setupUi(this);

    macroTableView->setModel(model_);
    fileListComboBox->setModel(fileListModel_);

    operationMenu_ = new QMenu(this);
    operationMenu_->addAction(_("Add File"), this,
                              &ListEditor::addFileTriggered);
    operationMenu_->addAction(_("Remove File"), this,
                              &ListEditor::removeFileTriggered);
    operationMenu_->addAction(_("Refresh List"), this,
                              &ListEditor::refreshListTriggered);
    operationButton->setMenu(operationMenu_);

    loadFileList();
    itemFocusChanged();

    connect(addButton, &QPushButton::clicked, this, &ListEditor::addWord);
    connect(batchEditButton, &QPushButton::clicked, this,
            &ListEditor::batchEditWord);
    connect(deleteButton, &QPushButton::clicked, this, &ListEditor::deleteWord);
    connect(clearButton, &QPushButton::clicked, this,
            &ListEditor::deleteAllWord);
    connect(importButton, &QPushButton::clicked, this, &ListEditor::importData);
    connect(exportButton, &QPushButton::clicked, this, &ListEditor::exportData);

    connect(fileListComboBox, qOverload<int>(&QComboBox::activated), this,
            &ListEditor::changeFile);

    connect(macroTableView->selectionModel(),
            &QItemSelectionModel::selectionChanged, this,
            &ListEditor::itemFocusChanged);
    connect(model_, &QuickPhraseModel::needSaveChanged, this,
            &ListEditor::changed);
}

void ListEditor::load() {
    lastFile_ = currentFile();
    model_->load(currentFile(), false);
}

void ListEditor::load(const QString &file) { model_->load(file, true); }

void ListEditor::save(const QString &file) { model_->save(file); }

void ListEditor::save() {
    // QFutureWatcher< bool >* futureWatcher =
    // m_model->save("data/QuickPhrase.mb");
    QFutureWatcher<bool> *futureWatcher = model_->save(currentFile());
    connect(futureWatcher, &QFutureWatcherBase::finished, this,
            &ListEditor::saveFinished);
}

bool ListEditor::asyncSave() { return true; }

void ListEditor::changeFile(int) {
    if (model_->needSave()) {
        int ret = QMessageBox::question(
            this, _("Save Changes"),
            _("The content has changed.\n"
              "Do you want to save the changes or discard them?"),
            QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (ret == QMessageBox::Save) {
            // save(fileListComboBox->itemText(lastFileIndex));
            save(lastFile_);
        } else if (ret == QMessageBox::Cancel) {
            fileListComboBox->setCurrentIndex(
                fileListModel_->findFile(lastFile_));
            return;
        }
    }
    load();
}

QString ListEditor::title() { return _("Quick Phrase Editor"); }

void ListEditor::itemFocusChanged() {
    deleteButton->setEnabled(macroTableView->currentIndex().isValid());
}

void ListEditor::deleteWord() {
    if (!macroTableView->currentIndex().isValid())
        return;
    int row = macroTableView->currentIndex().row();
    model_->deleteItem(row);
}

void ListEditor::deleteAllWord() { model_->deleteAllItem(); }

void ListEditor::addWord() {
    EditorDialog *dialog = new EditorDialog(this);
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    dialog->open();
    connect(dialog, &QDialog::accepted, this, &ListEditor::addWordAccepted);
}

void ListEditor::batchEditWord() {
    BatchDialog *dialog = new BatchDialog(this);
    QString text;
    QTextStream stream(&text);
    model_->saveDataToStream(stream);
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    dialog->setText(text);
    dialog->open();
    connect(dialog, &QDialog::accepted, this, &ListEditor::batchEditAccepted);
}

void ListEditor::addWordAccepted() {
    const EditorDialog *dialog =
        qobject_cast<const EditorDialog *>(QObject::sender());

    model_->addItem(dialog->key(), dialog->value());
    QModelIndex last = model_->index(model_->rowCount() - 1, 0);
    macroTableView->setCurrentIndex(last);
    macroTableView->scrollTo(last);
}

void ListEditor::batchEditAccepted() {
    const BatchDialog *dialog =
        qobject_cast<const BatchDialog *>(QObject::sender());

    QString s = dialog->text();
    QTextStream stream(&s);

    model_->loadData(stream);
    QModelIndex last = model_->index(model_->rowCount() - 1, 0);
    macroTableView->setCurrentIndex(last);
    macroTableView->scrollTo(last);
}

void ListEditor::importData() {
    QFileDialog *dialog = new QFileDialog(this);
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    dialog->setFileMode(QFileDialog::ExistingFile);
    dialog->setAcceptMode(QFileDialog::AcceptOpen);
    dialog->open();
    connect(dialog, &QDialog::accepted, this, &ListEditor::importFileSelected);
}

void ListEditor::exportData() {
    QFileDialog *dialog = new QFileDialog(this);
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    dialog->setAcceptMode(QFileDialog::AcceptSave);
    dialog->open();
    connect(dialog, &QDialog::accepted, this, &ListEditor::exportFileSelected);
}

void ListEditor::importFileSelected() {
    const QFileDialog *dialog =
        qobject_cast<const QFileDialog *>(QObject::sender());
    if (dialog->selectedFiles().length() <= 0)
        return;
    QString file = dialog->selectedFiles()[0];
    load(file);
}

void ListEditor::exportFileSelected() {
    const QFileDialog *dialog =
        qobject_cast<const QFileDialog *>(QObject::sender());
    if (dialog->selectedFiles().length() <= 0)
        return;
    QString file = dialog->selectedFiles()[0];
    save(file);
}

void ListEditor::loadFileList() {
    int row = fileListComboBox->currentIndex();
    int col = fileListComboBox->modelColumn();
    QString lastFileName =
        fileListModel_->data(fileListModel_->index(row, col), Qt::UserRole)
            .toString();
    fileListModel_->loadFileList();
    fileListComboBox->setCurrentIndex(fileListModel_->findFile(lastFileName));
    load();
}

QString ListEditor::currentFile() {
    int row = fileListComboBox->currentIndex();
    int col = fileListComboBox->modelColumn();
    return fileListModel_->data(fileListModel_->index(row, col), Qt::UserRole)
        .toString();
}

QString ListEditor::currentName() {
    int row = fileListComboBox->currentIndex();
    int col = fileListComboBox->modelColumn();
    return fileListModel_
        ->data(fileListModel_->index(row, col), Qt::DisplayRole)
        .toString();
}

void ListEditor::addFileTriggered() {
    bool ok;
    QString filename = QInputDialog::getText(
        this, _("Create new file"), _("Please input a filename for newfile"),
        QLineEdit::Normal, "newfile", &ok);

    if (filename.contains('/')) {
        QMessageBox::warning(this, _("Invalid filename"),
                             _("File name should not contain '/'."));
        return;
    }

    filename.append(".mb");
    if (!StandardPaths::global().safeSave(
            StandardPathsType::PkgData,
            std::filesystem::path(QUICK_PHRASE_CONFIG_DIR) /
                filename.toStdString(),
            [](int) { return true; })) {
        QMessageBox::warning(
            this, _("File Operation Failed"),
            QString(_("Cannot create file %1.")).arg(filename));
        return;
    }

    fileListModel_->loadFileList();
    fileListComboBox->setCurrentIndex(fileListModel_->findFile(
        filename.prepend(QUICK_PHRASE_CONFIG_DIR "/")));
    load();
}

void ListEditor::refreshListTriggered() { loadFileList(); }

void ListEditor::removeFileTriggered() {
    QString filename = currentFile();
    QString curName = currentName();
    auto fullname =
        StandardPaths::global().userDirectory(StandardPathsType::PkgData) /
        filename.toStdString();
    QFile f(QString::fromStdString(fullname.string()));
    if (!f.exists()) {
        int ret = QMessageBox::question(
            this, _("Cannot remove system file"),
            QString(_("%1 is a system file, do you want to delete all phrases "
                      "instead?"))
                .arg(curName),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if (ret == QMessageBox::Yes) {
            deleteAllWord();
        }
        return;
    }

    int ret = QMessageBox::question(
        this, _("Confirm deletion"),
        QString(_("Are you sure to delete %1?")).arg(curName),
        QMessageBox::Ok | QMessageBox::Cancel);

    if (ret == QMessageBox::Ok) {
        bool ok = f.remove();
        if (!ok) {
            QMessageBox::warning(
                this, _("File Operation Failed"),
                QString(_("Error while deleting %1.")).arg(curName));
        }
    }
    loadFileList();
    load();
}
} // namespace fcitx