summaryrefslogtreecommitdiffstats
path: root/src/linguist/linguist/messageeditorwidgets.cpp
blob: 25969ca68856e31c53089129ff8a8c586a83e1dc (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "messageeditorwidgets.h"
#include "messagehighlighter.h"

#include <translator.h>

#include <QAbstractTextDocumentLayout>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QDebug>
#include <QLayout>
#include <QMenu>
#include <QMessageBox>
#include <QPainter>
#include <QScrollArea>
#include <QTextBlock>
#include <QTextDocumentFragment>
#include <QToolButton>
#include <QVBoxLayout>
#include <QtGui/private/qtextdocument_p.h>

QT_BEGIN_NAMESPACE

ExpandingTextEdit::ExpandingTextEdit(QWidget *parent)
    : QTextEdit(parent)
{
    setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding));

    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    QAbstractTextDocumentLayout *docLayout = document()->documentLayout();
    connect(docLayout, &QAbstractTextDocumentLayout::documentSizeChanged,
            this, &ExpandingTextEdit::updateHeight);
    connect(this, &QTextEdit::cursorPositionChanged,
            this, &ExpandingTextEdit::reallyEnsureCursorVisible);

    m_minimumHeight = qRound(docLayout->documentSize().height()) + frameWidth() * 2;
}

void ExpandingTextEdit::updateHeight(const QSizeF &documentSize)
{
    m_minimumHeight = qRound(documentSize.height()) + frameWidth() * 2;
    updateGeometry();
}

QSize ExpandingTextEdit::sizeHint() const
{
    return QSize(100, m_minimumHeight);
}

QSize ExpandingTextEdit::minimumSizeHint() const
{
    return QSize(100, m_minimumHeight);
}

void ExpandingTextEdit::reallyEnsureCursorVisible()
{
    QObject *ancestor = parent();
    while (ancestor) {
        QScrollArea *scrollArea = qobject_cast<QScrollArea*>(ancestor);
        if (scrollArea &&
                (scrollArea->verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff &&
                 scrollArea->horizontalScrollBarPolicy() != Qt::ScrollBarAlwaysOff)) {
            const QRect &r = cursorRect();
            const QPoint &c = mapTo(scrollArea->widget(), r.center());
            scrollArea->ensureVisible(c.x(), c.y());
            break;
        }
        ancestor = ancestor->parent();
    }
}

FormatTextEdit::FormatTextEdit(QWidget *parent)
    : ExpandingTextEdit(parent)
{
    setLineWrapMode(QTextEdit::WidgetWidth);
    setAcceptRichText(false);

    // Do not set different background if disabled
    QPalette p = palette();
    p.setColor(QPalette::Disabled, QPalette::Base, p.color(QPalette::Active, QPalette::Base));
    setPalette(p);

    setEditable(true);

    m_highlighter = new MessageHighlighter(this);
}

FormatTextEdit::~FormatTextEdit()
{
    emit editorDestroyed();
}

void FormatTextEdit::setEditable(bool editable)
{
    // save default frame style
    static int framed = frameStyle();
    static Qt::FocusPolicy defaultFocus = focusPolicy();

    if (editable) {
        setFrameStyle(framed);
        setFocusPolicy(defaultFocus);
    } else {
        setFrameStyle(QFrame::NoFrame | QFrame::Plain);
        setFocusPolicy(Qt::NoFocus);
    }

    setReadOnly(!editable);
}

void FormatTextEdit::setPlainText(const QString &text, bool userAction)
{
    if (!userAction) {
        // Prevent contentsChanged signal
        bool oldBlockState = blockSignals(true);
        document()->setUndoRedoEnabled(false);
        ExpandingTextEdit::setPlainText(text);
        // highlighter is out of sync because of blocked signals
        m_highlighter->rehighlight();
        document()->setUndoRedoEnabled(true);
        blockSignals(oldBlockState);
    } else {
        ExpandingTextEdit::setPlainText(text);
    }
}

void FormatTextEdit::setVisualizeWhitespace(bool value)
{
    QTextOption option = document()->defaultTextOption();
    if (value) {
        option.setFlags(option.flags()
                        | QTextOption::ShowLineAndParagraphSeparators
                        | QTextOption::ShowTabsAndSpaces);
    } else {
        option.setFlags(option.flags()
                        & ~QTextOption::ShowLineAndParagraphSeparators
                        & ~QTextOption::ShowTabsAndSpaces);
    }
    document()->setDefaultTextOption(option);
}

FormWidget::FormWidget(const QString &label, bool isEditable, QWidget *parent)
        : QWidget(parent),
          m_hideWhenEmpty(false)
{
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setContentsMargins(QMargins());

    m_label = new QLabel(this);
    QFont fnt;
    fnt.setBold(true);
    m_label->setFont(fnt);
    m_label->setText(label);
    layout->addWidget(m_label);

    m_editor = new FormatTextEdit(this);
    m_editor->setEditable(isEditable);
    //m_textEdit->setWhatsThis(tr("This area shows text from an auxillary translation."));
    layout->addWidget(m_editor);

    setLayout(layout);

    connect(m_editor, &QTextEdit::textChanged,
            this, &FormWidget::slotTextChanged);
    connect(m_editor, &QTextEdit::selectionChanged,
            this, &FormWidget::slotSelectionChanged);
    connect(m_editor, &QTextEdit::cursorPositionChanged,
            this, &FormWidget::cursorPositionChanged);
}

void FormWidget::slotTextChanged()
{
    emit textChanged(m_editor);
}

void FormWidget::slotSelectionChanged()
{
    emit selectionChanged(m_editor);
}

void FormWidget::setTranslation(const QString &text, bool userAction)
{
    m_editor->setPlainText(text, userAction);
    if (m_hideWhenEmpty)
        setHidden(text.isEmpty());
}

void FormWidget::setEditingEnabled(bool enable)
{
    // Use read-only state so that the text can still be copied
    m_editor->setReadOnly(!enable);
    m_label->setEnabled(enable);
}


class ButtonWrapper : public QWidget
{
    // no Q_OBJECT: no need to, and don't want the useless moc file

public:
    ButtonWrapper(QWidget *wrapee, QWidget *relator)
    {
        QBoxLayout *box = new QVBoxLayout;
        box->setContentsMargins(QMargins());
        setLayout(box);
        box->addWidget(wrapee, 0, Qt::AlignBottom);
        if (relator)
            relator->installEventFilter(this);
    }

protected:
    bool eventFilter(QObject *object, QEvent *event) override
    {
        if (event->type() == QEvent::Resize) {
            QWidget *relator = static_cast<QWidget *>(object);
            setFixedHeight(relator->height());
        }
        return false;
    }
};

FormMultiWidget::FormMultiWidget(const QString &label, QWidget *parent)
        : QWidget(parent),
          m_hideWhenEmpty(false),
          m_multiEnabled(false),
          m_plusIcon(QIcon(QLatin1String(":/images/plus.png"))),  // make static
          m_minusIcon(QIcon(QLatin1String(":/images/minus.png")))
{
    m_label = new QLabel(this);
    QFont fnt;
    fnt.setBold(true);
    m_label->setFont(fnt);
    m_label->setText(label);

    m_plusButtons.append(
            new ButtonWrapper(makeButton(m_plusIcon, &FormMultiWidget::plusButtonClicked), 0));
}

QAbstractButton *FormMultiWidget::makeButton(const QIcon &icon)
{
    QAbstractButton *btn = new QToolButton(this);
    btn->setIcon(icon);
    btn->setFixedSize(icon.availableSizes().first() /* + something */);
    btn->setFocusPolicy(Qt::NoFocus);
    return btn;
}

void FormMultiWidget::addEditor(int idx)
{
    FormatTextEdit *editor = new FormatTextEdit(this);
    m_editors.insert(idx, editor);

    m_minusButtons.insert(idx, makeButton(m_minusIcon, &FormMultiWidget::minusButtonClicked));
    m_plusButtons.insert(idx + 1,
            new ButtonWrapper(makeButton(m_plusIcon, &FormMultiWidget::plusButtonClicked), editor));

    connect(editor, &QTextEdit::textChanged,
            this, &FormMultiWidget::slotTextChanged);
    connect(editor, &QTextEdit::selectionChanged,
            this, &FormMultiWidget::slotSelectionChanged);
    connect(editor, &QTextEdit::cursorPositionChanged,
            this, &FormMultiWidget::cursorPositionChanged);
    editor->installEventFilter(this);

    emit editorCreated(editor);
}

bool FormMultiWidget::eventFilter(QObject *watched, QEvent *event)
{
    int i = 0;
    while (m_editors.at(i) != watched)
        if (++i >= m_editors.size()) // Happens when deleting an editor
            return false;
    if (event->type() == QEvent::FocusOut) {
        m_minusButtons.at(i)->setToolTip(QString());
        m_plusButtons.at(i)->setToolTip(QString());
        m_plusButtons.at(i + 1)->setToolTip(QString());
    } else if (event->type() == QEvent::FocusIn) {
        m_minusButtons.at(i)->setToolTip(/*: translate, but don't change */ tr("Alt+Delete"));
        m_plusButtons.at(i)->setToolTip(/*: translate, but don't change */ tr("Shift+Alt+Insert"));
        m_plusButtons.at(i + 1)->setToolTip(/*: translate, but don't change */ tr("Alt+Insert"));
    } else if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->modifiers() & Qt::AltModifier) {
            if (ke->key() == Qt::Key_Delete) {
                deleteEditor(i);
                return true;
            } else if (ke->key() == Qt::Key_Insert) {
                if (!(ke->modifiers() & Qt::ShiftModifier))
                    ++i;
                insertEditor(i);
                return true;
            }
        }
    }
    return false;
}

void FormMultiWidget::updateLayout()
{
    delete layout();

    QGridLayout *layout = new QGridLayout;
    layout->setContentsMargins(QMargins());
    setLayout(layout);

    bool variants = m_multiEnabled && m_label->isEnabled();

    layout->addWidget(m_label, 0, 0, 1, variants ? 2 : 1);

    if (variants) {
        QVBoxLayout *layoutForPlusButtons = new QVBoxLayout;
        layoutForPlusButtons->setContentsMargins(QMargins());
        for (int i = 0; i < m_plusButtons.size(); ++i)
            layoutForPlusButtons->addWidget(m_plusButtons.at(i), Qt::AlignTop);
        layout->addLayout(layoutForPlusButtons, 1, 0, Qt::AlignTop);

        const int minimumRowHeight = m_plusButtons.at(0)->sizeHint().height() / 2.0;
        QGridLayout *layoutForLabels = new QGridLayout;
        layoutForLabels->setContentsMargins(QMargins());
        layoutForLabels->setRowMinimumHeight(0, minimumRowHeight);
        for (int j = 0; j < m_editors.size(); ++j) {
            layoutForLabels->addWidget(m_editors.at(j), 1 + j, 0, Qt::AlignVCenter);
            layoutForLabels->addWidget(m_minusButtons.at(j), 1 + j, 1, Qt::AlignVCenter);
        }
        layoutForLabels->setRowMinimumHeight(m_editors.size() + 1, minimumRowHeight);
        layout->addLayout(layoutForLabels, 1, 1, Qt::AlignTop);
    } else {
        for (int k = 0; k < m_editors.size(); ++k)
            layout->addWidget(m_editors.at(k), 1 + k, 0, Qt::AlignVCenter);
    }

    for (int i = 0; i < m_plusButtons.size(); ++i)
        m_plusButtons.at(i)->setVisible(variants);
    for (int j = 0; j < m_minusButtons.size(); ++j)
        m_minusButtons.at(j)->setVisible(variants);

    updateGeometry();
}

void FormMultiWidget::slotTextChanged()
{
    emit textChanged(static_cast<QTextEdit *>(sender()));
}

void FormMultiWidget::slotSelectionChanged()
{
    emit selectionChanged(static_cast<QTextEdit *>(sender()));
}

void FormMultiWidget::setTranslation(const QString &text, bool userAction)
{
    QStringList texts = text.split(QChar(Translator::BinaryVariantSeparator), Qt::KeepEmptyParts);

    while (m_editors.size() > texts.size()) {
        delete m_minusButtons.takeLast();
        delete m_plusButtons.takeLast();
        delete m_editors.takeLast();
    }
    while (m_editors.size() < texts.size())
        addEditor(m_editors.size());
    updateLayout();

    for (int i = 0; i < texts.size(); ++i)
        // XXX this will emit n textChanged signals
        m_editors.at(i)->setPlainText(texts.at(i), userAction);

    if (m_hideWhenEmpty)
        setHidden(text.isEmpty());
}

// Copied from QTextDocument::toPlainText() and modified to
// not replace QChar::Nbsp with QLatin1Char(' ')
QString toPlainText(const QString &text)
{
    QString txt = text;
    QChar *uc = txt.data();
    QChar *e = uc + txt.size();

    for (; uc != e; ++uc) {
        switch (uc->unicode()) {
        case 0xfdd0: // QTextBeginningOfFrame
        case 0xfdd1: // QTextEndOfFrame
        case QChar::ParagraphSeparator:
        case QChar::LineSeparator:
            *uc = QLatin1Char('\n');
            break;
        }
    }
    return txt;
}

QString FormMultiWidget::getTranslation() const
{
    QString ret;
    for (int i = 0; i < m_editors.size(); ++i) {
        if (i)
            ret += QChar(Translator::BinaryVariantSeparator);
        ret += toPlainText(m_editors.at(i)->document()->toRawText());
    }
    return ret;
}

void FormMultiWidget::setEditingEnabled(bool enable)
{
    // Use read-only state so that the text can still be copied
    for (int i = 0; i < m_editors.size(); ++i)
        m_editors.at(i)->setReadOnly(!enable);
    m_label->setEnabled(enable);
    if (m_multiEnabled)
        updateLayout();
}

void FormMultiWidget::setMultiEnabled(bool enable)
{
    m_multiEnabled = enable;
    if (m_label->isEnabled())
        updateLayout();
}

void FormMultiWidget::minusButtonClicked()
{
    int i = 0;
    while (m_minusButtons.at(i) != sender())
        ++i;
    deleteEditor(i);
}

void FormMultiWidget::plusButtonClicked()
{
    QWidget *btn = static_cast<QAbstractButton *>(sender())->parentWidget();
    int i = 0;
    while (m_plusButtons.at(i) != btn)
        ++i;
    insertEditor(i);
}

void FormMultiWidget::deleteEditor(int idx)
{
    if (m_editors.size() == 1) {
        // Don't just clear(), so the undo history is not lost
        QTextCursor c = m_editors.first()->textCursor();
        c.select(QTextCursor::Document);
        c.removeSelectedText();
    } else {
        if (!m_editors.at(idx)->toPlainText().isEmpty()) {
            if (QMessageBox::question(topLevelWidget(), tr("Confirmation - Qt Linguist"),
                                      tr("Delete non-empty length variant?"),
                                      QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes)
                != QMessageBox::Yes)
                return;
        }
        delete m_editors.takeAt(idx);
        delete m_minusButtons.takeAt(idx);
        delete m_plusButtons.takeAt(idx + 1);
        updateLayout();
        emit textChanged(m_editors.at((m_editors.size() == idx) ? idx - 1 : idx));
    }
}

void FormMultiWidget::insertEditor(int idx)
{
    addEditor(idx);
    updateLayout();
    emit textChanged(m_editors.at(idx));
}

QT_END_NAMESPACE