18#include <QButtonGroup>
23#include <QGuiApplication>
26#include <QApplication>
33#include <QPlainTextEdit>
36#include <QRadioButton>
39#include <QSignalBlocker>
44#include <QStyleOptionSizeGrip>
45#include <QStylePainter>
64class FlowLayout :
public QLayout
67 FlowLayout(QWidget* parent,
int hSpacingFactor,
bool equalRowHeight) : QLayout(parent), mHSpacingFactor(hSpacingFactor), mEqualRowHeight(equalRowHeight) {}
68 ~FlowLayout()
override
70 while (QLayoutItem* item = takeAt(0)) {
74 void addItem(QLayoutItem* item)
override { mItems.append(item); }
75 int count()
const override {
return mItems.size(); }
76 QLayoutItem* itemAt(
int index)
const override {
return mItems.value(
index); }
77 QLayoutItem* takeAt(
int index)
override {
return index >= 0 &&
index < mItems.size() ? mItems.takeAt(
index) :
nullptr; }
78 Qt::Orientations expandingDirections()
const override {
return {}; }
79 bool hasHeightForWidth()
const override {
return true; }
80 int heightForWidth(
int width)
const override {
return doLayout(QRect(0, 0,
width, 0),
true); }
81 void setGeometry(
const QRect& rect)
override
83 QLayout::setGeometry(rect);
84 doLayout(rect,
false);
86 QSize sizeHint() const override
89 for (
const QLayoutItem* item : mItems) {
92 const QMargins
m = contentsMargins();
93 return size + QSize(
m.left() +
m.right(),
m.top() +
m.bottom());
95 QSize minimumSize() const override
98 for (
const QLayoutItem* item : mItems) {
99 size =
size.expandedTo(item->minimumSize());
101 const QMargins
m = contentsMargins();
102 return size + QSize(
m.left() +
m.right(),
m.top() +
m.bottom());
104 void setPreferredWidth(QWidget* widget,
int width) { mPreferredWidth[widget] =
width; }
107 int hSpacing()
const {
return mHSpacingFactor * spacing(); }
108 int itemWidth(
const QLayoutItem* item)
const {
return mPreferredWidth.value(item->widget(), item->sizeHint().width()); }
109 int doLayout(
const QRect& rect,
bool testOnly)
const
111 const QRect
r = rect.marginsRemoved(contentsMargins());
112 int x =
r.x(),
y =
r.y(), lineHeight = 0;
113 std::vector<std::pair<QLayoutItem*, QRect>>
line;
114 auto placeLine = [&]() {
116 for (
auto& [item, geometry] :
line) {
117 item->setGeometry(mEqualRowHeight ? QRect(geometry.x(), geometry.y(), geometry.width(), lineHeight) : geometry.translated(0, (lineHeight - geometry.
height()) / 2));
122 for (QLayoutItem* item : mItems) {
123 const int width = std::max(std::min(itemWidth(item),
r.width()), item->minimumSize().width());
124 const int height = item->hasHeightForWidth() ? item->heightForWidth(
width) : item->sizeHint().height();
125 if (
x >
r.x() &&
x +
width >
r.right() + 1) {
128 y += lineHeight + spacing();
133 lineHeight = std::max(lineHeight,
height);
136 return y + lineHeight - rect.y() + contentsMargins().bottom();
138 QList<QLayoutItem*> mItems;
139 QHash<const QWidget*, int> mPreferredWidth;
141 bool mEqualRowHeight;
143class GUIStyle :
public QProxyStyle
146 int styleHint(StyleHint hint,
const QStyleOption*
option,
const QWidget* widget, QStyleHintReturn* returnData)
const override
148 return hint == SH_ToolTip_WakeUpDelay ? 1500 : (hint == SH_ToolTip_FallAsleepDelay ? 0 : QProxyStyle::styleHint(hint,
option, widget, returnData));
152class ResizeGrip :
public QWidget
155 ResizeGrip(QWidget* parent, std::function<
void(QSize)>
resize) : QWidget(parent), mResize(
std::move(
resize))
157 setCursor(Qt::SizeFDiagCursor);
158 setFixedSize(16, 16);
162 void paintEvent(QPaintEvent*)
override
165 QStyleOptionSizeGrip opt;
167 opt.corner = Qt::BottomRightCorner;
168 painter.drawControl(QStyle::CE_SizeGrip, opt);
170 void mousePressEvent(QMouseEvent*
e)
override
172 mStartPos =
e->globalPosition().toPoint();
173 mStartSize = parentWidget()->size();
175 void mouseMoveEvent(QMouseEvent*
e)
override
177 if (
e->buttons() & Qt::LeftButton) {
178 const QPoint
d =
e->globalPosition().toPoint() - mStartPos;
179 mResize(mStartSize + QSize(
d.x(),
d.y()));
184 std::function<
void(QSize)> mResize;
189class TextEdit :
public QPlainTextEdit
192 TextEdit(
uint32_t lines, std::function<
void(
const QString&)> changed) : mChanged(
std::move(changed)), mGrip(new ResizeGrip(
this, [
this](QSize
size) {
193 mUnscaledSize =
size.expandedTo(QSize(60, 30) * mScale) / mScale;
197 const int margins = 2 * (frameWidth() + std::lround(document()->documentMargin())) + 6;
198 mUnscaledSize = QSize(400, std::max<uint32_t>(lines, 1) * fontMetrics().lineSpacing() + margins);
200 QSize sizeHint()
const override {
return mPreferredSize; }
201 void setScale(
float scale)
204 mPreferredSize = mUnscaledSize * scale;
205 setFixedHeight(mPreferredSize.height());
206 setMinimumWidth(std::min(mPreferredSize.width(), 100));
207 setMaximumWidth(mPreferredSize.width());
210 void showText(
const QString& text)
213 if (!hasFocus() && toPlainText() != text) {
215 document()->setModified(
false);
220 void focusOutEvent(QFocusEvent*
e)
override
222 QPlainTextEdit::focusOutEvent(
e);
223 if (document()->isModified()) {
224 document()->setModified(
false);
225 mCurrent = toPlainText();
231 void resizeEvent(QResizeEvent*
e)
override
233 QPlainTextEdit::resizeEvent(
e);
234 mGrip->move(
width() - mGrip->width(),
height() - mGrip->height());
239 std::function<
void(
const QString&)> mChanged;
242 QSize mPreferredSize;
248 QLineEdit* edit =
new QLineEdit;
249 std::shared_ptr<QString> current = std::make_shared<QString>();
251 void show(
const QString& text)
const
254 if (!edit->hasFocus()) {
258 void commit(
const QString& text)
const
263 std::optional<QString> entered() const
265 if (edit->isModified()) {
268 edit->setText(*current);
271 std::optional<double> number() const
274 const double v = edit->text().toDouble(&ok);
275 if (edit->isModified() && ok && std::isfinite(
v)) {
278 edit->setText(*current);
283class MultiSlider :
public QWidget
286 explicit MultiSlider(
double step) : mStep(
step)
288 setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
289 setFocusPolicy(Qt::ClickFocus);
291 std::function<
void()> changed;
292 std::function<
void()> focusChanged;
300 focused = focused < (
int32_t)
value.values.size() ? focused : -1;
304 void setPosition(int32_t
i,
double v)
312 QSize sizeHint()
const override {
return {300, handleHeight() + 6 + fontMetrics().height() + 8}; }
313 QSize minimumSizeHint()
const override {
return {100, sizeHint().height()}; }
316 void paintEvent(QPaintEvent*)
override
319 p.setRenderHint(QPainter::Antialiasing);
320 const QPalette& pal = palette();
321 const int32_t trackY = handleHeight() / 2 + 1, tickY = handleHeight() + 3;
322 p.setPen(QPen(pal.color(QPalette::Mid), 2));
323 p.drawLine(margin(), trackY,
width() - margin(), trackY);
325 p.setPen(QPen(pal.color(QPalette::Highlight), 4));
326 p.drawLine(margin(), trackY, toX(
value.progress / 65535. *
value.values.back()), trackY);
328 p.setPen(pal.color(QPalette::WindowText));
329 const double tick = tickStep();
330 for (int32_t k = 0; k * tick <= maxValue() * (1 + 1
e-9); k++) {
332 p.drawLine(
x, tickY,
x, tickY + 4);
333 p.drawText(QRect(
x - 50, tickY + 5, 100, fontMetrics().
height()), Qt::AlignHCenter | Qt::AlignTop, QString::number(k * tick));
336 const QRect
r(toX(
value.values[
i]) - handleWidth() / 2, 1, handleWidth(), handleHeight());
337 p.setBrush((int32_t)
i ==
value.selected ? pal.color(QPalette::Highlight) : pal.
color(QPalette::Button));
338 p.setPen(QPen((int32_t)
i == focused ? pal.color(QPalette::WindowText) : pal.
color(QPalette::Mid), (
int32_t)
i == focused ? 2 : 1));
339 p.drawRoundedRect(
r, 2, 2);
342 void mousePressEvent(QMouseEvent*
e)
override
344 if (
e->button() != Qt::LeftButton) {
349 if (
const int32_t
d = std::abs(toX(
value.values[
i]) - (int32_t)
e->position().x());
d <= bestDistance) {
355 mDragging = focused =
best;
361 void mouseMoveEvent(QMouseEvent*
e)
override
366 const float v = snap(toValue(
e->position().x()));
367 if (isFree(
v, mDragging) &&
v !=
value.values[mDragging]) {
368 value.values[mDragging] =
v;
374 void mouseReleaseEvent(QMouseEvent*
e)
override
376 if (
e->button() != Qt::LeftButton || mDragging < 0) {
380 value.selected =
value.selected == mDragging ? -1 : mDragging;
387 void sendAndNormalize()
390 std::vector<uint32_t> order(
value.values.size());
391 std::iota(order.begin(), order.end(), 0);
392 std::stable_sort(order.begin(), order.end(), [
this](
uint32_t a,
uint32_t b) { return value.values[a] < value.values[b]; });
398 newFocused = (
int32_t)order[
i] == focused ?
i : newFocused;
400 value = std::move(sorted);
401 focused = newFocused;
405 double maxValue()
const {
return std::max<double>(
value.max, mStep); }
406 double snap(
double v)
const {
return std::clamp(std::round(
v / mStep) * mStep, 0., maxValue()); }
407 bool isFree(
double v, int32_t except)
const
409 return std::none_of(
value.values.begin(),
value.values.end(), [&](
const float&
x) { return &x - value.values.data() != except && std::abs(x - v) < mStep / 2; });
411 int32_t handleHeight()
const {
return fontMetrics().height(); }
412 int32_t handleWidth()
const {
return std::max(6, fontMetrics().
height() / 2); }
413 int32_t margin()
const {
return std::max(handleWidth() / 2 + 1, fontMetrics().horizontalAdvance(
"00.00") / 2); }
414 int32_t toX(
double v)
const {
return margin() + std::lround(
v / maxValue() * (
width() - 2 * margin())); }
415 double toValue(
double x)
const {
return (
x - margin()) / std::max(1,
width() - 2 * margin()) * maxValue(); }
416 double tickStep() const
418 const double minStep = maxValue() * 2 * fontMetrics().horizontalAdvance(
"00.00") / std::max(1,
width() - 2 * margin());
419 const double base = std::pow(10., std::floor(std::log10(std::max(minStep, 1
e-9))));
420 for (
double m : {1., 2., 5.}) {
421 if (
m * base >= minStep) {
422 return std::max(
m * base, mStep);
425 return std::max(10 * base, mStep);
434 static constexpr int32_t FLOAT_STEPS = 1000;
437 SliderRange(
double minValue,
double maxValue,
bool isInteger,
double fixedStep = 0) :
min(minValue),
step(fixedStep > 0 ? fixedStep : (isInteger ? 1. : (maxValue - minValue) / FLOAT_STEPS)), steps(fixedStep > 0 || isInteger ?
std::
max<
int32_t>(
std::lround((maxValue - minValue) /
step), 0) : FLOAT_STEPS) {}
443static float clampScale(
float scale) {
return std::clamp(scale, 0.25f, 4.f); }
447 static constexpr double MAX_FIXED_LENGTH_STEPS = 16;
453 return std::visit([](
const auto&
x) ->
double {
454 if constexpr (std::is_same_v<std::remove_cvref_t<
decltype(
x)>, std::string>) {
455 return QString::fromStdString(
x).toDouble();
467 return std::visit([](
const auto&
x) {
468 if constexpr (std::is_same_v<std::remove_cvref_t<
decltype(
x)>, std::string>) {
469 return QString::fromStdString(
x);
473 return QString::number(
x);
481static uint32_t nearestChoice(
const std::vector<std::pair<std::string, GPUDisplayGUIValue>>& choices,
double value)
485 if (std::abs(toDouble(choices[
i].second) -
value) < std::abs(toDouble(choices[best].second) -
value)) {
494 const bool aNumber = std::holds_alternative<int64_t>(
a) || std::holds_alternative<double>(
a), bNumber = std::holds_alternative<int64_t>(
b) || std::holds_alternative<double>(
b);
495 return aNumber && bNumber ? toDouble(
a) == toDouble(
b) :
a ==
b;
500 qApp->setStyle(
new GUIStyle);
502 setMinimumSize(500, 500);
503 mStatusLabel =
new QLabel;
504 mStatusLabel->setWordWrap(
true);
505 mStatusLabel->hide();
506 statusBar()->addWidget(mStatusLabel, 1);
507 mDarkMode = darkPalette();
508 connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged,
this, &GPUDisplayGUI::colorSchemeChanged, Qt::QueuedConnection);
509 mInfoTextTimer.setSingleShot(
true);
510 connect(&mInfoTextTimer, &QTimer::timeout,
this, &GPUDisplayGUI::updateInfoLabels);
511 std::vector<GPUDisplayGUIChannel::Frame> layout;
513 std::lock_guard lock(mChannel.
mutex);
514 setWindowTitle(QString::fromStdString(mChannel.
windowName +
" GUI"));
517 mBaseFontSize = font().pointSizeF() > 0 ? font().pointSizeF() : 10.f;
518 auto* content =
new QWidget;
519 auto* contentLayout =
new QVBoxLayout(content);
520 contentLayout->addWidget(buildElements(layout));
521 contentLayout->addStretch();
522 auto* scroll =
new QScrollArea;
523 scroll->setWidgetResizable(
true);
524 scroll->setFrameShape(QFrame::NoFrame);
525 scroll->setWidget(content);
526 setCentralWidget(scroll);
527 colorSchemeChanged();
528 qApp->installEventFilter(
this);
529 connect(&mTimer, &QTimer::timeout,
this, &GPUDisplayGUI::timerTick);
530 mTimer.start(std::chrono::milliseconds(10));
533void GPUDisplayGUI::timerTick()
535 std::unique_lock lock(mChannel.
mutex);
537 if (mUpdate.
empty()) {
538 mChannel.
stateUpdated.wait_for(lock, mChannel.
replyTimeout, [
this] { return !mChannel.displayProcessingCurrentUpdate || mChannel.stop; });
541 mChannel.
stateUpdated.wait_for(lock, mChannel.
replyTimeout, [
this] { return mChannel.state.appliedUpdate == mLastSentId || mChannel.stop; });
551 mState = mChannel.
state;
553 mLastAppliedId = mLastSentId;
556 std::vector<std::pair<uint32_t, GPUDisplayGUIChannel::Options>> options;
558 for (
uint32_t id = 0;
id < mElements.size();
id++) {
559 if (mElements[
id].getOptions) {
560 options.emplace_back(
id, mElements[
id].getOptions());
566 const bool apply = newState && mUpdate.
empty() && mState.
appliedUpdate == mLastSentId;
570 mChannel.
update->merge(mUpdate);
572 mChannel.
update = std::move(mUpdate);
574 mChannel.
update->id = ++mLastSentId;
584 if (mState.
cfg.
mCfgO.guiDarkMode < 0) {
586 }
else if ((mState.
cfg.
mCfgO.guiDarkMode != 0) != mDarkMode) {
587 setDarkMode(mState.
cfg.
mCfgO.guiDarkMode != 0);
595 for (
const auto& [
id, o] : options) {
596 mElements[
id].setOptions(o);
597 mElements[
id].applied.reset();
598 applyElement(mElements[
id]);
605bool GPUDisplayGUI::darkPalette()
const {
return palette().window().color().lightness() < 128; }
607void GPUDisplayGUI::setDarkMode(
bool dark)
609#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
610 QGuiApplication::styleHints()->setColorScheme(dark ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
615void GPUDisplayGUI::colorSchemeChanged()
617 setStyleSheet(QString());
624 QMainWindow::resizeEvent(
event);
628void GPUDisplayGUI::fitStatusLabel()
630 mStatusLabel->setMinimumHeight(0);
631 mStatusLabel->setFixedHeight(mStatusLabel->heightForWidth(mStatusLabel->width()));
634void GPUDisplayGUI::updateInfoLabels()
636 const QString status = QString::fromStdString(mState.
infoStatus) + QString(
" GUI %1x%2").arg(
width()).arg(
height());
637 if (mInfoTextTimer.isActive() && !mState.
infoText.empty()) {
638 const char*
color = darkPalette() ?
"lightblue" :
"darkblue";
639 mStatusLabel->setTextFormat(Qt::RichText);
640 mStatusLabel->setText(
"<span style=\"white-space: pre-wrap;\">" + status.toHtmlEscaped() + QString(
"</span> - <span style=\"font-weight: bold; color: %1;\">%2</span>").arg(
color, QString::fromStdString(mState.
infoText).toHtmlEscaped()));
642 mStatusLabel->setTextFormat(Qt::PlainText);
643 mStatusLabel->setText(status);
645 mStatusLabel->setVisible(!mState.
infoStatus.empty());
649void GPUDisplayGUI::applySettings()
651 if (clampScale(mState.
cfg.
mCfgO.guiScale) != mScale) {
652 setScale(mState.
cfg.
mCfgO.guiScale);
654 for (
auto&
element : mElements) {
659void GPUDisplayGUI::applyElement(GUIElement&
element)
674 mElements[
id].applied.reset();
679 auto*
w =
new QCheckBox(QString::fromStdString(el.
name));
680 connect(
w, &QCheckBox::toggled,
this, [
this,
id = el.
id](
bool v) { setValue(id, (int64_t)v); });
681 return {
w, [
w](
const GPUDisplayGUIValue&
v) {
const QSignalBlocker blocker(
w);
w->setChecked(toDouble(
v) != 0.); }, {}};
687 connect(text.edit, &QLineEdit::editingFinished,
this, [
this, text,
id = el.
id, isInteger = el.
isInteger,
isString = el.
isString, hasRange = el.
hasRange,
min = el.
min,
max = el.
max]() {
689 if (const auto str = text.entered()) {
691 setValue(id, str->toStdString());
693 }
else if (
const auto entered = text.number()) {
694 const GPUDisplayGUIValue v = toValue(hasRange ? std::clamp(*entered, min, max) : *entered, isInteger);
695 text.commit(toQString(v));
702QHBoxLayout* GPUDisplayGUI::createSliderRow(ElementWidget&
retVal, QWidget* slider, QLineEdit* edit, Qt::Alignment editAlignment)
704 retVal.widget =
new QWidget;
705 auto*
row =
new QHBoxLayout(
retVal.widget);
706 row->setContentsMargins(0, 0, 0, 0);
707 mScaleSetters.emplace_back([edit](
float scale) { edit->setFixedWidth(std::lround(60 * scale)); });
708 row->addWidget(slider);
709 row->addWidget(edit, 0, editAlignment);
716 auto* slider =
new QSlider(Qt::Horizontal);
718 auto*
row = createSliderRow(
retVal, slider, text.edit);
719 const bool fixedLength = fixedLengthSlider(el);
720 const int32_t length = fixedLength ? (el.
choices.size() ? el.
choices.size() - 1 : std::lround(el.
max - el.
min)) * 2 * style()->pixelMetric(QStyle::PM_IndicatorWidth) : 150;
721 mScaleSetters.emplace_back([slider,
length, fixedLength](
float scale) {
723 slider->setFixedWidth(std::lround(
length * scale));
725 slider->setMinimumWidth(std::lround(
length * scale));
732 auto choices = std::make_shared<const std::vector<std::pair<std::string, GPUDisplayGUIValue>>>(el.
choices);
733 slider->setRange(0, choices->size() - 1);
734 connect(slider, &QSlider::valueChanged,
this, [
this, text,
id = el.
id, choices](int32_t
pos) {
735 text.show(QString::fromStdString((*choices)[pos].first));
736 setValue(id, (*choices)[pos].second);
738 connect(text.edit, &QLineEdit::editingFinished,
this, [
this, text, slider,
id = el.
id, choices]() {
739 if (const auto entered = text.number()) {
740 const uint32_t pos = nearestChoice(*choices, *entered);
741 text.commit(QString::fromStdString((*choices)[pos].first));
742 const QSignalBlocker blocker(slider);
743 slider->setValue(pos);
744 setValue(id, (*choices)[pos].second);
749 const QSignalBlocker blocker(slider);
750 slider->setValue(best);
751 text.show(sameValue((*choices)[best].second,
value) ? QString::fromStdString((*choices)[best].
first) : toQString(
value));
755 slider->setRange(0,
range->steps);
756 connect(slider, &QSlider::valueChanged,
this, [
this, text,
id = el.
id,
range, isInteger = el.
isInteger](int32_t
pos) {
757 const GPUDisplayGUIValue v = toValue(range->value(pos), isInteger);
758 text.show(toQString(v));
761 connect(text.edit, &QLineEdit::editingFinished,
this, [
this, text, slider,
id = el.
id,
range, isInteger = el.
isInteger, step = el.
step]() {
762 if (const auto entered = text.number()) {
763 const double clamped = std::clamp(*entered, range->min, range->value(range->steps));
764 const GPUDisplayGUIValue v = toValue(step > 0 ? range->value(range->position(clamped)) : clamped, isInteger);
765 text.commit(toQString(v));
766 const QSignalBlocker blocker(slider);
767 slider->setValue(range->position(toDouble(v)));
772 const QSignalBlocker blocker(slider);
773 slider->setValue(
range->position(toDouble(
value)));
774 text.show(toQString(
value));
777 *
range = SliderRange(o.min, o.max, isInteger, step);
778 const QSignalBlocker blocker(slider);
779 slider->setRange(0,
range->steps);
788 auto* slider =
new MultiSlider(el.
step);
790 createSliderRow(
retVal, slider, text.edit, Qt::AlignTop);
791 mScaleSetters.emplace_back([slider](
float scale) { slider->setMinimumWidth(std::lround(300 * scale)); });
792 slider->changed = [
this, slider,
id = el.
id]() { setValue(
id, slider->value); };
793 auto focusedText = [slider]() {
return slider->focused >= 0 ? QString::number(slider->value.values[slider->focused]) : QString(); };
794 slider->focusChanged = [text, focusedText]() { text.show(focusedText()); };
795 connect(text.edit, &QLineEdit::editingFinished,
this, [slider, text, focusedText]() {
796 if (const auto entered = text.number(); entered && slider->focused >= 0) {
797 slider->setPosition(slider->focused, *entered);
799 text.commit(focusedText());
807 auto* widget =
new QWidget;
808 auto*
row =
new QHBoxLayout(widget);
809 row->setContentsMargins(0, 0, 0, 0);
810 auto*
group =
new QButtonGroup(widget);
812 auto* button =
new QRadioButton(QString::fromStdString(el.
choices[
i].first));
813 group->addButton(button,
i);
814 row->addWidget(button);
816 connect(
group, &QButtonGroup::idClicked,
this, [
this,
id = el.
id, choices = el.
choices](int32_t
i) { setValue(id, choices[i].second); });
819 if (sameValue(choices[
i].second,
v)) {
820 group->button(
i)->setChecked(
true);
829 auto*
w =
new TextEdit(el.
lines, [
this,
id = el.
id](
const QString& text) { setValue(id, text.toStdString()); });
830 mScaleSetters.emplace_back([
w](
float scale) {
w->setScale(scale); });
836 auto*
w =
new QPushButton(QString::fromStdString(el.
name));
837 connect(
w, &QPushButton::clicked,
this, [
this,
id = el.
id]() { setValue(id, (int64_t)1); });
843 auto*
w =
new QComboBox;
844 auto choices = std::make_shared<std::vector<std::pair<std::string, GPUDisplayGUIValue>>>(el.
choices);
845 for (
const auto& choice : *choices) {
846 w->addItem(QString::fromStdString(choice.first));
848 connect(
w, &QComboBox::currentIndexChanged,
this, [
this,
id = el.
id, choices](int32_t
i) {
849 if (i >= 0 && i < (int32_t)choices->size()) {
850 setValue(id, (*choices)[i].second);
854 const QSignalBlocker blocker(
w);
856 if (sameValue((*choices)[
i].second,
v)) {
857 w->setCurrentIndex(
i);
861 *choices = o.choices;
862 const QSignalBlocker blocker(
w);
864 for (
const auto& choice : *choices) {
865 w->addItem(QString::fromStdString(choice.first));
870QWidget* GPUDisplayGUI::buildElements(
const std::vector<GPUDisplayGUIChannel::Frame>& layout)
873 auto*
frames =
new QWidget;
874 auto* framesLayout =
new FlowLayout(
frames, 1,
true);
875 framesLayout->setContentsMargins(0, 0, 0, 0);
876 for (
const auto& frame : layout) {
877 auto*
box =
new QGroupBox(QString::fromStdString(frame.description));
878 if (frame.description.empty()) {
879 box->setStyleSheet(
"QGroupBox { margin-top: 0; }");
881 auto* boxLayout =
new QVBoxLayout(
box);
882 QLayout* section =
nullptr;
883 bool sectionHorizontal =
false;
884 for (
const auto& el : frame.elements) {
885 ElementWidget created;
888 created = createCheckbox(el);
891 created = createTextbox(el);
894 created = createSlider(el);
896 case Type::RADIO_BUTTONS:
897 created = createRadioButtons(el);
900 created = createTextEdit(el);
903 created = createButton(el);
906 created = createDropdown(el);
908 case Type::MULTI_SLIDER:
909 created = createMultiSlider(el);
912 QWidget* widget = created.widget;
913 QLabel*
name = el.
type == Type::CHECKBOX || el.
type == Type::BUTTON || el.
name.empty() ? nullptr :
new QLabel(QString::fromStdString(el.
name));
914 widget->setToolTip(QString::fromStdString(el.
description));
916 name->setToolTip(widget->toolTip());
918 if (!section || el.
horizontal != sectionHorizontal) {
920 if (sectionHorizontal) {
921 section =
new FlowLayout(
nullptr, 3,
false);
923 auto* form =
new QFormLayout;
924 form->setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);
925 form->setFormAlignment(Qt::AlignLeft | Qt::AlignTop);
926 form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
927 form->setRowWrapPolicy(QFormLayout::DontWrapRows);
930 section->setContentsMargins(0, 0, 0, 0);
931 boxLayout->addLayout(section);
933 if (!sectionHorizontal) {
934 name ? ((QFormLayout*)section)->addRow(
name, widget) : ((QFormLayout*)section)->addRow(widget);
936 auto* item =
new QWidget;
937 auto*
row =
new QHBoxLayout(item);
938 row->setContentsMargins(0, 0, 0, 0);
940 row->addWidget(widget);
941 section->addWidget(item);
943 section->addWidget(widget);
945 mElements.push_back({std::move(created.set), std::move(created.setOptions), el.
get, el.
dynamicOptions, std::nullopt});
947 framesLayout->addWidget(
box);
948 if (std::any_of(frame.elements.begin(), frame.elements.end(), [](
const auto& el) { return (el.type == Type::SLIDER && !fixedLengthSlider(el)) || el.type == Type::MULTI_SLIDER; })) {
949 mScaleSetters.emplace_back([
this, framesLayout,
box](
float scale) { framesLayout->setPreferredWidth(
box, std::lround(screen()->availableGeometry().
width() / 3 * scale)); });
952 mScaleSetters.emplace_back([framesLayout](
float) { framesLayout->invalidate(); });
956void GPUDisplayGUI::setScale(
float scale)
958 mScale = clampScale(scale);
959 for (
const auto& setter : mScaleSetters) {
962 const int indicator = std::lround(style()->pixelMetric(QStyle::PM_IndicatorWidth) * mScale);
963 setStyleSheet(QString(
"QGroupBox { border: 1px solid palette(mid); border-radius: 3px; margin-top: 0.6em; padding-top: 0.3em; }"
964 "QGroupBox::title { subcontrol-origin: margin; left: 8px; padding: 0 3px; }"
965 "QCheckBox::indicator, QRadioButton::indicator { width: %1px; height: %1px; }"
966 "QWidget { font-size: %2pt; }")
968 .arg(mBaseFontSize * mScale, 0,
'f', 1));
973 const auto*
w = qobject_cast<QWidget*>(watched);
974 if (!
w ||
w->window() !=
this) {
977 if (watched == mStatusLabel &&
event->type() == QEvent::Resize) {
981 if (
event->type() == QEvent::Wheel && (
static_cast<QWheelEvent*
>(
event)->modifiers() & Qt::ControlModifier)) {
982 const int delta =
static_cast<QWheelEvent*
>(
event)->angleDelta().y();
984 setScale(mScale * std::pow(1.1f, delta / 120.f));
989 if (
event->type() == QEvent::KeyPress &&
static_cast<QKeyEvent*
>(
event)->key() == Qt::Key_0 && (
static_cast<QKeyEvent*
>(
event)->modifiers() & Qt::ControlModifier)) {
999 setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
1009 QMainWindow::keyPressEvent(
event);
1012 mUpdate.
keys.emplace_back(
key);
1015int32_t GPUDisplayGUI::translateKey(
const QKeyEvent*
event)
1018 if (
event->nativeScanCode() == 0x29) {
1020 if (
event->nativeScanCode() == 49) {
1024 switch (
event->key()) {
1026 return GPUDisplayFrontendKeyVars::KEY_UP;
1028 return GPUDisplayFrontendKeyVars::KEY_DOWN;
1030 return GPUDisplayFrontendKeyVars::KEY_LEFT;
1032 return GPUDisplayFrontendKeyVars::KEY_RIGHT;
1033 case Qt::Key_PageUp:
1034 return GPUDisplayFrontendKeyVars::KEY_PAGEUP;
1035 case Qt::Key_PageDown:
1036 return GPUDisplayFrontendKeyVars::KEY_PAGEDOWN;
1038 return GPUDisplayFrontendKeyVars::KEY_HOME;
1040 return GPUDisplayFrontendKeyVars::KEY_END;
1041 case Qt::Key_Insert:
1042 return GPUDisplayFrontendKeyVars::KEY_INSERT;
1043 case Qt::Key_Escape:
1044 return GPUDisplayFrontendKeyVars::KEY_ESCAPE;
1045 case Qt::Key_Backspace:
1046 return GPUDisplayFrontendKeyVars::KEY_BACKSPACE;
1047 case Qt::Key_Delete:
1048 return GPUDisplayFrontendKeyVars::KEY_DELETE;
1049 case Qt::Key_Return:
1051 return GPUDisplayFrontendKeyVars::KEY_ENTER;
1055 if (
event->key() >= Qt::Key_F1 &&
event->key() <= Qt::Key_F12) {
1056 static_assert(GPUDisplayFrontendKeyVars::KEY_F12 - GPUDisplayFrontendKeyVars::KEY_F1 == Qt::Key_F12 - Qt::Key_F1);
1057 return GPUDisplayFrontendKeyVars::KEY_F1 + (
event->key() - Qt::Key_F1);
1059 const QString text =
event->text();
1060 if (text.size() == 1 && text[0].unicode() >= 32 && text[0].unicode() < 127) {
1061 return text[0].unicode();
bool isString(TDataMember const &dm)
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time frames(excluding borders)") AddOption(eventStride
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events d
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder int32_t
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging option
void keyPressEvent(QKeyEvent *event) override
void resizeEvent(QResizeEvent *event) override
bool eventFilter(QObject *watched, QEvent *event) override
GPUDisplayGUI(GPUDisplayGUIChannel &channel, QWidget *parent=nullptr)
GLuint const GLchar * name
GLintptr GLsizeiptr GLboolean commit
GLint GLsizei GLsizei height
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLuint GLsizei GLsizei * length
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLboolean GLboolean GLboolean GLboolean a
GLubyte GLubyte GLubyte GLubyte w
GLsizei const GLint * box
std::string show(const DeliveryType type)
int32_t const char int32_t line
std::variant< int64_t, double, std::string, GPUDisplayMultiSliderValue > GPUDisplayGUIValue
const bool const bool const int FollowDirection BestTrial TrackITSInternal< NLayers > & best
if(!okForPhiMin(phi0, phi1))
Drawing helper functions.
std::function< Options()> dynamicOptions
std::function< GPUDisplayGUIValue(const Settings &)> get
std::vector< std::pair< std::string, GPUDisplayGUIValue > > choices
std::function< void()> updatePosted
std::chrono::milliseconds replyTimeout
std::chrono::milliseconds infoTextTime
bool displayWaitingForOptions
std::condition_variable stateUpdated
uint64_t optionsReadRevision
std::optional< Update > update
std::vector< Frame > layout
std::condition_variable optionsRead
std::optional< float > guiScale
void setValue(uint32_t element, GPUDisplayGUIValue value)
std::vector< int32_t > keys
std::optional< int8_t > guiDarkMode