2 * This file is part of the PulseView project.
4 * Copyright (C) 2015 Victor Anjin <virinext@gmail.com>
5 * Copyright (C) 2019 Soeren Apel <soeren@apelpie.net>
7 * The MIT License (MIT)
11 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
18 * The above copyright notice and this permission notice shall be included in all
19 * copies or substantial portions of the Software.
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 #include <QApplication>
39 #include <QPaintEvent>
41 #include "QHexView.hpp"
43 const unsigned int BYTES_PER_LINE = 16;
44 const unsigned int HEXCHARS_IN_LINE = BYTES_PER_LINE * 3 - 1;
45 const unsigned int GAP_ADR_HEX = 10;
46 const unsigned int GAP_HEX_ASCII = 10;
47 const unsigned int GAP_ASCII_SLIDER = 5;
50 QHexView::QHexView(QWidget *parent):
51 QAbstractScrollArea(parent),
52 mode_(ChunkedDataMode),
58 setFont(QFont("Courier", 10));
60 charWidth_ = fontMetrics().boundingRect('X').width();
61 charHeight_ = fontMetrics().height();
63 setFocusPolicy(Qt::StrongFocus);
65 if (palette().color(QPalette::ButtonText).toHsv().value() > 127) {
67 chunk_colors_.emplace_back(100, 149, 237); // QColorConstants::Svg::cornflowerblue
68 chunk_colors_.emplace_back(60, 179, 113); // QColorConstants::Svg::mediumseagreen
69 chunk_colors_.emplace_back(210, 180, 140); // QColorConstants::Svg::tan
72 chunk_colors_.emplace_back(0, 0, 139); // QColorConstants::Svg::darkblue
73 chunk_colors_.emplace_back(34, 139, 34); // QColorConstants::Svg::forestgreen
74 chunk_colors_.emplace_back(160, 82, 45); // QColorConstants::Svg::sienna
78 void QHexView::set_mode(Mode m)
82 // This is not expected to be set when data is showing,
83 // so we don't update the viewport here
86 void QHexView::set_data(const DecodeBinaryClass* data)
92 size_t chunks = data_->chunks.size();
93 for (size_t i = 0; i < chunks; i++)
94 size += data_->chunks[i].data.size();
98 address_digits_ = (uint8_t)QString::number(data_size_, 16).length();
100 // Calculate X coordinates of the three sub-areas
102 posHex_ = address_digits_ * charWidth_ + GAP_ADR_HEX;
103 posAscii_ = posHex_ + HEXCHARS_IN_LINE * charWidth_ + GAP_HEX_ASCII;
105 viewport()->update();
108 unsigned int QHexView::get_bytes_per_line() const
110 return BYTES_PER_LINE;
113 void QHexView::clear()
115 verticalScrollBar()->setValue(0);
119 viewport()->update();
122 void QHexView::showFromOffset(size_t offset)
124 if (data_ && (offset < data_size_)) {
125 setCursorPos(offset * 2);
127 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
128 verticalScrollBar() -> setValue(cursorY);
131 viewport()->update();
134 QSizePolicy QHexView::sizePolicy() const
136 return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
139 pair<size_t, size_t> QHexView::get_selection() const
141 size_t start = selectBegin_ / 2;
142 size_t end = selectEnd_ / 2;
145 // Nothing is currently selected
148 } if (end < data_size_)
151 return std::make_pair(start, end);
154 size_t QHexView::create_hex_line(size_t start, size_t end, QString* dest,
155 bool with_offset, bool with_ascii)
159 // Determine start address for the row
160 uint64_t row = start / BYTES_PER_LINE;
161 uint64_t offset = row * BYTES_PER_LINE;
162 end = std::min((uint64_t)end, offset + BYTES_PER_LINE);
165 dest->append(QString("%1 ").arg(row * BYTES_PER_LINE, address_digits_, 16, QChar('0')).toUpper());
167 initialize_byte_iterator(offset);
168 for (size_t i = offset; i < offset + BYTES_PER_LINE; i++) {
172 value = get_next_byte();
174 if ((i < start) || (i >= end))
177 dest->append(QString("%1 ").arg(value, 2, 16, QChar('0')).toUpper());
181 initialize_byte_iterator(offset);
182 for (size_t i = offset; i < end; i++) {
183 uint8_t value = get_next_byte();
185 if ((value < 0x20) || (value > 0x7E))
191 dest->append((char)value);
198 void QHexView::initialize_byte_iterator(size_t offset)
200 current_chunk_id_ = 0;
201 current_chunk_offset_ = 0;
202 current_offset_ = offset;
204 size_t chunks = data_->chunks.size();
205 for (size_t i = 0; i < chunks; i++) {
206 size_t size = data_->chunks[i].data.size();
208 if (offset >= size) {
212 current_chunk_offset_ = offset;
217 if (current_chunk_id_ < data_->chunks.size())
218 current_chunk_ = data_->chunks[current_chunk_id_];
221 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
223 if (is_next_chunk != nullptr)
224 *is_next_chunk = (current_chunk_offset_ == 0);
227 if (current_chunk_offset_ < current_chunk_.data.size())
228 v = current_chunk_.data[current_chunk_offset_];
231 current_chunk_offset_++;
233 if (current_offset_ > data_size_) {
234 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
235 current_offset_ << "of" << data_size_ << "bytes";
239 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
241 current_chunk_offset_ = 0;
242 current_chunk_ = data_->chunks[current_chunk_id_];
248 QSize QHexView::getFullSize() const
250 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
252 if (verticalScrollBar()->isEnabled())
253 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
255 if (!data_ || (data_size_ == 0))
256 return QSize(width, 0);
258 size_t height = data_size_ / BYTES_PER_LINE;
260 if (data_size_ % BYTES_PER_LINE)
263 height *= charHeight_;
265 return QSize(width, height);
268 void QHexView::paintEvent(QPaintEvent *event)
270 QPainter painter(viewport());
272 // Calculate and update the widget and paint area sizes
273 QSize widgetSize = getFullSize();
274 setMinimumWidth(widgetSize.width());
275 setMaximumWidth(widgetSize.width());
276 QSize areaSize = viewport()->size() - QSize(0, charHeight_);
278 // Only show scrollbar if the content goes beyond the visible area
279 if (widgetSize.height() > areaSize.height()) {
280 verticalScrollBar()->setEnabled(true);
281 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
282 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
284 verticalScrollBar()->setEnabled(false);
286 // Fill widget background
287 painter.fillRect(event->rect(), palette().color(QPalette::Base));
289 if (!data_ || (data_size_ == 0) || (data_->chunks.empty())) {
290 painter.setPen(palette().color(QPalette::Text));
291 QString s = tr("No data available");
292 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
293 int y = areaSize.height() / 2;
294 painter.drawText(x, y, s);
298 // Determine first/last line indices
299 size_t firstLineIdx = verticalScrollBar()->value();
301 size_t lastLineIdx = firstLineIdx + (areaSize.height() / charHeight_);
302 if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
303 lastLineIdx = data_size_ / BYTES_PER_LINE;
304 if (data_size_ % BYTES_PER_LINE)
308 // Paint divider line between hex and ASCII areas
309 int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
310 painter.setPen(palette().color(QPalette::Midlight));
311 painter.drawLine(line_x, event->rect().top(), line_x, height());
313 // Fill address area background
314 painter.fillRect(QRect(posAddr_, event->rect().top(),
315 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
316 painter.fillRect(QRect(posAddr_, event->rect().top(),
317 posAscii_ - (GAP_HEX_ASCII / 2), charHeight_ + 2), palette().color(QPalette::Window));
319 // Paint address area
320 painter.setPen(palette().color(QPalette::ButtonText));
322 int yStart = 2 * charHeight_;
323 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
325 QString address = QString("%1").arg(lineIdx * 16, address_digits_, 16, QChar('0')).toUpper();
326 painter.drawText(posAddr_, y, address);
330 // Paint top row with hex offsets
331 painter.setPen(palette().color(QPalette::ButtonText));
332 for (int offset = 0; offset <= 0xF; offset++)
333 painter.drawText(posHex_ + (1 + offset * 3) * charWidth_,
334 charHeight_ - 3, QString::number(offset, 16).toUpper());
337 QBrush regular = palette().buttonText();
338 QBrush selected = palette().highlight();
340 bool multiple_chunks = (data_->chunks.size() > 1);
341 unsigned int chunk_color = 0;
343 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
344 yStart = 2 * charHeight_;
345 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
348 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
349 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
353 uint8_t byte_value = get_next_byte(&is_next_chunk);
357 if (chunk_color == chunk_colors_.size())
361 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
362 painter.setBackgroundMode(Qt::OpaqueMode);
363 painter.setBackground(selected);
364 painter.setPen(palette().color(QPalette::HighlightedText));
366 painter.setBackground(regular);
367 painter.setBackgroundMode(Qt::TransparentMode);
368 if (!multiple_chunks)
369 painter.setPen(palette().color(QPalette::Text));
371 painter.setPen(chunk_colors_[chunk_color]);
375 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
376 painter.drawText(x, y, val);
379 val = QString::number((byte_value & 0xF), 16).toUpper();
380 painter.drawText(x + charWidth_, y, val);
382 if ((pos >= selectBegin_) && (pos < selectEnd_ - 1) && (i < BYTES_PER_LINE - 1))
383 painter.drawText(x + 2 * charWidth_, y, QString(' '));
391 // Paint ASCII characters
392 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
393 yStart = 2 * charHeight_;
394 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
397 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
399 uint8_t ch = get_next_byte();
401 if ((ch < 0x20) || (ch > 0x7E))
404 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
405 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
406 painter.setBackgroundMode(Qt::OpaqueMode);
407 painter.setBackground(selected);
408 painter.setPen(palette().color(QPalette::HighlightedText));
410 painter.setBackgroundMode(Qt::TransparentMode);
411 painter.setBackground(regular);
412 painter.setPen(palette().color(QPalette::Text));
415 painter.drawText(x, y, QString(ch));
424 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
425 int y = cursorPos_ / (2 * BYTES_PER_LINE);
427 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
428 int cursorY = charHeight_ + y * charHeight_ + 4;
429 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
433 void QHexView::keyPressEvent(QKeyEvent *event)
435 bool setVisible = false;
438 if (event->matches(QKeySequence::MoveToNextChar)) {
439 setCursorPos(cursorPos_ + 1);
440 resetSelection(cursorPos_);
443 if (event->matches(QKeySequence::MoveToPreviousChar)) {
444 setCursorPos(cursorPos_ - 1);
445 resetSelection(cursorPos_);
449 if (event->matches(QKeySequence::MoveToEndOfLine)) {
450 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
451 resetSelection(cursorPos_);
454 if (event->matches(QKeySequence::MoveToStartOfLine)) {
455 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
456 resetSelection(cursorPos_);
459 if (event->matches(QKeySequence::MoveToPreviousLine)) {
460 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
461 resetSelection(cursorPos_);
464 if (event->matches(QKeySequence::MoveToNextLine)) {
465 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
466 resetSelection(cursorPos_);
470 if (event->matches(QKeySequence::MoveToNextPage)) {
471 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
472 resetSelection(cursorPos_);
475 if (event->matches(QKeySequence::MoveToPreviousPage)) {
476 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
477 resetSelection(cursorPos_);
480 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
481 setCursorPos(data_size_ * 2);
482 resetSelection(cursorPos_);
485 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
487 resetSelection(cursorPos_);
492 if (event->matches(QKeySequence::SelectAll)) {
494 setSelection(2 * data_size_);
497 if (event->matches(QKeySequence::SelectNextChar)) {
498 int pos = cursorPos_ + 1;
503 if (event->matches(QKeySequence::SelectPreviousChar)) {
504 int pos = cursorPos_ - 1;
509 if (event->matches(QKeySequence::SelectEndOfLine)) {
510 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
515 if (event->matches(QKeySequence::SelectStartOfLine)) {
516 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
521 if (event->matches(QKeySequence::SelectPreviousLine)) {
522 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
527 if (event->matches(QKeySequence::SelectNextLine)) {
528 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
534 if (event->matches(QKeySequence::SelectNextPage)) {
535 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
540 if (event->matches(QKeySequence::SelectPreviousPage)) {
541 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
546 if (event->matches(QKeySequence::SelectEndOfDocument)) {
547 int pos = data_size_ * 2;
552 if (event->matches(QKeySequence::SelectStartOfDocument)) {
558 if (event->matches(QKeySequence::Copy) && (data_)) {
561 initialize_byte_iterator(selectBegin_ / 2);
563 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
564 for (size_t i = 0; i < selectedSize; i++) {
565 uint8_t byte_value = get_next_byte();
567 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
568 QString::number((byte_value & 0xF), 16).toUpper() + " ";
571 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
575 QClipboard *clipboard = QApplication::clipboard();
576 clipboard->setText(text, QClipboard::Clipboard);
577 if (clipboard->supportsSelection())
578 clipboard->setText(text, QClipboard::Selection);
584 viewport()->update();
587 void QHexView::mouseMoveEvent(QMouseEvent *event)
589 int actPos = cursorPosFromMousePos(event->pos());
590 setCursorPos(actPos);
591 setSelection(actPos);
593 viewport()->update();
596 void QHexView::mousePressEvent(QMouseEvent *event)
598 int cPos = cursorPosFromMousePos(event->pos());
600 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
603 resetSelection(cPos);
607 viewport()->update();
610 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
614 if (((size_t)position.x() >= posHex_) &&
615 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
617 // Note: We add 1.5 character widths so that selection across
618 // byte gaps is smoother
619 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
621 // Note: We allow only full bytes to be selected, not nibbles,
622 // so we round to the nearest byte gap
625 size_t firstLineIdx = verticalScrollBar()->value();
626 size_t y = ((position.y() / charHeight_) - 1) * 2 * BYTES_PER_LINE;
627 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
630 size_t max_pos = data_size_ * 2;
632 return std::min(pos, max_pos);
635 void QHexView::resetSelection()
637 selectBegin_ = selectInit_;
638 selectEnd_ = selectInit_;
641 void QHexView::resetSelection(int pos)
651 void QHexView::setSelection(int pos)
656 if ((size_t)pos >= selectInit_) {
658 selectBegin_ = selectInit_;
661 selectEnd_ = selectInit_;
665 void QHexView::setCursorPos(int position)
670 int max_pos = data_size_ * 2;
672 if (position > max_pos)
675 cursorPos_ = position;
678 void QHexView::ensureVisible()
680 QSize areaSize = viewport()->size();
682 int firstLineIdx = verticalScrollBar()->value();
683 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
685 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
687 if (cursorY < firstLineIdx)
688 verticalScrollBar()->setValue(cursorY);
690 if(cursorY >= lastLineIdx)
691 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);