forked from 0xb8/WiseTagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.cpp
538 lines (445 loc) · 13.8 KB
/
input.cpp
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
/* Copyright © 2014 cat <[email protected]>
* This program is free software. It comes without any warranty, to the extent
* permitted by applicable law. You can redistribute it and/or modify it under
* the terms of the Do What The Fuck You Want To Public License, Version 2, as
* published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
#include "input.h"
#include "global_enums.h"
#include "util/strings.h"
#include <vector>
#include <QKeyEvent>
#include <QLoggingCategory>
#include <QSettings>
#include <QTextLayout>
#include <QCoreApplication>
namespace logging_category {
Q_LOGGING_CATEGORY(input, "TagInput")
}
#define pdbg qCDebug(logging_category::input)
#define pwarn qCWarning(logging_category::input)
#include "util/imageboard.h"
TagInput::TagInput(QWidget *_parent) : QLineEdit(_parent)
{
m_completer = std::make_unique<MultiSelectCompleter>(QStringList(), nullptr);
connect(&m_tag_parser, &TagParser::parseError, this, &TagInput::parseError);
connect(this, &QLineEdit::textEdited, this, [this](auto){
const auto tag_list = tags_list();
classifyText(tag_list);
});
}
void TagInput::fixTags(bool sort)
{
if (m_edit_mode != EditMode::Tagging)
return;
auto opts = TagParser::FixOptions::from_settings();
opts.sort = sort;
m_text_list = m_tag_parser.fixTags(m_edit_state, text(), opts);
auto newname = util::join(m_text_list);
util::replace_special(newname);
updateText(newname);
}
void TagInput::setTags(const QString& s)
{
auto text_list = util::split(text());
QStringList imageboard_ids;
tag_iterator tag_begin = text_list.begin(), id = tag_begin;
// find long imageboard id tag
if (ib::find_imageboard_tags(tag_begin, text_list.end(), tag_begin, id)) {
id = std::next(id);
for (auto it = tag_begin; it != id; ++it) {
imageboard_ids.append(*it);
}
}
// find all short imageboard id tags
tag_begin = text_list.begin();
while (ib::find_short_imageboard_tag(tag_begin, text_list.end(), tag_begin)) {
imageboard_ids.append(*tag_begin);
tag_begin = std::next(tag_begin);
}
QString res = util::join(imageboard_ids);
res.append(' ');
res.append(s);
setText(res, m_path_length_limit);
}
QString TagInput::tags() const
{
return util::join(tags_list());
}
QStringList TagInput::tags_list() const
{
auto text_list = util::split(text());
tag_iterator tag_begin = text_list.begin(), id = tag_begin;
// clear long imageboard id tag
if (ib::find_imageboard_tags(tag_begin, text_list.end(), tag_begin, id)) {
for (auto it = tag_begin; it != std::next(id); ++it)
it->clear();
}
// clear short imageboard id tags
tag_begin = text_list.begin();
while (ib::find_short_imageboard_tag(tag_begin, text_list.end(), tag_begin)) {
tag_begin->clear();
tag_begin = std::next(tag_begin);
}
// remove empty strings from list
text_list.erase(std::remove_if(text_list.begin(), text_list.end(), [](const auto& str){
return str.isEmpty();
}), text_list.end());
return text_list;
}
const TagParser & TagInput::tag_parser() const
{
return m_tag_parser;
}
void TagInput::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Tab) {
if((!next_completer())&&(!next_completer()))
return;
updateText(m_completer->currentCompletion());
return;
}
if(event->key() == Qt::Key_Escape) {
releaseKeyboard();
parentWidget()->setFocus();
return;
}
if(event->key() == Qt::Key_Enter || event->key()== Qt::Key_Return)
{
fixTags();
releaseKeyboard();
parentWidget()->setFocus();
return;
}
// NOTE: Shift+Space - workaround for space not working as expected when typing in the middle of the word.
if(event->key() == Qt::Key_Space && !(event->modifiers() & Qt::ShiftModifier)) {
/* Don't sort tags, haven't finished editing yet */
fixTags(false);
}
QLineEdit::keyPressEvent(event);
m_completer->setCompletionPrefix(text());
m_index = 0;
}
void TagInput::focusInEvent(QFocusEvent * event)
{
QLineEdit::focusInEvent(event);
QSettings settings;
bool space = event->isAccepted() && event->gotFocus() && event->reason() == Qt::TabFocusReason;
if (space && settings.value("window/focus-append", true).toBool()) {
// add a space to text and move fursor forward
auto tmp_text = text().trimmed();
if (!tmp_text.isEmpty())
tmp_text.append(' ');
updateText(tmp_text);
cursorForward(false);
}
}
void TagInput::update_qss()
{
QString qss;
if (m_edit_mode == EditMode::Naming) {
qss.append(QStringLiteral("background-color: %1;").arg(getNamingModeBackgroundColor().name()));
}
setStyleSheet(QStringLiteral("QLineEdit#Input { %1 }").arg(qss));
}
static int update_model(QStandardItemModel& model, const TagParser& parser)
{
const auto& tags = parser.getAllTags();
model.clear();
model.setColumnCount(1);
model.setRowCount(tags.size());
for(int i = 0; i < model.rowCount(); ++i) {
auto index = model.index(i, 0);
const auto& tag = tags[i];
if(Q_UNLIKELY(!model.setData(index, tag, Qt::UserRole))) {
pwarn << "could not set completion data for "<< tag << "at" << index;
}
QString tag_display = tag;
std::unordered_set<QString> consequents;
if (parser.getConsequents(tag, consequents)) {
QStringList cons_list{consequents.begin(), consequents.end()};
cons_list.sort();
tag_display.append(QStringLiteral(" → "));
for (auto it = cons_list.cbegin(); it != cons_list.end(); ++it) {
auto c = *it;
if (c.startsWith(QChar('-'))) {
c[0] = QChar(0x00AC); // ¬
}
tag_display.append(c);
if (it == std::prev(cons_list.cend()))
break;
tag_display.append(QStringLiteral(", "));
}
}
auto comment = parser.getComment(tag);
if(!comment.isEmpty()) {
tag_display.append(QStringLiteral(" ("));
tag_display.append(comment);
tag_display.append(QStringLiteral(")"));
if (Q_UNLIKELY((!model.setData(index, comment, Qt::UserRole + 1))))
pwarn << "could not set tag comment:" << comment;
}
if(Q_UNLIKELY(!model.setData(index, tag_display, Qt::DisplayRole)))
pwarn << "could not set tag display role:" << tag_display;
auto color = parser.getColor(tag);
if (color.isValid()) {
if(Q_UNLIKELY(!model.setData(index, color, Qt::ForegroundRole)))
pwarn << "could not set tag color role:" << tag << color;
}
}
return model.rowCount();
}
void TagInput::loadTagData(const QByteArray& data)
{
if (!m_tag_parser.loadTagData(data)) {
m_tags_model.clear();
return;
}
m_tags_model_num_main_tags = update_model(m_tags_model, m_tag_parser);
m_completer = std::make_unique<MultiSelectCompleter>(&m_tags_model, nullptr);
m_completer->setCompletionRole(Qt::UserRole);
m_completer->setCompletionMode(QCompleter::PopupCompletion);
setCompleter(m_completer.get());
updateText(text());
}
static void set_line_edit_text_formats(QLineEdit& input, const std::vector<QTextLayout::FormatRange>& formats)
{
QList<QInputMethodEvent::Attribute> attributes;
for(const auto& fr : formats) {
QInputMethodEvent::AttributeType type = QInputMethodEvent::TextFormat;
int start = fr.start - input.cursorPosition();
int length = fr.length;
QVariant value = fr.format;
attributes.append(QInputMethodEvent::Attribute(type, start, length, value));
}
QInputMethodEvent event(QString(), attributes);
QCoreApplication::sendEvent(&input, &event);
}
static void clear_line_edit_text_formats(QLineEdit& input)
{
set_line_edit_text_formats(input, std::vector<QTextLayout::FormatRange>{});
}
void TagInput::clearTagData()
{
loadTagData(QByteArray{});
clear_line_edit_text_formats(*this);
}
void TagInput::setText(const QString &s, int path_length_limit)
{
m_path_length_limit = path_length_limit;
m_initial_text = s;
clearTagEditState();
updateText(s);
}
void TagInput::setEditMode(EditMode mode)
{
m_edit_mode = mode;
update_qss();
}
EditMode TagInput::editMode() const noexcept
{
return m_edit_mode;
}
void TagInput::clearTagEditState()
{
m_edit_state.clear();
}
void TagInput::updateText(const QString &t)
{
m_text_list = util::split(t);
QLineEdit::setText(t);
classifyText(tags_list()); // classification ignores imageboard id tags
updateModelRemovedTags(m_text_list); // negation includes imageboard id tags
}
void TagInput::classifyText(const QStringList& tag_list)
{
const auto text = QLineEdit::text();
std::unordered_set<QStringView> antecedent_tags;
std::unordered_set<QString> consequent_tags;
for (const auto& tag: tag_list) {
if (m_tag_parser.getConsequents(tag, consequent_tags)) {
antecedent_tags.insert(tag); // add antecedent tag too
}
}
std::vector<QTextLayout::FormatRange> formats;
const auto consequent_color = m_tag_parser.getCustomKindColor(TagParser::TagKind::Consequent);
auto replaced_color = m_tag_parser.getCustomKindColor(TagParser::TagKind::Replaced);
if (!replaced_color.isValid()) {
replaced_color = getReplacedTagColor();
}
auto removed_color = m_tag_parser.getCustomKindColor(TagParser::TagKind::Removed);
if (!removed_color.isValid()) {
removed_color = getRemovedTagColor();
}
int offset = 0;
for (const auto& tag : tag_list) {
offset = text.indexOf(tag, offset);
if (offset < 0)
break;
QTextCharFormat f;
auto tag_kind = m_tag_parser.classify(tag, tag_list);
bool has_custom_color = false;
if (tag_kind & TagParser::TagKind::Unknown) {
f.setForeground(getUnknownTagColor());
} else {
// tag has custom color
auto color = m_tag_parser.getColor(tag);
if (Q_UNLIKELY(color.isValid())) {
has_custom_color = true;
f.setForeground(color);
}
// this tag implies another tag
if (antecedent_tags.find(tag) != antecedent_tags.end()) {
f.setFontItalic(true);
f.setFontWeight(QFont::Bold);
}
}
if (tag_kind & TagParser::TagKind::Consequent) {
// this tag is implied by other tag
if (consequent_tags.find(tag) != consequent_tags.end()) {
f.setFontItalic(true);
if (consequent_color.isValid() && !has_custom_color) {
f.setForeground(consequent_color);
}
}
}
if (tag_kind & TagParser::TagKind::Replaced) {
f.setForeground(replaced_color);
}
if (tag_kind & TagParser::TagKind::Removed) {
f.setForeground(removed_color);
}
QTextLayout::FormatRange fr;
fr.start = offset;
fr.length = tag.length();
fr.format = f;
formats.push_back(fr);
offset += tag.length();
}
if (text.size() > m_path_length_limit) {
QTextCharFormat f;
f.setFontUnderline(true);
f.setUnderlineStyle(QTextCharFormat::UnderlineStyle::SpellCheckUnderline);
f.setUnderlineColor(Qt::red);
QTextLayout::FormatRange fr;
fr.start = m_path_length_limit;
// trailing spaces will be stripped when saving, so ignore them
int count_trailing_spaces = std::distance(text.rbegin(),
std::find_if_not(text.rbegin(),
text.rend(),
[](QChar c){ return c.isSpace(); }));
fr.length = text.size() - count_trailing_spaces - fr.start;
fr.format = f;
formats.push_back(fr);
}
set_line_edit_text_formats(*this, formats);
}
void TagInput::updateModelRemovedTags(const QStringList& tag_list)
{
int current_row = m_tags_model_num_main_tags;
// add all tags to model with negation
for (const auto& tag : tag_list) {
if (tag.startsWith('-'))
continue; // shouldn't happen, but just in case
if (current_row >= m_tags_model.rowCount()) {
m_tags_model.setRowCount(current_row + 1);
}
auto dst_index = m_tags_model.index(current_row, 0);
const auto negtag = "-" + tag;
m_tags_model.setData(dst_index, negtag, Qt::DisplayRole);
m_tags_model.setData(dst_index, negtag, Qt::UserRole);
++current_row;
}
// remove any remaining rows
m_tags_model.setRowCount(current_row);
}
QString TagInput::postURL() const
{
return ib::get_imageboard_meta(m_text_list.begin(), m_text_list.end()).post_url;
}
QString TagInput::postTagsApiURL() const
{
return ib::get_imageboard_meta(m_text_list.begin(), m_text_list.end()).post_api_url;
}
bool TagInput::hasTagFile() const
{
return m_tag_parser.hasTagFile();
}
QStringList TagInput::getAddedTags(bool exclude_tags_from_file) const
{
auto initial_tags = util::split(m_initial_text);
auto new_tags = util::split(text());
initial_tags.sort();
new_tags.sort();
QStringList ret;
std::set_difference(new_tags.begin(), new_tags.end(), initial_tags.begin(), initial_tags.end(), std::back_inserter(ret));
if(exclude_tags_from_file) {
auto tags_file = m_tag_parser.getAllTags();
tags_file.sort();
QStringList ret2;
std::set_difference(ret.begin(), ret.end(), tags_file.begin(), tags_file.end(), std::back_inserter(ret2));
return ret2;
}
return ret;
}
void TagInput::setViewMode(ViewMode view_mode)
{
QSettings settings;
QFont font(settings.value(QStringLiteral("window/font"), QStringLiteral("Consolas")).toString());
if(view_mode == ViewMode::Normal) {
font.setPixelSize(settings.value(QStringLiteral("window/font-size"), 14).toInt());
setMinimumHeight(m_minimum_height);
setFrame(true);
}
if(view_mode == ViewMode::Minimal) {
font.setPixelSize(settings.value(QStringLiteral("window/font-size-minmode"), 12).toInt());
setMinimumHeight(m_minimum_height_minmode);
setFrame(false);
}
m_view_mode = view_mode;
setFont(font);
update_qss();
}
QColor TagInput::getRemovedTagColor() const
{
return m_removed_tag_color;
}
void TagInput::setRemovedTagColor(QColor color)
{
m_removed_tag_color = color;
}
QColor TagInput::getReplacedTagColor() const
{
return m_replaced_tag_color;
}
void TagInput::setReplacedTagColor(QColor color)
{
m_replaced_tag_color = color;
}
QColor TagInput::getUnknownTagColor() const
{
return m_unknown_tag_color;
}
void TagInput::setUnknownTagColor(QColor color)
{
m_unknown_tag_color = color;
}
QColor TagInput::getNamingModeBackgroundColor() const
{
return m_naming_mode_color;
}
void TagInput::setNamingModeBackgroundColor(QColor color)
{
m_naming_mode_color = color;
}
QAbstractItemModel * TagInput::completionModel()
{
return &m_tags_model;
}
bool TagInput::next_completer()
{
if(m_completer->setCurrentRow(m_index++))
return true;
m_index = 0;
return false;
}