aboutsummaryrefslogtreecommitdiff
path: root/src/views/mlabelview_simple.cpp
blob: 7a8c26badee5308ba883044af509643c2f2e8592 (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
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mlabelview.h"
#include "mlabelview_p.h"
#include "mlabelmodel.h"
#include "mlabel.h"
#include "mviewcreator.h"

#include <QPainter>
#include <QTextDocument>
#include <QTextCursor>
#include <QTransform>
#include <QFontMetrics>
#include <QPixmapCache>
#include <QAbstractTextDocumentLayout>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneResizeEvent>
#include <QGestureEvent>
#include <QTapAndHoldGesture>


MLabelViewSimple::MLabelViewSimple(MLabelViewPrivate *viewPrivate) :
    viewPrivate(viewPrivate), preferredSize(-1, -1), textOffset(), paintingRect(), dirty(true), staticText()
{
    staticText.setTextFormat(Qt::PlainText);
}

MLabelViewSimple::~MLabelViewSimple()
{
}

void MLabelViewSimple::drawContents(QPainter *painter, const QSizeF &size)
{
    Q_UNUSED(size);

    initializeStaticText();
    if (staticText.text().isEmpty() || paintingRect.isEmpty()) {
        return;
    }

    const MLabelModel *model = viewPrivate->model();
    const MLabelStyle *style = viewPrivate->style();

    painter->setPen(model->color().isValid() ? model->color() : style->color());
    painter->setFont(viewPrivate->controller->font());
    painter->setRenderHint(QPainter::TextAntialiasing);
    painter->setLayoutDirection(model->textDirection());

    const bool clip =    textOffset.x() < paintingRect.x()
                      || textOffset.y() < paintingRect.y()
                      || textOffset.x() + staticText.size().width()  > paintingRect.right()
                      || textOffset.y() + staticText.size().height() > paintingRect.bottom();

    if (clip) {
        painter->save();
        painter->setClipRect(paintingRect, Qt::IntersectClip);
        painter->drawStaticText(textOffset, staticText);
        painter->restore();
    } else {
        painter->drawStaticText(textOffset, staticText);
    }
}

bool MLabelViewSimple::resizeEvent(QGraphicsSceneResizeEvent *event)
{
    // There is no way to specify sizeHint for a text without knowing possible width.
    // 1st phase, when Qt calls sizeHint, view will return approximate values for
    // minimum and preferred size. When resizeEvent comes, layout already knows
    // sizes of components, and here comes
    // 2nd phase, when we identify widget's height, based on width. Our height will
    // change and we don't want to occupy more space then need, so we have to call
    // updateGeometry, to tell layout to update sizeHint cache. This function
    // return true if such update is needed.

    QFontMetricsF fm(viewPrivate->controller->font());

    QString text = viewPrivate->model()->text();

    // If the text represents a multilength-string, only respect the first
    // (= longest) text for the bounding rectangle.
    const QChar multiLengthSeparator(0x9c, 0);
    const int index = text.indexOf(multiLengthSeparator);
    if (index >= 0) {
        text = text.left(index);
    }

    QRectF bR = fm.boundingRect(QRectF(QPoint(0, 0), event->newSize()), 
                                viewPrivate->textOptions.alignment() | textFlagForWrapMode(),
                                text);
    if (bR.height() > fm.height()) {
        preferredSize = QSizeF(bR.width(), bR.height());
        return true;
    } else
        return false;
}

QSizeF MLabelViewSimple::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
    switch (which) {
    case Qt::MinimumSize: {
        QFontMetricsF fm(viewPrivate->controller->font());
        return QSizeF(fm.width(QLatin1Char('x')), fm.height());
    }
    case Qt::PreferredSize: {
        QSizeF maxSize = sizeForConstraint(constraint);
        if (preferredSize.width() >= 0 && preferredSize.width() < maxSize.width()) {
            maxSize.rwidth() = preferredSize.width();
        }
        if (preferredSize.height() >= 0 && preferredSize.height() < maxSize.height()) {
            maxSize.rheight() = preferredSize.height();
        }

        return sizeForWidth(maxSize.width()).boundedTo(maxSize);
    }
    case Qt::MaximumSize: {
        return QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
    }
    default:
        qWarning("MLabel::sizeHint() don't know how to handle the value of 'which' ");
    }

    return QSizeF(0, 0);
}

void MLabelViewSimple::setupModel()
{
    viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection());
    viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment());
    if (viewPrivate->model()->wordWrap()) {
        viewPrivate->textOptions.setWrapMode(viewPrivate->model()->wrapMode());
    } else {
        viewPrivate->textOptions.setWrapMode(QTextOption::NoWrap);
    }
    viewPrivate->previousStaticTextSize = staticText.size();
}

bool MLabelViewSimple::updateData(const QList<const char *>& modifications)
{
    const char *member = NULL;
    bool needUpdate = false;

    const MLabelModel *model = viewPrivate->model();

    foreach(member, modifications) {
        if (member == MLabelModel::Text) {
            preferredSize = QSizeF(-1, -1);
            needUpdate = viewPrivate->previousStaticTextSize != staticText.size();
            viewPrivate->previousStaticTextSize = staticText.size();
        } else if (member == MLabelModel::Color) {
            needUpdate = true;
        } else if(member == MLabelModel::WrapMode) {
            if (model->wordWrap()) {
                viewPrivate->textOptions.setWrapMode(model->wrapMode());
            }
            needUpdate = true;
        } else if (member == MLabelModel::WordWrap) {
            if (model->wordWrap()) {
                viewPrivate->textOptions.setWrapMode(model->wrapMode());
            } else {
                viewPrivate->textOptions.setWrapMode(QTextOption::NoWrap);
            }
            needUpdate = true;
        } else if (member == MLabelModel::TextDirection) {
            needUpdate = true;
            viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection());
        } else if (member == MLabelModel::Alignment) {
            viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment());
        } else if (member == MLabelModel::UseModelFont || member == MLabelModel::Font) {
            needUpdate = true;
        }
    }
    return needUpdate;
}

bool MLabelViewSimple::isRich()
{
    return false;
}

void MLabelViewSimple::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    event->ignore(); //propagate link up to owner of label
}

void MLabelViewSimple::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
}

void MLabelViewSimple::cancelEvent(MCancelEvent *event)
{
    Q_UNUSED(event);
}

void MLabelViewSimple::longPressEvent(QGestureEvent *event, QTapAndHoldGesture* gesture)
{
    event->ignore(gesture);
}

void MLabelViewSimple::orientationChangeEvent(MOrientationChangeEvent *event)
{
    Q_UNUSED(event);
}

void MLabelViewSimple::applyStyle()
{
    if (viewPrivate->model()->alignmentFromStyle())
        const_cast<MLabelModel*>(viewPrivate->model())->setAlignment(viewPrivate->style()->horizontalAlignment() | viewPrivate->style()->verticalAlignment());
}

void MLabelViewSimple::initializeStaticText()
{
    if (!dirty) {
        return;
    }

    dirty = false;

    const MLabelStyle *style = viewPrivate->style();

    paintingRect = (viewPrivate->textOptions.textDirection() == Qt::LeftToRight)
        ? viewPrivate->boundingRect().adjusted(style->paddingLeft(), style->paddingTop(), -style->paddingRight(), -style->paddingBottom())
        : viewPrivate->boundingRect().adjusted(style->paddingRight(), style->paddingTop(), -style->paddingLeft(), -style->paddingBottom());
    textOffset = paintingRect.topLeft().toPoint();

    unconstraintText = textToRender(QWIDGETSIZE_MAX);
    const QString text = textToRender(paintingRect.width());

    staticText.setTextWidth(paintingRect.width());
    staticText.setTextOption(viewPrivate->textOptions);
    staticText.setText(text);
    staticText.prepare(QTransform(), viewPrivate->controller->font());

    adjustTextOffset();
}

QString MLabelViewSimple::textToRender(qreal width) const
{
    QString text = viewPrivate->model()->text();

    const QChar multiLengthSeparator(0x9c, 0);
    if (text.contains(multiLengthSeparator)) {
        // The text consists of several strings. Find the first string that fits into the
        // available width. If no string has been found, the last string will be used.
        const QStringList strings = text.split(multiLengthSeparator);
        const QFontMetricsF metrics(viewPrivate->controller->font());
        foreach (const QString &string, strings) {
            text = string;
            if (metrics.width(text) <= width) {
                break;
            }
        }
    }

    if (viewPrivate->model()->textElide() && text.size() > 4) {
        QFontMetrics metrics(viewPrivate->controller->font());
        text = metrics.elidedText(text, Qt::ElideRight, width);
    }

    // QStaticText uses QTextLayout internally to render text. Contrary to
    // QPainter::drawText(const QRect &rectangle, ...) no pre-preparation of the
    // text is done (e. g. replace \n by QChar::LineSeparator or spaces dependent
    // on the wrapping). This is done manually here:
    if (wrap()) {
        text.replace(QLatin1Char('\n'), QChar::LineSeparator);
    } else {
        // The text should be shown in a single line. Replace all line breaks by a space.
        for (int i = 0; i < text.length(); ++i) {
            const QChar chr = text.at(i);
            if (chr == QLatin1Char('\n') || chr == QChar::LineSeparator) {
                text[i] = QLatin1Char(' ');
            }
        }
    }

    return text;
}

qreal MLabelViewSimple::restrictedTextWidth(const QString &text, qreal width) const
{   
    qreal textWidth = -1.0;
    if (wrap()) {
        const QFontMetricsF metrics(viewPrivate->controller->font());
        textWidth = metrics.boundingRect(text).width();
        if (textWidth > width) {
            textWidth = width;
        }
    }
    return textWidth;
}

bool MLabelViewSimple::wrap() const
{
    const QTextOption::WrapMode wrapMode = viewPrivate->model()->wrapMode();
    return viewPrivate->controller->wordWrap()
           && (wrapMode != QTextOption::NoWrap)
           && (wrapMode != QTextOption::ManualWrap);
}

Qt::TextFlag MLabelViewSimple::textFlagForWrapMode() const
{
    Qt::TextFlag textFlag = Qt::TextSingleLine;
    if (viewPrivate->controller->wordWrap()) {
        const QTextOption::WrapMode wrapMode = viewPrivate->model()->wrapMode();
        if (wrapMode == QTextOption::WordWrap) {
            textFlag = Qt::TextWordWrap;
        } else if (wrapMode == QTextOption::WrapAnywhere || wrapMode == QTextOption::WrapAtWordBoundaryOrAnywhere) {
            textFlag = Qt::TextWrapAnywhere;
        }
    }
    return textFlag;
}

void MLabelViewSimple::adjustTextOffset()
{
    const MLabelModel *model = viewPrivate->model();
    Qt::Alignment alignment = viewPrivate->textOptions.alignment();
    if (model->textDirection() == Qt::RightToLeft && !(alignment & Qt::AlignHCenter)) {
        // Mirror the horizontal alignment
        if (alignment & Qt::AlignRight) {
            alignment = (alignment | Qt::AlignLeft) & ~Qt::AlignRight;
        } else {
            alignment = (alignment | Qt::AlignRight) & ~Qt::AlignLeft;
        }
    }

    // Adjust x-position dependent on the horizontal alignment
    if (alignment & Qt::AlignHCenter) {
        textOffset.rx() += (paintingRect.width() - staticText.size().width()) / 2.0;
    } else if (alignment & Qt::AlignRight) {
        textOffset.setX(paintingRect.right() - staticText.size().width());
    }

    // Adjust y-position dependent on the vertical alignment
    if (alignment & Qt::AlignVCenter) {
        textOffset.ry() += (paintingRect.height() - staticText.size().height()) / 2.0;
    } else if (alignment & Qt::AlignBottom) {
        textOffset.setY(paintingRect.bottom() - staticText.size().height());
    }
}

QSizeF MLabelViewSimple::sizeForWidth(qreal width) const
{
    if (width == QWIDGETSIZE_MAX) {
        width = -1.0;
    }

    const_cast<MLabelViewSimple*>(this)->initializeStaticText();

    const bool equalWidth = (width < 0.0 && staticText.textWidth() < 0.0) || width == staticText.textWidth();
    if (equalWidth && staticText.text() == unconstraintText) {
        return staticText.size();
    }

    QStaticText staticText2(staticText);
    staticText2.setTextOption(staticText.textOption());  // TODO: remove after Qt-bug #13368 has been fixed
    staticText2.setTextWidth(width);
    if (staticText2.text() != unconstraintText) {
        staticText2.setText(unconstraintText);
    }
    staticText2.prepare(QTransform(), viewPrivate->controller->font());

    return staticText2.size();
}

QSizeF MLabelViewSimple::sizeForConstraint(const QSizeF &constraint) const
{
    QSizeF size = constraint;
    if (size.width() < 0.0) {
        size.setWidth(QWIDGETSIZE_MAX);
    }
    if (size.height() < 0.0) {
        size.setHeight(QWIDGETSIZE_MAX);
    }
    return size;
}

void MLabelViewSimple::markDirty()
{
    dirty = true;
}