SILICON
Loading...
Searching...
No Matches
graphicalText.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
7#include "graphicalText.hpp"
8
9#include <algorithm>
10#include <cmath>
11#include <limits>
12#include <memory>
13#include <stdexcept>
14#include <tuple>
15#include <vector>
16
17#include <QAbstractTextDocumentLayout>
18#include <QFontMetricsF>
19#include <QGraphicsTextItem>
20#include <QImage>
21#include <QObject>
22#include <QPainter>
23#include <QTextBlock>
24#include <QTextCharFormat>
25#include <QTextCursor>
26#include <QTextDocument>
27#include <QTextLayout>
28#include <QTextOption>
29
30#include <jkqtmathtext/jkqtmathtext.h>
31
32#include <ui/shell/theme.hpp>
33
34namespace SILICON::ui {
35namespace {
36
37 const StringPropertyOptions FontOptions{"Quicksand", "Chango", "NovaMono"};
38
39 // Inline objects let Qt wrap prose around vector-rendered equations and include
40 // their full height when measuring annotations and resizing them.
41 class MathTextObjects : public QObject, public QTextObjectInterface {
42 Q_OBJECT
43 Q_INTERFACES(QTextObjectInterface)
44
45 public:
46 static constexpr int ObjectType = QTextFormat::UserObject;
47 static constexpr int FormulaIndex = QTextFormat::UserProperty;
48
49 void registerWith(QTextDocument* document)
50 {
51 document->documentLayout()->registerHandler(ObjectType, this);
52 }
53
54 bool insert(QTextCursor& cursor, QStringView source, const QTextCharFormat& format)
55 {
56 auto math = std::make_unique<JKQTMathText>();
57 math->setFontSize(cursor.document()->defaultFont().pointSizeF());
58 math->setFontRoman(cursor.document()->defaultFont().family());
59 math->setFontOption(JKQTMathText::BaseFontBold, format.fontWeight() >= QFont::Bold);
60 math->setFontOption(JKQTMathText::BaseFontItalic, format.fontItalic());
61 if (!math->parse(source.toString()))
62 return false;
63
64 QImage device(1, 1, QImage::Format_ARGB32_Premultiplied);
65 QPainter painter(&device);
66 const auto size = math->getSize(painter);
67 if (!size.isValid() || size.isEmpty())
68 return false;
69
70 auto objectFormat = format;
71 objectFormat.setObjectType(ObjectType);
72 objectFormat.setProperty(FormulaIndex, static_cast<int>(formulas.size()));
73 objectFormat.setVerticalAlignment(QTextCharFormat::AlignMiddle);
74 formulas.push_back({std::move(math), size});
75 cursor.insertText(QString(QChar::ObjectReplacementCharacter), objectFormat);
76 return true;
77 }
78
79 QSizeF intrinsicSize(QTextDocument*, int, const QTextFormat& format) override
80 {
81 return formulas.at(format.intProperty(FormulaIndex)).size;
82 }
83
84 void drawObject(QPainter* painter, const QRectF& rect, QTextDocument*, int,
85 const QTextFormat& format) override
86 {
87 auto& math = *formulas.at(format.intProperty(FormulaIndex)).math;
88 painter->save();
89 painter->setRenderHint(QPainter::Antialiasing);
90 painter->setRenderHint(QPainter::TextAntialiasing);
92 math.draw(*painter, Qt::AlignCenter, rect);
93 painter->restore();
94 }
95
96 private:
97 struct Formula {
98 std::unique_ptr<JKQTMathText> math;
99 QSizeF size;
100 };
101 std::vector<Formula> formulas;
102 };
103
104 bool isFormattingCharacter(QChar character)
105 {
106 return std::ranges::contains(QStringView(u"*_$\\"), character);
107 }
108
109 qsizetype findClosingDelimiter(QStringView text, QChar delimiter)
110 {
111 bool escaped = false;
112 for (qsizetype index = 0; index < text.size(); ++index) {
113 const auto character = text[index];
114 if (delimiter != '$' && (character == '\n' || character == '\r'))
115 break;
116 if (!escaped && character == delimiter)
117 return index;
118 // Emphasis delimiters inside an equation belong to LaTeX.
119 if (!escaped && character == '$' && delimiter != '$') {
120 const auto length = findClosingDelimiter(text.mid(index + 1), '$');
121 if (length >= 0)
122 index += length + 1;
123 }
124 escaped = !escaped && character == '\\';
125 }
126 return -1;
127 }
128
129 void insertFormattedText(QTextCursor& cursor, MathTextObjects& math, QStringView text,
130 const QTextCharFormat& format = {})
131 {
132 QString plain;
133 for (qsizetype index = 0; index < text.size();) {
134 const auto character = text[index++];
135 if (character == '\\' && index < text.size()
136 && isFormattingCharacter(text[index])) {
137 plain += text[index++];
138 continue;
139 }
140
141 const auto length = character == '*' || character == '_' || character == '$'
142 ? findClosingDelimiter(text.mid(index), character)
143 : -1;
144 // Unmatched and empty delimiters stay visible as ordinary text.
145 if (length <= 0) {
146 plain += character;
147 continue;
148 }
149
150 cursor.insertText(plain, format);
151 plain.clear();
152 if (character == '$') {
153 const auto source = text.mid(index - 1, length + 2);
154 if (!math.insert(cursor, source, format))
155 cursor.insertText(source.toString(), format);
156 index += length + 1;
157 continue;
158 }
159 auto emphasis = format;
160 if (character == '*')
161 emphasis.setFontWeight(QFont::Bold);
162 else
163 emphasis.setFontItalic(true);
164 insertFormattedText(cursor, math, text.mid(index, length), emphasis);
165 index += length + 1;
166 }
167 cursor.insertText(plain, format);
168 }
169
170 class TextShape : public QGraphicsTextItem {
171 public:
172 TextShape(const QString& text, const QFont& font, int wrapWidth)
173 {
174 setAcceptedMouseButtons(Qt::NoButton);
175 setAcceptHoverEvents(false);
176 setTextInteractionFlags(Qt::NoTextInteraction);
177 document()->setDocumentMargin(0);
178 auto option = document()->defaultTextOption();
179 option.setWrapMode(QTextOption::WordWrap);
180 document()->setDefaultTextOption(option);
181 setFont(font);
182 math.registerWith(document());
183 QTextCursor cursor(document());
184 insertFormattedText(cursor, math, text);
185 // Measure the formatted text once; probes never alter the live item's geometry.
186 measurement.reset(document()->clone());
187 math.registerWith(measurement.get());
188 measurement->setTextWidth(1);
189 (void)measurement->size();
190 for (auto block = measurement->begin(); block.isValid(); block = block.next()) {
191 auto* layout = block.layout();
192 for (int line = 0; line < layout->lineCount(); ++line)
193 minimumWidth = std::max(minimumWidth, layout->lineAt(line).naturalTextWidth());
194 }
195 measurement->setTextWidth(-1);
196 (void)measurement->size();
197 for (auto block = measurement->begin(); block.isValid(); block = block.next()) {
198 naturalWidth = std::max(naturalWidth, block.layout()->maximumWidth());
199 }
200 setWrapWidth(wrapWidth);
201 }
202
203 int clampWidth(qreal width) const
204 {
205 return static_cast<int>(std::clamp(std::ceil(std::max(width, minimumWidth)), 1.0,
206 double(std::numeric_limits<int>::max())));
207 }
208
209 void setWrapWidth(int width) { setTextWidth(width > 0 ? clampWidth(width) : -1); }
210
211 int automaticWidth() const { return clampWidth(naturalWidth); }
212
213 int widthForHeight(qreal height, int startingWidth)
214 {
215 const int minimum = clampWidth(minimumWidth);
216 const int maximum = std::max(automaticWidth(), startingWidth);
217 const int start = startingWidth > 0 ? clampWidth(startingWidth) : maximum;
218 auto heightAt = [this](int width) {
219 measurement->setTextWidth(width);
220 return measurement->size().height();
221 };
222 int low = minimum;
223 int high = maximum;
224 while (low < high) {
225 const int middle = low + (high - low) / 2;
226 if (heightAt(middle) > height)
227 low = middle + 1;
228 else
229 high = middle;
230 }
231 int best = start;
232 // A whole interval of widths can produce the same height. Choose its point
233 // nearest the starting width rather than jumping to the narrowest box.
234 auto nearestWidth = [&](int width) {
235 const qreal lineHeight = heightAt(width);
236 int first = minimum;
237 int last = maximum;
238 while (first < last) {
239 const int middle = first + (last - first) / 2;
240 if (heightAt(middle) > lineHeight)
241 first = middle + 1;
242 else
243 last = middle;
244 }
245 const int lower = first;
246 last = maximum;
247 while (first < last) {
248 const int middle = first + (last - first) / 2 + 1;
249 if (heightAt(middle) >= lineHeight)
250 first = middle;
251 else
252 last = middle - 1;
253 }
254 return std::clamp(start, lower, first);
255 };
256 auto score = [&](int width) {
257 return std::tuple{std::abs(heightAt(width) - height), std::abs(width - start),
258 -width};
259 };
260 auto bestScore = score(best);
261 for (int candidateWidth : {low, std::max(minimum, low - 1)}) {
262 const int width = nearestWidth(candidateWidth);
263 const auto candidate = score(width);
264 if (candidate < bestScore) {
265 best = width;
266 bestScore = candidate;
267 }
268 }
269 return best;
270 }
271
272 int legacyWrapWidth(int length) const
273 {
274 if (length == 0)
275 return 0;
276 std::unique_ptr<QTextDocument> legacy(document()->clone());
277 // QTextDocument::clone() does not copy custom object handlers.
278 math.registerWith(legacy.get());
279 legacy->setTextWidth(-1);
280 QTextCursor cursor(legacy.get());
281 for (auto block = legacy->begin(); block.isValid(); block = block.next()) {
282 if (block.length() - 1 <= length)
283 continue;
284 cursor.setPosition(block.position());
285 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, length);
286 if (cursor.block() == block && !cursor.atBlockEnd())
287 cursor.insertBlock();
288 }
289 return clampWidth(legacy->idealWidth());
290 }
291
292 QRectF boundingRect() const override
293 {
294 // Empty annotations must remain easy to select and edit.
295 return QGraphicsTextItem::boundingRect().united(
296 QRectF(0, 0, GRID_SIZE, QFontMetricsF(font()).height()));
297 }
298
299 void paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
300 QWidget* widget) override
301 {
303 if (defaultTextColor() != ink)
304 setDefaultTextColor(ink);
305 QGraphicsTextItem::paint(painter, option, widget);
306 }
307
308 private:
309 mutable MathTextObjects math;
310 std::unique_ptr<QTextDocument> measurement;
311 qreal minimumWidth = GRID_SIZE;
312 qreal naturalWidth = GRID_SIZE;
313 };
314
315} // namespace
316
318{
319 hiddenProperties.insert("wrapWidth");
320 // Keep annotations above circuit components and wires, regardless of insertion order.
321 setZValue(1);
323}
324
325std::optional<std::reference_wrapper<const StringPropertyOptions>>
327{
328 if (key == "font")
329 return std::cref(FontOptions);
330 return std::nullopt;
331}
332
334{
335 const auto* text = std::get_if<std::string>(&next.at("text"));
336 const auto* size = std::get_if<int>(&next.at("size"));
337 const auto* font = std::get_if<std::string>(&next.at("font"));
338 const auto* wrapWidth = std::get_if<int>(&next.at("wrapWidth"));
339 if (!text || !size || !font || !wrapWidth)
340 throw std::invalid_argument(
341 "Text properties require text, integer size, font, and integer wrapWidth");
342 if (*size <= 0)
343 throw std::invalid_argument("Text size must be a positive number of points");
344 if (*wrapWidth < 0)
345 throw std::invalid_argument("Text wrapWidth must be non-negative");
346 if (!std::ranges::contains(FontOptions, *font))
347 throw std::invalid_argument("Text font must be Quicksand, Chango, or NovaMono");
348
349 if (auto* existing = dynamic_cast<TextShape*>(getItemShape());
350 existing && next.at("text") == properties.at("text")
351 && next.at("size") == properties.at("size")
352 && next.at("font") == properties.at("font")) {
354 existing->setWrapWidth(*wrapWidth);
355 update();
356 } else {
357 auto shape = std::make_unique<TextShape>(QString::fromStdString(*text),
358 QFont(QString::fromStdString(*font), *size),
359 *wrapWidth);
360 setItemShape(shape.release());
361 }
362 properties = std::move(next);
363}
364
366 const PropertyMap& initial)
367{
368 auto next = initial;
369 auto* shape = static_cast<TextShape*>(getItemShape());
370 const int startingWidth = std::get<int>(initial.at("wrapWidth"));
371 const int width = resizesLeft(handle) || resizesRight(handle)
372 ? shape->clampWidth(size.width())
373 : shape->widthForHeight(size.height(), startingWidth);
374 // Keep automatic width when the reflow has not actually changed the box.
375 const int initialWidth =
376 startingWidth > 0 ? shape->clampWidth(startingWidth) : shape->automaticWidth();
377 if (width == initialWidth)
378 return next;
379 next.at("wrapWidth") = width;
380 return next;
381}
382
383void GraphicalText::applyProperty(std::string_view key, const PropertyValue& value)
384{
385 const auto found = properties.find(key);
386 if (found == properties.end())
387 throw std::invalid_argument("Unknown text property: " + std::string(key));
388 if (found->second == value)
389 return;
390 auto next = properties;
391 next.at(std::string(key)) = value;
392 setProperties(std::move(next));
393}
394
395nlohmann::ordered_json GraphicalText::serialize() const
396{
397 auto json = GraphicalComponent::serialize();
398 json["properties"] = {{"text", std::get<std::string>(properties.at("text"))},
399 {"size", std::get<int>(properties.at("size"))},
400 {"font", std::get<std::string>(properties.at("font"))},
401 {"wrapWidth", std::get<int>(properties.at("wrapWidth"))}};
402 return json;
403}
404
405void GraphicalText::loadSerializedState(const nlohmann::json& json)
406{
407 if (!json.contains("properties"))
408 return;
409 const auto& values = json.at("properties");
410 if (!values.is_object())
411 throw std::invalid_argument("Text properties must be an object");
412 auto next = properties;
413 if (values.contains("text"))
414 next.at("text") = values.at("text").get<std::string>();
415 for (const auto& [key, minimum] : {std::pair{"size", 1}, std::pair{"wrapWidth", 0}}) {
416 if (!values.contains(key))
417 continue;
418 const auto& value = values.at(key);
419 if (!value.is_number_integer() || value < minimum
420 || value > std::numeric_limits<int>::max())
421 throw std::invalid_argument(std::string(key)
422 + " must be an integer >= " + std::to_string(minimum));
423 next.at(key) = value.get<int>();
424 }
425 if (values.contains("font"))
426 next.at("font") = values.at("font").get<std::string>();
427 if (!values.contains("wrapWidth") && values.contains("wrapLength")) {
428 const auto& length = values.at("wrapLength");
429 if (!length.is_number_integer() || length < 0
430 || length > std::numeric_limits<int>::max())
431 throw std::invalid_argument("Text wrapLength must be a non-negative integer");
432 // Validate all properties before constructing the temporary migration layout.
433 GraphicalText legacy;
434 legacy.setProperties(next);
435 next.at("wrapWidth") = static_cast<TextShape*>(legacy.getItemShape())
436 ->legacyWrapWidth(length.get<int>());
437 }
438 setProperties(std::move(next));
439}
440
441} // namespace SILICON::ui
442
443#include "graphicalText.moc"
void prepareSceneBoundsChange()
Prepares a geometry edit and checks its final bounds on the event loop.
GraphicalComponent(ItemCategory category, QGraphicsItem *shape, QGraphicsItem *parent=nullptr, bool scanShape=false)
virtual nlohmann::ordered_json serialize() const
Serializes the component to JSON.
std::unordered_set< std::string, TransparentStringHash, std::equal_to<> > hiddenProperties
Property names hidden from the panel, still accessible and serialized. Add names in subclasses with h...
QGraphicsItem * getItemShape() const
Gets the component shape.
void setItemShape(QGraphicsItem *shape)
Sets the component shape graphics item.
void applyProperty(std::string_view key, const PropertyValue &value) override
nlohmann::ordered_json serialize() const override
Serializes the component to JSON.
std::optional< std::reference_wrapper< const StringPropertyOptions > > getStringPropertyOptions(std::string_view key) const override
PropertyMap resizedProperties(QSizeF size, ResizeHandle handle, const PropertyMap &initial) override
void setProperties(PropertyMap next)
void loadSerializedState(const nlohmann::json &json) override
Loads subclass-specific serialized state.
GraphicalText(QGraphicsItem *parent=nullptr)
static const QColor & getColor(theme::ColorToken token)
Definition theme.hpp:92
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
std::unordered_map< std::string, PropertyValue, TransparentStringHash, TransparentStringEqual > PropertyMap
Map from property names to their values.
std::vector< std::string > StringPropertyOptions
Allowed values for a constrained string property.
bool resizesRight(ResizeHandle handle)
constexpr int GRID_SIZE
Definition grid.hpp:27
bool resizesLeft(ResizeHandle handle)