17#include <QAbstractTextDocumentLayout>
18#include <QFontMetricsF>
19#include <QGraphicsTextItem>
24#include <QTextCharFormat>
26#include <QTextDocument>
30#include <jkqtmathtext/jkqtmathtext.h>
41 class MathTextObjects :
public QObject,
public QTextObjectInterface {
43 Q_INTERFACES(QTextObjectInterface)
46 static constexpr int ObjectType = QTextFormat::UserObject;
47 static constexpr int FormulaIndex = QTextFormat::UserProperty;
49 void registerWith(QTextDocument* document)
51 document->documentLayout()->registerHandler(ObjectType,
this);
54 bool insert(QTextCursor& cursor, QStringView source,
const QTextCharFormat& format)
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()))
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())
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);
79 QSizeF intrinsicSize(QTextDocument*,
int,
const QTextFormat& format)
override
81 return formulas.at(format.intProperty(FormulaIndex)).size;
84 void drawObject(QPainter* painter,
const QRectF& rect, QTextDocument*,
int,
85 const QTextFormat& format)
override
87 auto& math = *formulas.at(format.intProperty(FormulaIndex)).math;
89 painter->setRenderHint(QPainter::Antialiasing);
90 painter->setRenderHint(QPainter::TextAntialiasing);
92 math.draw(*painter, Qt::AlignCenter, rect);
98 std::unique_ptr<JKQTMathText> math;
101 std::vector<Formula> formulas;
104 bool isFormattingCharacter(QChar character)
106 return std::ranges::contains(QStringView(u
"*_$\\"), character);
109 qsizetype findClosingDelimiter(QStringView text, QChar delimiter)
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'))
116 if (!escaped && character == delimiter)
119 if (!escaped && character ==
'$' && delimiter !=
'$') {
120 const auto length = findClosingDelimiter(text.mid(index + 1),
'$');
124 escaped = !escaped && character ==
'\\';
129 void insertFormattedText(QTextCursor& cursor, MathTextObjects& math, QStringView text,
130 const QTextCharFormat& format = {})
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++];
141 const auto length = character ==
'*' || character ==
'_' || character ==
'$'
142 ? findClosingDelimiter(text.mid(index), character)
150 cursor.insertText(plain, format);
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);
159 auto emphasis = format;
160 if (character ==
'*')
161 emphasis.setFontWeight(QFont::Bold);
163 emphasis.setFontItalic(
true);
164 insertFormattedText(cursor, math, text.mid(index, length), emphasis);
167 cursor.insertText(plain, format);
170 class TextShape :
public QGraphicsTextItem {
172 TextShape(
const QString& text,
const QFont& font,
int wrapWidth)
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);
182 math.registerWith(document());
183 QTextCursor cursor(document());
184 insertFormattedText(cursor, math, text);
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());
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());
200 setWrapWidth(wrapWidth);
203 int clampWidth(qreal width)
const
205 return static_cast<int>(std::clamp(std::ceil(std::max(width, minimumWidth)), 1.0,
206 double(std::numeric_limits<int>::max())));
209 void setWrapWidth(
int width) { setTextWidth(width > 0 ? clampWidth(width) : -1); }
211 int automaticWidth()
const {
return clampWidth(naturalWidth); }
213 int widthForHeight(qreal height,
int startingWidth)
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();
225 const int middle = low + (high - low) / 2;
226 if (heightAt(middle) > height)
234 auto nearestWidth = [&](
int width) {
235 const qreal lineHeight = heightAt(width);
238 while (first < last) {
239 const int middle = first + (last - first) / 2;
240 if (heightAt(middle) > lineHeight)
245 const int lower = first;
247 while (first < last) {
248 const int middle = first + (last - first) / 2 + 1;
249 if (heightAt(middle) >= lineHeight)
254 return std::clamp(start, lower, first);
256 auto score = [&](
int width) {
257 return std::tuple{std::abs(heightAt(width) - height), std::abs(width - start),
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) {
266 bestScore = candidate;
272 int legacyWrapWidth(
int length)
const
276 std::unique_ptr<QTextDocument> legacy(document()->clone());
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)
284 cursor.setPosition(block.position());
285 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, length);
286 if (cursor.block() == block && !cursor.atBlockEnd())
287 cursor.insertBlock();
289 return clampWidth(legacy->idealWidth());
292 QRectF boundingRect()
const override
295 return QGraphicsTextItem::boundingRect().united(
296 QRectF(0, 0,
GRID_SIZE, QFontMetricsF(font()).height()));
299 void paint(QPainter* painter,
const QStyleOptionGraphicsItem* option,
300 QWidget* widget)
override
303 if (defaultTextColor() != ink)
304 setDefaultTextColor(ink);
305 QGraphicsTextItem::paint(painter, option, widget);
309 mutable MathTextObjects math;
310 std::unique_ptr<QTextDocument> measurement;
325std::optional<std::reference_wrapper<const StringPropertyOptions>>
329 return std::cref(FontOptions);
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");
343 throw std::invalid_argument(
"Text size must be a positive number of points");
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");
349 if (
auto* existing =
dynamic_cast<TextShape*
>(
getItemShape());
350 existing && next.at(
"text") ==
properties.at(
"text")
352 && next.at(
"font") ==
properties.at(
"font")) {
354 existing->setWrapWidth(*wrapWidth);
357 auto shape = std::make_unique<TextShape>(QString::fromStdString(*text),
358 QFont(QString::fromStdString(*font), *size),
370 const int startingWidth = std::get<int>(initial.at(
"wrapWidth"));
372 ? shape->clampWidth(size.width())
373 : shape->widthForHeight(size.height(), startingWidth);
375 const int initialWidth =
376 startingWidth > 0 ? shape->clampWidth(startingWidth) : shape->automaticWidth();
377 if (width == initialWidth)
379 next.at(
"wrapWidth") = width;
387 throw std::invalid_argument(
"Unknown text property: " + std::string(key));
388 if (found->second == value)
391 next.at(std::string(key)) = value;
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"))}};
407 if (!json.contains(
"properties"))
409 const auto& values = json.at(
"properties");
410 if (!values.is_object())
411 throw std::invalid_argument(
"Text properties must be an object");
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))
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>();
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");
435 next.at(
"wrapWidth") =
static_cast<TextShape*
>(legacy.
getItemShape())
436 ->legacyWrapWidth(length.get<
int>());
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)
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)
bool resizesLeft(ResizeHandle handle)