33#include <QAbstractItemView>
40#include <QIntValidator>
50#include <QSignalBlocker>
51#include <QTemporaryFile>
65using namespace SILICON::core;
66using namespace SILICON::waveform;
70 constexpr int RULER_HEIGHT_PX = 24;
71 constexpr int TRACE_ROW_HEIGHT_PX = 28;
72 constexpr int GROUP_HEADER_HEIGHT_PX = 22;
73 constexpr int SIGNAL_LIST_WIDTH_PX = 220;
74 constexpr int WAVEFORM_LEFT_INSET = 16;
76 int normalizedIndex(
const int index,
const int count)
78 return index >= 0 && index < count ? index : -1;
81 std::pair<quint64, quint64> normalizedInterval(quint64 startTime, quint64 endTime,
82 const quint64 duration)
84 startTime = std::min(startTime, duration);
85 endTime = std::min(endTime, duration);
86 if (endTime < startTime)
87 std::swap(startTime, endTime);
88 return {startTime, endTime};
91 BusValueFormat formatForSignal(
const std::vector<BusValueFormat>& formats,
94 return row >= 0 && row < static_cast<int>(formats.size())
95 ? formats[
static_cast<std::size_t
>(row)]
99 std::pair<int, int> traceBounds(
const int rowY)
101 return {rowY + 5, rowY + TRACE_ROW_HEIGHT_PX - 6};
104 QColor colorForTraceValue(
const BusValue& value)
106 if (std::ranges::any_of(value, [](
const auto s) {
return s == State::ERROR; }))
108 if (std::ranges::any_of(value, [](
const auto s) {
return s == State::UNKNOWN; }))
110 if (std::ranges::all_of(value, [](
const auto s) {
return s == State::LOW; }))
118 QColor groupBackground;
124 TraceTheme traceTheme()
134 void paintGroupBand(QPainter& painter,
int y,
int width,
const TraceTheme& theme,
135 const QString& label = {})
137 painter.fillRect(QRect(0, y, width, GROUP_HEADER_HEIGHT_PX),
138 label.isEmpty() ? theme.background : theme.groupBackground);
139 if (!label.isEmpty()) {
140 painter.setPen(theme.text);
141 painter.drawText(QRect(6, y, width - 12, GROUP_HEADER_HEIGHT_PX),
142 Qt::AlignVCenter | Qt::AlignLeft, label);
144 painter.setPen(theme.grid);
145 painter.drawLine(0, y + GROUP_HEADER_HEIGHT_PX - 1, width,
146 y + GROUP_HEADER_HEIGHT_PX - 1);
150 void paintSignalRow(QPainter& painter,
int y,
int width,
int row,
int selectedRow,
151 const TraceTheme& theme)
153 if (row == selectedRow)
154 painter.fillRect(QRect(0, y, width, TRACE_ROW_HEIGHT_PX), theme.selectedRow);
155 painter.setPen(theme.grid);
156 painter.drawLine(0, y + TRACE_ROW_HEIGHT_PX - 1, width, y + TRACE_ROW_HEIGHT_PX - 1);
159 bool hasInputGroup(
int inputCount)
161 return inputCount > 0;
164 bool hasOutputGroup(
int signalCount,
int inputCount)
166 return inputCount < signalCount;
169 int totalGroupHeaderCount(
int signalCount,
int inputCount)
171 return (hasInputGroup(inputCount) ? 1 : 0)
172 + (hasOutputGroup(signalCount, inputCount) ? 1 : 0);
175 int totalGroupHeaderCountBeforeSignal(
int row,
int signalCount,
int inputCount)
177 int count = hasInputGroup(inputCount) ? 1 : 0;
178 if (row >= inputCount && hasOutputGroup(signalCount, inputCount))
187 setFixedWidth(SIGNAL_LIST_WIDTH_PX);
207 const int nextIndex = normalizedIndex(signalIndex,
names.size());
218 +
names.size() * TRACE_ROW_HEIGHT_PX;
223 return std::max(96, SIGNAL_LIST_WIDTH_PX * 33 / 50);
229 * GROUP_HEADER_HEIGHT_PX
230 + row * TRACE_ROW_HEIGHT_PX;
235 if (position.x() < 0 || position.x() >= width())
238 for (
int row = 0; row <
names.size(); ++row) {
240 if (position.y() >= y && position.y() < y + TRACE_ROW_HEIGHT_PX)
248 QWidget::paintEvent(event);
250 QPainter painter(
this);
251 const auto theme = traceTheme();
253 const QColor gridColor =
theme.grid;
255 painter.fillRect(rect(),
theme.background);
257 painter.setPen(gridColor);
258 painter.drawLine(valueX - 8, 0, valueX - 8, height());
261 paintGroupBand(painter, 0, width(),
theme, tr(
"Inputs"));
264 width(),
theme, tr(
"Outputs"));
266 for (
const auto& [row, name] :
names | SILICON::views::enumerate) {
268 const QString value = row <
values.size() ?
values[row] : QString(
"x");
273 painter.setPen(
theme.text);
274 painter.drawText(QRect(6, y, valueX - 18, TRACE_ROW_HEIGHT_PX),
275 Qt::AlignVCenter | Qt::AlignLeft, name);
276 painter.drawText(QRect(valueX, y, width() - valueX - 6, TRACE_ROW_HEIGHT_PX),
277 Qt::AlignVCenter | Qt::AlignLeft, value);
283 QWidget::mousePressEvent(event);
285 const int row =
signalRowAt(event->position().toPoint());
289 if (event->button() == Qt::LeftButton) {
291 }
else if (event->button() == Qt::RightButton) {
298 setAutoFillBackground(
true);
299 setMouseTracking(
true);
300 setMinimumSize(480, RULER_HEIGHT_PX);
309 const int inputCount)
334 const qsizetype minimumHeight = RULER_HEIGHT_PX + TRACE_ROW_HEIGHT_PX;
335 const qsizetype contentHeight =
338 * GROUP_HEADER_HEIGHT_PX
340 const qsizetype height = std::max(minimumHeight, contentHeight);
341 setMinimumSize(width, height);
342 resize(width, height);
347 const double nextPixelsPerTick = std::clamp(value, 2.0, 80.0);
371 const int nextIndex = normalizedIndex(signalIndex,
signalNames.size());
401 const int nextSignalIndex = normalizedIndex(signalIndex,
signalNames.size());
403 startTime = interval.first;
437 return WAVEFORM_LEFT_INSET + std::lround(time *
pixelsPerTick);
442 const double rawTime = std::max(0.0, (x - WAVEFORM_LEFT_INSET) /
pixelsPerTick);
443 const auto rounded =
static_cast<quint64
>(std::llround(rawTime));
444 return std::min(rounded,
endTime());
449 return RULER_HEIGHT_PX
451 * GROUP_HEADER_HEIGHT_PX
452 + row * TRACE_ROW_HEIGHT_PX;
457 if (position.y() < RULER_HEIGHT_PX)
460 for (
int row = 0; row <
signalNames.size(); ++row) {
462 if (position.y() >= y && position.y() < y + TRACE_ROW_HEIGHT_PX)
471 || sampleIndex >=
static_cast<int>(
traceSamples->size()))
474 const auto& values = (*traceSamples)[
static_cast<std::size_t
>(sampleIndex)].values;
475 return row >= 0 && row < static_cast<int>(values.size())
476 ? values[
static_cast<std::size_t
>(row)]
482 QWidget::paintEvent(event);
484 QPainter painter(
this);
485 painter.setRenderHint(QPainter::Antialiasing,
false);
487 const auto theme = traceTheme();
488 painter.fillRect(rect(),
theme.background);
490 const QPen gridPen(
theme.grid);
491 const QPen textPen(
theme.text);
492 const QRect visibleRect =
event ?
event->rect() : rect();
494 painter.setPen(gridPen);
495 painter.drawLine(0, RULER_HEIGHT_PX - 1, width(), RULER_HEIGHT_PX - 1);
497 const auto visibleTimeForX = [
this](
int x) -> quint64 {
498 return std::max(0.0, (x - WAVEFORM_LEFT_INSET) /
pixelsPerTick);
504 const auto visibleSamples = [&, traceEnd = samples.cend()] {
505 using VisibleSampleRange = std::ranges::subrange<std::vector<Sample>::const_iterator>;
508 return VisibleSampleRange{traceEnd, traceEnd};
511 auto firstVisible = std::ranges::lower_bound(
512 samples, visibleTimeForX(visibleRect.left()), {}, &
Sample::time);
513 if (firstVisible != samples.cbegin())
514 firstVisible = std::prev(firstVisible);
518 std::ranges::upper_bound(std::ranges::subrange(firstVisible, traceEnd),
519 visibleTimeForX(visibleRect.right()), {}, &
Sample::time);
520 if (lastVisible != traceEnd)
521 lastVisible = std::next(lastVisible);
523 return VisibleSampleRange{firstVisible, lastVisible};
525 const auto firstVisibleIndex = visibleSamples.begin() - samples.cbegin();
526 const auto lastVisibleIndex = visibleSamples.end() - samples.cbegin();
528 const bool hasSelectedSignal =
530 auto drawTimeMarker = [&](
const quint64 time,
const QPen& linePen,
const QPen& labelPen,
531 const bool clampRight) {
533 const QString label = QString::number(time);
534 const int labelWidth =
535 std::max(40, painter.fontMetrics().horizontalAdvance(label) + 8);
537 clampRight ? std::clamp(x - labelWidth / 2, 0, std::max(0, width() - labelWidth))
538 : std::max(0, x - labelWidth / 2);
540 painter.setPen(linePen);
541 painter.drawLine(x, painter.fontMetrics().height() + 2, x, height());
542 painter.setPen(labelPen);
543 painter.drawText(QRect(labelX, 1, labelWidth, RULER_HEIGHT_PX - 4),
544 Qt::AlignHCenter | Qt::AlignTop, label);
547 const auto isSelectedSignalTick = [&](
const int sampleIndex) {
548 if (!hasSelectedSignal)
550 if (sampleIndex < 0 || sampleIndex >=
static_cast<int>(samples.size()))
552 if (sampleIndex == firstVisibleIndex || sampleIndex == 0)
558 if (hasSelectedSignal && !samples.empty()) {
559 for (
auto sampleIt = visibleSamples.begin(); sampleIt != visibleSamples.end();
561 const int sampleIndex =
static_cast<int>(sampleIt - samples.cbegin());
562 if (isSelectedSignalTick(sampleIndex))
563 drawTimeMarker(sampleIt->time, gridPen, textPen,
false);
566 for (
const Sample& sample : visibleSamples)
567 drawTimeMarker(sample.time, gridPen, textPen,
false);
571 paintGroupBand(painter, RULER_HEIGHT_PX, width(),
theme);
579 const int editSignalIndex =
582 if (
editMode && drawEditSelection && editSignalIndex >= 0
595 QRect(std::min(x0, x1), y, std::max(2, std::abs(x1 - x0)), TRACE_ROW_HEIGHT_PX),
596 selectionColor.lighter(170));
598 const QPen selectionPen(selectionColor, 2);
599 drawTimeMarker(startTime, selectionPen, selectionPen,
true);
601 drawTimeMarker(
endTime, selectionPen, selectionPen,
true);
608 for (
int row = 0; row <
signalNames.size(); ++row) {
609 for (
int i = firstVisibleIndex; i + 1 < lastVisibleIndex;) {
612 while (end < lastVisibleIndex - 1 &&
sampleValueAt(end, row) == value)
615 const int x0 =
xForTime(samples[i].time);
616 const int x1 =
xForTime(samples[end].time);
617 if (value.size() == 1) {
619 if (end < lastVisibleIndex - 1) {
621 if (nextValue.size() == 1)
625 drawBus(painter, row, x0, x1, value);
636 selectionPen, selectionPen,
false);
642 QWidget::mouseMoveEvent(event);
659 const int mouseX =
event->position().toPoint().x();
661 const bool hasSelectedSignal =
666 int closestIndex = -1;
667 int closestDistance = std::numeric_limits<int>::max();
668 for (
int i = 0; i < static_cast<int>(samples.size()); ++i) {
669 if (hasSelectedSignal && i > 0
673 const int distance = std::abs(mouseX -
xForTime(samples[i].time));
674 if (distance < closestDistance) {
675 closestDistance = distance;
680 if (closestIndex >= 0)
686 QWidget::mousePressEvent(event);
688 const int row =
signalRowAt(event->position().toPoint());
692 if (event->button() == Qt::LeftButton) {
701 }
else if (event->button() == Qt::RightButton) {
708 QWidget::mouseReleaseEvent(event);
731 const int mid = std::midpoint(top, bottom);
743 painter.setPen(QPen(colorForTraceValue(value), 2));
751 if (previousValue == nextValue)
754 painter.setPen(QPen(colorForTraceValue(previousValue), 2));
763 const int mid = std::midpoint(top, bottom);
764 const int offset = std::min(5, (x1 - x0) / 2);
766 painter.setPen(QPen(colorForTraceValue(value), 2));
767 painter.drawLine(x0, mid, x0 + offset, top);
768 painter.drawLine(x0, mid, x0 + offset, bottom);
769 painter.drawLine(x0 + offset, top, x1 - offset, top);
770 painter.drawLine(x0 + offset, bottom, x1 - offset, bottom);
771 painter.drawLine(x1 - offset, top, x1, mid);
772 painter.drawLine(x1 - offset, bottom, x1, mid);
776 const QString displayValue =
778 painter.drawText(QRect(x0 + 7, top, x1 - x0 - 14, bottom - top), Qt::AlignCenter,
785 const auto root =
new QVBoxLayout(
this);
786 root->setContentsMargins(4, 4, 4, 4);
788 const auto makeToolBar = [
this] {
789 const auto toolBar =
new QToolBar(
this);
790 toolBar->setFloatable(
false);
791 toolBar->setMovable(
false);
792 toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
795 const auto makeNumberEdit = [
this](
const int minimum) {
796 const auto edit =
new QLineEdit(
this);
797 edit->setValidator(
new QIntValidator(minimum, std::numeric_limits<int>::max(), edit));
798 edit->setMaximumWidth(96);
799 edit->setAlignment(Qt::AlignRight);
803 const auto fileToolBar = makeToolBar();
805 const auto newAct =
new QAction(
Icon(
"file"), tr(
"&New"),
this);
806 const auto openAct =
new QAction(
Icon(
"open"), tr(
"&Open..."),
this);
807 const auto saveAct =
new QAction(
Icon(
"save"), tr(
"&Save"),
this);
808 editAct =
new QAction(
Icon(
"pencil"), tr(
"Edit Inputs"),
this);
811 fileToolBar->addAction(newAct);
812 fileToolBar->addAction(openAct);
813 fileToolBar->addAction(saveAct);
814 fileToolBar->addSeparator();
815 fileToolBar->addAction(
editAct);
816 root->addWidget(fileToolBar);
818 const auto splitter =
new QSplitter(
this);
819 splitter->setHandleWidth(0);
820 const auto labelPane =
new QWidget();
821 const auto labelLayout =
new QVBoxLayout(labelPane);
822 labelLayout->setContentsMargins(0, 0, 0, 0);
823 labelLayout->setSpacing(0);
825 const auto labelRulerSpacer =
new QWidget(labelPane);
826 labelRulerSpacer->setFixedHeight(RULER_HEIGHT_PX);
827 labelLayout->addWidget(labelRulerSpacer);
844 splitter->addWidget(labelPane);
846 splitter->setCollapsible(0,
false);
847 splitter->setCollapsible(1,
false);
848 splitter->setStretchFactor(0, 0);
849 splitter->setStretchFactor(1, 1);
850 labelPane->setFixedWidth(SIGNAL_LIST_WIDTH_PX);
851 root->addWidget(splitter);
853 const auto zoomToolBar = makeToolBar();
855 const auto zoomOutAct =
new QAction(
Icon(
"minus"), tr(
"Zoom Out"),
this);
856 const auto zoomInAct =
new QAction(
Icon(
"plus"), tr(
"Zoom In"),
this);
858 zoomToolBar->addAction(zoomOutAct);
859 zoomToolBar->addAction(zoomInAct);
867 const auto bottomBar =
new QWidget(
this);
868 const auto bottomLayout =
new QHBoxLayout(bottomBar);
869 bottomLayout->setContentsMargins(0, 0, 0, 0);
870 bottomLayout->addWidget(zoomToolBar);
871 bottomLayout->addStretch();
872 bottomLayout->addWidget(
new QLabel(tr(
"Duration"), bottomBar));
874 bottomLayout->addWidget(
new QLabel(tr(
"Start"), bottomBar));
876 bottomLayout->addWidget(
new QLabel(tr(
"End"), bottomBar));
877 bottomLayout->addWidget(
endEdit);
878 root->addWidget(bottomBar);
888 scrollArea->horizontalScrollBar()->maximum());
895 callbacks.connect(zoomInAct, &QAction::triggered, [
this]() {
899 callbacks.connect(zoomOutAct, &QAction::triggered, [
this]() {
903 connect(
scrollArea->verticalScrollBar(), &QScrollBar::valueChanged,
905 connect(
labelScrollArea->verticalScrollBar(), &QScrollBar::valueChanged,
906 scrollArea->verticalScrollBar(), &QScrollBar::setValue);
920 [
this](
const int signalIndex,
const quint64 startTime,
const quint64 endTime) {
925 [
this](
int index, quint64 start, quint64 end) {
935 const auto duration =
durationEdit->text().toULongLong(&ok);
936 const auto next = ok ? std::max<quint64>(1, duration) :
editDuration;
951 const QList<int>& widths)
953 std::vector<Signal> signalDefinitions;
954 signalDefinitions.reserve(
static_cast<std::size_t
>(signalNames.size()));
955 for (
int i = 0; i < signalNames.size(); ++i) {
956 const int width = i < widths.size() ? widths[i] : 1;
957 signalDefinitions.push_back(
958 {signalNames[i].toStdString(),
static_cast<std::size_t
>(std::max(1, width))});
964 : (
trace.signalDefinitions.empty() ? -1 : 0);
979 if (event->type() == QEvent::FocusIn) {
982 }
else if (event->type() == QEvent::FocusOut) {
983 QTimer::singleShot(0,
callbacks.context(), [
this]() {
984 preciseIntervalEditing = startEdit->hasFocus() || endEdit->hasFocus();
990 return QWidget::eventFilter(watched, event);
994 const QList<QPair<qulonglong, std::vector<BusValue>>>& snapshots)
1000 ||
scrollArea->horizontalScrollBar()->value()
1001 ==
scrollArea->horizontalScrollBar()->maximum();
1003 std::vector<Sample> coreSnapshots;
1004 coreSnapshots.reserve(snapshots.size());
1005 for (
const auto& [time, values] : snapshots) {
1006 coreSnapshots.push_back({time, values});
1024 bool durationOk =
false;
1025 const auto typedDuration =
durationEdit->text().toULongLong(&durationOk);
1054 const int scrollValue =
labelScrollArea->verticalScrollBar()->value();
1080 const QString& rawValue)
1082 if (!
editMode || signalIndex < 0 || signalIndex >=
trace.inputCount
1083 || endTime <= startTime)
1086 const auto parsed =
valueFromStr(rawValue.toStdString());
1091 const auto resized =
1103 if (!
editMode || signalIndex < 0 || signalIndex >=
trace.inputCount)
1111 this, tr(
"Input Value"),
1112 tr(
"Set value from %1 to %2").arg(startTime).arg(endTime),
1113 QStringList{tr(
"0"), tr(
"1")}, 0,
false,
1114 [
this, signalIndex, startTime, endTime](
const QString& text) {
1122 this, tr(
"Bus Input"),
1123 tr(
"Set %1-bit value from %2 to %3 "
1124 "(decimal, 0x..., or 0b...)")
1129 [
this, signalIndex, startTime, endTime, width](
const QString& text) {
1134 this, QObject::tr(
"Bus Input"),
1135 QObject::tr(
"The value does not fit in the selected signal width."));
1140 signalIndex, startTime, endTime,
1154 const auto [normalizedStart, normalizedEnd] =
1159 const QSignalBlocker startBlocker(
startEdit);
1160 const QSignalBlocker endBlocker(
endEdit);
1168 bool startOk =
false;
1170 const auto start =
startEdit->text().toULongLong(&startOk);
1171 const auto end =
endEdit->text().toULongLong(&endOk);
1180 const auto displayedDuration =
1182 durationEdit->setText(QString::number(displayedDuration));
1187 const QSignalBlocker blocker(
editAct);
1207 const int signalCount =
static_cast<int>(
trace.signalDefinitions.size());
1208 return editMode ? std::min(
trace.inputCount, signalCount) : signalCount;
1216 result.reserve(visibleCount);
1217 for (
int i = 0; i < visibleCount; ++i)
1218 result.push_back(QString::fromStdString(
1219 trace.signalDefinitions[
static_cast<std::size_t
>(i)].name));
1225 const std::vector<BusValue>* rawValues =
nullptr;
1229 else if (!
trace.samples.empty())
1230 rawValues = &
trace.samples.back().values;
1235 values.reserve(
static_cast<qsizetype
>(rawValues->size()));
1236 for (
int i = 0; i < static_cast<int>(rawValues->size()); ++i)
1237 values.push_back(
displayValue(i, (*rawValues)[
static_cast<std::size_t
>(i)]));
1246 return QString::fromStdString(
1267#ifdef __EMSCRIPTEN__
1268 auto* menu =
new QMenu(
this);
1269 menu->setAttribute(Qt::WA_DeleteOnClose);
1271 QMenu stackMenu(
this);
1272 auto* menu = &stackMenu;
1276 QAction* action = menu->addAction(label);
1277 action->setCheckable(
true);
1278 action->setChecked(formatForSignal(
signalFormats, signalIndex) == format);
1279 callbacks.connect(action, &QAction::triggered, [
this, signalIndex, format]() {
1280 if (normalizedIndex(signalIndex,
static_cast<int>(
signalFormats.size())) < 0)
1282 signalFormats[
static_cast<std::size_t
>(signalIndex)] = format;
1287 const std::array formats{
1294 for (
const auto& [label, format] : formats)
1295 addFormatAction(label, format);
1296#ifdef __EMSCRIPTEN__
1297 menu->popup(globalPosition);
1299 menu->exec(globalPosition);
1305#ifdef __EMSCRIPTEN__
1306 QTemporaryFile traceFile(
this);
1307 if (!traceFile.open()) {
1308 QMessageBox::warning(
1309 this, tr(
"Save Waveform"),
1310 tr(
"Cannot write FST trace:\nCould not create a temporary file."));
1315 const QString traceFileName = traceFile.fileName();
1319 QFile file(traceFileName);
1320 if (!file.open(QIODevice::ReadOnly)) {
1321 QMessageBox::warning(
1322 this, tr(
"Save Waveform"),
1323 tr(
"Cannot write FST trace:\nCould not read the generated trace."));
1327 this, tr(
"Save Waveform"), QStringLiteral(
"waveform.fst"),
1328 tr(
"FST Trace (*.fst);;All Files (*)"), file.readAll());
1329 }
catch (
const std::exception& e) {
1330 QMessageBox::warning(
this, tr(
"Save Waveform"),
1331 tr(
"Cannot write FST trace:\n%1").arg(e.what()));
1334 const QString fileName = QFileDialog::getSaveFileName(
1335 this, tr(
"Save Waveform"), QString(), tr(
"FST Trace (*.fst);;All Files (*)"));
1336 if (fileName.isEmpty())
1341 }
catch (
const std::exception& e) {
1342 QMessageBox::warning(
this, tr(
"Save Waveform"),
1343 tr(
"Cannot write FST trace:\n%1").arg(e.what()));
static const QColor & getColor(theme::ColorToken token)
ParsedBusValue valueFromStr(const std::string_view value)
Parse user-facing decimal, hexadecimal, octal, binary, or four-state text.
std::optional< BusValue > resizeParsedValue(const ParsedBusValue &parsed, const std::size_t width)
Adapts a parsed textual value to an exact destination width.
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
std::optional< QString > saveFileContent(QWidget *parent, const QString &caption, const QString &suggestedFileName, const QString &filter, const QByteArray &content)