Debian Codegraph @

avogadro/qtopengl/qttextrenderstrategy.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "qttextrenderstrategy.h"
7
8 #include <avogadro/rendering/textproperties.h>
9
10 #include <QtGui/QFont>
11 #include <QtGui/QFontMetrics>
12 #include <QtGui/QImage>
13 #include <QTransform>
14 #include <QtGui/QPainter>
15 #include <QtGui/QPolygonF>
16
17 #include <QtWidgets/QApplication>
18
19 #include <QtCore/QDebug>
20 #include <QtCore/QPoint>
21 #include <QtCore/QRectF>
22 #include <QtCore/QSysInfo>
23
24 #include <cmath>
25
26 using Avogadro::Rendering::TextProperties;
27
28 namespace {
29
30 inline Qt::Alignment textPropertiesToAlignment(const TextProperties& prop)
31 {
32 // This is initialized with no flags set as we want, no need to initialize.
33 Qt::Alignment result;
34
35 switch (prop.hAlign()) {
36 default:
37 case TextProperties::HLeft:
38 result |= Qt::AlignLeft;
39 break;
40 case TextProperties::HCenter:
41 result |= Qt::AlignHCenter;
42 break;
43 case TextProperties::HRight:
44 result |= Qt::AlignRight;
45 break;
46 }
47
48 switch (prop.vAlign()) {
49 default:
50 case TextProperties::VTop:
51 result |= Qt::AlignTop;
52 break;
53 case TextProperties::VCenter:
54 result |= Qt::AlignVCenter;
55 break;
56 case TextProperties::VBottom:
57 result |= Qt::AlignBottom;
58 break;
59 }
60
61 return result;
62 }
63
64 inline QFont textPropertiesToQFont(const TextProperties& prop)
65 {
66 QString family;
67 switch (prop.fontFamily()) {
68 case TextProperties::SansSerif:
69 #ifndef Q_OS_MAC
70 family = "SansSerif";
71 #else
72 family = QApplication::font().family();
73 #endif
74 break;
75 case TextProperties::Serif:
76 #ifndef Q_OS_MAC
77 family = "serif";
78 #else
79 family = "Times";
80 #endif
81 break;
82 case TextProperties::Mono:
83 #ifndef Q_OS_MAC
84 family = "mono";
85 #else
86 family = "Menlo";
87 #endif
88 break;
89 default:
90 qWarning() << "Unknown font family id: " << prop.fontFamily()
91 << "Defaulting to SansSerif.";
92 family = QApplication::font().family();
93 }
94
95 TextProperties::FontStyles style = prop.fontStyles();
96
97 QFont result(family, static_cast<int>(prop.pixelHeight()) / 2 + 1,
98 static_cast<bool>(style & TextProperties::Bold) ? QFont::Bold
99 : QFont::Normal,
100 static_cast<bool>(style & TextProperties::Italic));
101 result.setUnderline(static_cast<bool>(style & TextProperties::Underline));
102
103 // Scale the font size to match the specified pixel height:
104 QFontMetricsF metrics(result);
105 int iterLimiter = 0; // no more than 5 iterations below:
106 do {
107 result.setPointSizeF(result.pointSizeF() *
108 static_cast<qreal>(prop.pixelHeight()) /
109 metrics.height());
110
111 metrics = QFontMetricsF(result);
112 } while (
113 std::fabs(metrics.height() - static_cast<qreal>(prop.pixelHeight())) >
114 static_cast<qreal>(0.5) &&
115 iterLimiter++ < 5);
116
117 return result;
118 }
119
120 } // namespace
121
122 namespace Avogadro::QtOpenGL {
123
124 QtTextRenderStrategy::QtTextRenderStrategy() {}
125
126 QtTextRenderStrategy::~QtTextRenderStrategy() {}
127
128 Rendering::TextRenderStrategy* QtTextRenderStrategy::newInstance() const
129 {
130 return new QtTextRenderStrategy;
131 }
132
133 void QtTextRenderStrategy::boundingBox(const std::string& string,
134 const Rendering::TextProperties& tprop,
135 int bbox[]) const
136 {
137 QRect rect;
138 const QFont font(textPropertiesToQFont(tprop));
139 const Qt::Alignment align(textPropertiesToAlignment(tprop));
140 rect = QFontMetrics(font).boundingRect(rect, align,
141 QString::fromStdString(string));
142 // Rotate if needed
143 if (tprop.rotationDegreesCW() != 0.f) {
144 // Build transformation
145 QTransform transform;
146 transform.rotate(static_cast<qreal>(-tprop.rotationDegreesCW()));
147
148 // Transform a floating point representation of the bbox
149 QRectF tmpRect(rect);
150 tmpRect = transform.mapRect(tmpRect);
151
152 // Update the bbox, rounding values to give the largest containing bbox
153 rect.setLeft(static_cast<int>(std::floor(tmpRect.left())));
154 rect.setRight(static_cast<int>(std::floor(tmpRect.right())));
155 rect.setTop(static_cast<int>(std::ceil(tmpRect.top())));
156 rect.setBottom(static_cast<int>(std::floor(tmpRect.bottom())));
157 }
158
159 bbox[0] = rect.left();
160 bbox[1] = rect.right();
161 bbox[2] = rect.top();
162 bbox[3] = rect.bottom();
163 }
164
165 void QtTextRenderStrategy::render(const std::string& string,
166 const Rendering::TextProperties& tprop,
167 unsigned char* buffer,
168 const Vector2i& dims) const
169 {
170 // Convert inputs to Qt
171 QString str = QString::fromStdString(string);
172 Qt::Alignment flags = textPropertiesToAlignment(tprop);
173 QFont font = textPropertiesToQFont(tprop);
174
175 // Construct our target image to use the input buffer and clear it.
176 QImage target(buffer, dims[0], dims[1], QImage::Format_ARGB32_Premultiplied);
177 target.fill(qRgba(0, 0, 0, 0));
178
179 // Painter setup
180 QPainter painter(&target);
181 painter.setFont(font);
182
183 // Get a tight bbox for the text without rotations:
184 QRectF textRect(painter.boundingRect(QRectF(), flags, str));
185
186 // Undo any alignment translations of the bbox.
187 textRect.translate(-textRect.topLeft());
188
189 // Apply rotation, if any
190 auto rot(static_cast<qreal>(tprop.rotationDegreesCW()));
191 if (rot != 0.f) {
192 // Rotate the painter:
193 painter.rotate(static_cast<qreal>(rot));
194
195 // Convert the bbox into a polygon and rotate it
196 QPolygonF textCorners(textRect);
197 textCorners = painter.transform().map(textCorners);
198
199 // Find the new origin in the rotated space:
200 QPointF newOrigin(-textCorners.boundingRect().topLeft());
201
202 // Rotate the point back (drawText will reapply the rotation)
203 newOrigin = painter.transform().inverted().map(newOrigin);
204
205 // Account for the rotation in the bbox:
206 textRect.translate(newOrigin);
207 }
208
209 // Draw the text
210 painter.setPen(
211 QColor(tprop.red(), tprop.green(), tprop.blue(), tprop.alpha()));
212 painter.drawText(textRect, flags, str);
213 painter.end();
214
215 // Convert the buffer from ARGB --> RGBA for openGL by default
216 if (!m_preserveArgb)
217 argbToRgba(buffer, dims[0] * dims[1]);
218 }
219
220 namespace {
221
222 template <int ByteOrder>
223 inline void argbToRgbaWorker(quint32 in, quint32& out)
224 {
225 Q_UNUSED(in)
226 Q_UNUSED(out)
227 qWarning("QtTextRenderStrategy::argbToRgba: Invalid byte order.");
228 }
229
230 template <>
231 inline void argbToRgbaWorker<QSysInfo::BigEndian>(quint32 in, quint32& out)
232 {
233 out = ((in >> 24) & 0xff) | (in << 8);
234 }
235
236 template <>
237 inline void argbToRgbaWorker<QSysInfo::LittleEndian>(quint32 in, quint32& out)
238 {
239 out = ((in << 16) & 0xff0000) | ((in >> 16) & 0xff) | (in & 0xff00ff00);
240 }
241
242 } // namespace
243
244 void QtTextRenderStrategy::argbToRgba(unsigned char* buffer, size_t pixels)
245 {
246 // Adapted from QGLWidget::convertToGLFormat to perform the conversion
247 // in-place.
248 // input: 0xAARRGGBB
249 // output: 0xRRGGBBAA (big endian)
250 // output: 0xAABBGGRR (little endian)
251
252 auto* cur = reinterpret_cast<quint32*>(buffer);
253 quint32* end = &cur[pixels];
254
255 while (cur < end) {
256 // Ignore empty pixels
257 if (*cur)
258 argbToRgbaWorker<QSysInfo::ByteOrder>(*cur, *cur);
259 cur++;
260 }
261 }
262
263 } // namespace Avogadro::QtOpenGL