Debian Codegraph @

gui/customphraseeditor/customphrasemodel.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2012~2017 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7 #include "customphrasemodel.h"
8 #include "../../im/pinyin/customphrase.h"
9 #include <QAbstractTableModel>
10 #include <QApplication>
11 #include <QByteArray>
12 #include <QFile>
13 #include <QFuture>
14 #include <QFutureWatcher>
15 #include <QLatin1String>
16 #include <QList>
17 #include <QObject>
18 #include <Qt>
19 #include <QtConcurrentRun>
20 #include <fcitx-utils/fdstreambuf.h>
21 #include <fcitx-utils/i18n.h>
22 #include <fcitx-utils/standardpaths.h>
23 #include <fcitx-utils/stringutils.h>
24 #include <fcitx-utils/utf8.h>
25 #include <fcntl.h>
26 #include <istream>
27 #include <ostream>
28 #include <string>
29 #include <string_view>
30 #include <vector>
31
32 namespace fcitx {
33
34 std::string_view multilineComment =
35 NC_("Please ensure the line width is around 80 character width",
36 R"foo(The line should be in format key,order=value
37 If value is multiline, you may either write is as
38 key,order=
39 line1
40 line2
41 ...
42 lineN
43 Or, write it as key,order="line1\nline2...\nlineN"
44 The comment line is started with # or ;.
45 )foo");
46
47 std::string_view usageComment =
48 NC_("Please ensure the line width is around 80 character width",
49 R"foo(If you want to produce dynamic content, you may set the phrase to
50 start with symbol "#". The phrase may contain variable name like
51 $name or ${name}. For example, you can write: sj,2=#$fullhour:$minute
52 to produce current 24-hour time with sj.
53 Built-in functions include:
54 $year Current year, e.g. 1990, 2003.
55 $year_yy Current year in two-digit, e.g. 90, 03.
56 $month Current month, e.g. 1, 2, 3..., 12.
57 $month_mm Current month in two digit, e.g. 01, 02, ... 12.
58 $day Current day of month, e.g. 1, 2, 3..., 31.
59 $day_dd Current day of month in two digit, e.g. 01, 02, ... 31.
60 $weekday Current weekday, e.g. 1, 2, 3, ... 7.
61 $fullhour Current 24-hour, e.g. 00, 01, 02, ..., 23.
62 $halfhour Current 12-hour, 01, 02, 03, ..., 12.
63 $ampm Current AM or PM.
64 $minute Current minute, e.g. 00, 01, ..., 59
65 $second Current second, e.g. 00, 01, ..., 59
66 $year_cn Current year in Chinese, e.g. 一九九零, 二零零三.
67 $year_yy_cn Current year in two digit Chinese, e.g. 九零, 零三.
68 $month_cn Current month in Chinese, e.g. 一月, 二月, ... 十二月.
69 $day_cn Current day in Chinese, e.g. 一, 二, ... 三十一.
70 $fullhour_cn Current 24-hour in Chinese, e.g. 零, 一, 二, ... 二十三.
71 $halfhour_cn Current 12-hour in Chinese, e.g. 一, 二, ... 十二.
72 $ampm_cn Current AM, PM in Chinese, 上午 or 下午.
73 $minute_cn Current minute in Chinese, 零, 一, 二, ... 五十九.
74 $second_cn Current second in Chinese, 零, 一, 二, ... 五十九.
75
76 If lua is installed, the function defined in imeapi can be invoked
77 with ${lua:function_name}.
78 )foo");
79
80 std::string customPhraseHelpMessage() {
81 return C_("Please ensure the line width is around 80 character width",
82 std::string(usageComment));
83 }
84
85 CustomPhraseModel::CustomPhraseModel(QObject *parent)
86 : QAbstractTableModel(parent), needSave_(false) {}
87
88 CustomPhraseModel::~CustomPhraseModel() {}
89
90 bool CustomPhraseModel::needSave() { return needSave_; }
91
92 QVariant CustomPhraseModel::headerData(int section, Qt::Orientation orientation,
93 int role) const {
94 if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
95 if (section == Column_Key) {
96 return _("Key");
97 }
98 if (section == Column_Phrase) {
99 return _("Phrase");
100 }
101 if (section == Column_Order) {
102 return _("Order");
103 }
104 }
105 return {};
106 }
107
108 int CustomPhraseModel::rowCount(const QModelIndex &parent) const {
109 Q_UNUSED(parent);
110 return list_.count();
111 }
112
113 int CustomPhraseModel::columnCount(const QModelIndex &parent) const {
114 Q_UNUSED(parent);
115 return 4;
116 }
117
118 QVariant CustomPhraseModel::data(const QModelIndex &index, int role) const {
119 do {
120 if (role == Qt::CheckStateRole && index.column() == Column_Enable) {
121 return list_[index.row()].enabled ? Qt::Checked : Qt::Unchecked;
122 }
123 if ((role == Qt::DisplayRole || role == Qt::EditRole) &&
124 index.row() < list_.count()) {
125 if (index.column() == Column_Key) {
126 return list_[index.row()].key;
127 }
128 if (index.column() == Column_Phrase) {
129 return list_[index.row()].value;
130 }
131 if (index.column() == Column_Order) {
132 return qAbs(list_[index.row()].order);
133 }
134 }
135 } while (0);
136 return QVariant();
137 }
138
139 void CustomPhraseModel::addItem(const QString &key, const QString &word,
140 int order, bool enabled) {
141 beginInsertRows(QModelIndex(), list_.size(), list_.size());
142 list_.append(CustomPhraseItem{
143 .key = key, .value = word, .order = order, .enabled = enabled});
144 endInsertRows();
145 setNeedSave(true);
146 }
147
148 void CustomPhraseModel::deleteItem(int row) {
149 if (row >= list_.count() || row < 0) {
150 return;
151 }
152 beginRemoveRows(QModelIndex(), row, row);
153 list_.removeAt(row);
154 endRemoveRows();
155 setNeedSave(true);
156 }
157
158 void CustomPhraseModel::deleteAllItem() {
159 if (list_.count()) {
160 setNeedSave(true);
161 }
162 beginResetModel();
163 list_.clear();
164 endResetModel();
165 }
166
167 Qt::ItemFlags CustomPhraseModel::flags(const QModelIndex &index) const {
168 if (!index.isValid()) {
169 return {};
170 }
171
172 if (index.column() == Column_Enable) {
173 return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable |
174 Qt::ItemIsSelectable;
175 }
176 return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
177 }
178
179 bool CustomPhraseModel::setData(const QModelIndex &index, const QVariant &value,
180 int role) {
181 if (role == Qt::CheckStateRole && index.column() == Column_Enable) {
182 list_[index.row()].enabled = value.toBool();
183
184 Q_EMIT dataChanged(index, index);
185 setNeedSave(true);
186 return true;
187 }
188
189 if (role != Qt::EditRole) {
190 return false;
191 }
192
193 if (index.column() == Column_Key) {
194 list_[index.row()].key = value.toString();
195
196 Q_EMIT dataChanged(index, index);
197 setNeedSave(true);
198 return true;
199 }
200 if (index.column() == Column_Phrase) {
201 list_[index.row()].value = value.toString();
202
203 Q_EMIT dataChanged(index, index);
204 setNeedSave(true);
205 return true;
206 }
207 if (index.column() == Column_Order) {
208 list_[index.row()].order = value.toInt();
209
210 Q_EMIT dataChanged(index, index);
211 setNeedSave(true);
212 return true;
213 }
214 return false;
215 }
216
217 void CustomPhraseModel::load() {
218 if (futureWatcher_) {
219 return;
220 }
221
222 beginResetModel();
223 setNeedSave(false);
224 futureWatcher_ = new QFutureWatcher<QList<CustomPhraseItem>>(this);
225 futureWatcher_->setFuture(QtConcurrent::run(
226 &CustomPhraseModel::parse, QLatin1String(customPhraseFileName)));
227 connect(futureWatcher_, &QFutureWatcherBase::finished, this,
228 &CustomPhraseModel::loadFinished);
229 }
230
231 QList<CustomPhraseItem> CustomPhraseModel::parse(const QString &file) {
232 QByteArray fileNameArray = file.toLocal8Bit();
233 QList<CustomPhraseItem> list;
234
235 do {
236 auto fp = StandardPaths::global().open(StandardPathsType::PkgData,
237 fileNameArray.constData());
238 if (!fp.isValid()) {
239 break;
240 }
241
242 IFDStreamBuf buffer(fp.fd());
243
244 std::istream in(&buffer);
245 CustomPhraseDict dict;
246 dict.load(in, /*loadDisabled=*/true);
247 dict.foreach(
248 [&list](const std::string &key, std::vector<CustomPhrase> &items) {
249 for (const auto &item : items) {
250 list.append(CustomPhraseItem{
251 .key = QString::fromStdString(key),
252 .value = QString::fromStdString(item.value()),
253 .order = qAbs(item.order()),
254 .enabled = item.order() >= 0});
255 }
256 });
257 } while (0);
258
259 return list;
260 }
261
262 void CustomPhraseModel::loadFinished() {
263 list_ = futureWatcher_->future().result();
264 endResetModel();
265 futureWatcher_->deleteLater();
266 futureWatcher_ = nullptr;
267 }
268
269 QFutureWatcher<bool> *CustomPhraseModel::save() {
270 QFutureWatcher<bool> *futureWatcher = new QFutureWatcher<bool>(this);
271 futureWatcher->setFuture(
272 QtConcurrent::run(&CustomPhraseModel::saveData,
273 QLatin1String(customPhraseFileName), list_));
274 connect(futureWatcher, &QFutureWatcherBase::finished, this,
275 &CustomPhraseModel::saveFinished);
276 return futureWatcher;
277 }
278
279 bool CustomPhraseModel::saveData(const QString &file,
280 const QList<CustomPhraseItem> &list) {
281 QByteArray filenameArray = file.toLocal8Bit();
282 return StandardPaths::global().safeSave(
283 StandardPathsType::PkgData, filenameArray.constData(), [&list](int fd) {
284 OFDStreamBuf buffer(fd);
285 std::ostream out(&buffer);
286 auto printMultilineComment = [](std::ostream &out,
287 std::string_view text) {
288 for (const auto &line : stringutils::split(
289 text, "\n", stringutils::SplitBehavior::KeepEmpty)) {
290 out << "# " << line << "\n";
291 }
292 };
293 printMultilineComment(
294 out,
295 C_("Please ensure the line width is around 80 character width",
296 std::string(multilineComment)));
297 printMultilineComment(out, customPhraseHelpMessage());
298 out << "\n";
299 CustomPhraseDict dict;
300 for (const auto &item : list) {
301 dict.addPhrase(item.key.toStdString(), item.value.toStdString(),
302 item.order * (item.enabled ? 1 : -1));
303 }
304 dict.save(out);
305 return true;
306 });
307 }
308
309 void CustomPhraseModel::saveFinished() {
310 auto *watcher = static_cast<QFutureWatcher<bool> *>(sender());
311 QFuture<bool> future = watcher->future();
312 if (future.result()) {
313 setNeedSave(false);
314 }
315 watcher->deleteLater();
316 }
317
318 void CustomPhraseModel::setNeedSave(bool needSave) {
319 if (needSave_ != needSave) {
320 needSave_ = needSave;
321 Q_EMIT needSaveChanged(needSave_);
322 }
323 }
324 } // namespace fcitx