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>
38 #include <QPaintEvent>
40 #include "QHexView.hpp"
42 const unsigned int BYTES_PER_LINE = 16;
43 const unsigned int HEXCHARS_IN_LINE = BYTES_PER_LINE * 3 - 1;
44 const unsigned int GAP_ADR_HEX = 10;
45 const unsigned int GAP_HEX_ASCII = 10;
46 const unsigned int GAP_ASCII_SLIDER = 5;
49 QHexView::QHexView(QWidget *parent):
50 QAbstractScrollArea(parent),
51 mode_(ChunkedDataMode),
57 setFont(QFont("Courier", 10));
59 charWidth_ = fontMetrics().boundingRect('X').width();
60 charHeight_ = fontMetrics().height();
62 // Determine X coordinates of the three sub-areas
64 posHex_ = 10 * charWidth_ + GAP_ADR_HEX;
65 posAscii_ = posHex_ + HEXCHARS_IN_LINE * charWidth_ + GAP_HEX_ASCII;
67 setFocusPolicy(Qt::StrongFocus);
69 if (palette().color(QPalette::ButtonText).toHsv().value() > 127) {
71 chunk_colors_.emplace_back(100, 149, 237); // QColorConstants::Svg::cornflowerblue
72 chunk_colors_.emplace_back(60, 179, 113); // QColorConstants::Svg::mediumseagreen
73 chunk_colors_.emplace_back(210, 180, 140); // QColorConstants::Svg::tan
76 chunk_colors_.emplace_back(0, 0, 139); // QColorConstants::Svg::darkblue
77 chunk_colors_.emplace_back(34, 139, 34); // QColorConstants::Svg::forestgreen
78 chunk_colors_.emplace_back(160, 82, 45); // QColorConstants::Svg::sienna
82 void QHexView::set_mode(Mode m)
86 // This is not expected to be set when data is showing,
87 // so we don't update the viewport here
90 void QHexView::set_data(const DecodeBinaryClass* data)
96 size_t chunks = data_->chunks.size();
97 for (size_t i = 0; i < chunks; i++)
98 size += data_->chunks[i].data.size();
102 viewport()->update();
105 unsigned int QHexView::get_bytes_per_line() const
107 return BYTES_PER_LINE;
110 void QHexView::clear()
112 verticalScrollBar()->setValue(0);
116 viewport()->update();
119 void QHexView::showFromOffset(size_t offset)
121 if (data_ && (offset < data_size_)) {
122 setCursorPos(offset * 2);
124 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
125 verticalScrollBar() -> setValue(cursorY);
128 viewport()->update();
131 QSizePolicy QHexView::sizePolicy() const
133 return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
136 pair<size_t, size_t> QHexView::get_selection() const
138 size_t start = selectBegin_ / 2;
139 size_t end = selectEnd_ / 2;
142 // Nothing is currently selected
145 } if (end < data_size_)
148 return std::make_pair(start, end);
151 size_t QHexView::create_hex_line(size_t start, size_t end, QString* dest,
152 bool with_offset, bool with_ascii)
156 // Determine start address for the row
157 uint64_t row = start / BYTES_PER_LINE;
158 uint64_t offset = row * BYTES_PER_LINE;
159 end = std::min((uint64_t)end, offset + BYTES_PER_LINE);
162 dest->append(QString("%1 ").arg(row * BYTES_PER_LINE, 10, 16, QChar('0')).toUpper());
164 initialize_byte_iterator(offset);
165 for (size_t i = offset; i < offset + BYTES_PER_LINE; i++) {
169 value = get_next_byte();
171 if ((i < start) || (i >= end))
174 dest->append(QString("%1 ").arg(value, 2, 16, QChar('0')).toUpper());
178 initialize_byte_iterator(offset);
179 for (size_t i = offset; i < end; i++) {
180 uint8_t value = get_next_byte();
182 if ((value < 0x20) || (value > 0x7E))
188 dest->append((char)value);
195 void QHexView::initialize_byte_iterator(size_t offset)
197 current_chunk_id_ = 0;
198 current_chunk_offset_ = 0;
199 current_offset_ = offset;
201 size_t chunks = data_->chunks.size();
202 for (size_t i = 0; i < chunks; i++) {
203 size_t size = data_->chunks[i].data.size();
205 if (offset >= size) {
209 current_chunk_offset_ = offset;
214 if (current_chunk_id_ < data_->chunks.size())
215 current_chunk_ = data_->chunks[current_chunk_id_];
218 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
220 if (is_next_chunk != nullptr)
221 *is_next_chunk = (current_chunk_offset_ == 0);
224 if (current_chunk_offset_ < current_chunk_.data.size())
225 v = current_chunk_.data[current_chunk_offset_];
228 current_chunk_offset_++;
230 if (current_offset_ > data_size_) {
231 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
232 current_offset_ << "of" << data_size_ << "bytes";
236 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
238 current_chunk_offset_ = 0;
239 current_chunk_ = data_->chunks[current_chunk_id_];
245 QSize QHexView::getFullSize() const
247 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
249 if (verticalScrollBar()->isEnabled())
250 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
252 if (!data_ || (data_size_ == 0))
253 return QSize(width, 0);
255 size_t height = data_size_ / BYTES_PER_LINE;
257 if (data_size_ % BYTES_PER_LINE)
260 height *= charHeight_;
262 return QSize(width, height);
265 void QHexView::paintEvent(QPaintEvent *event)
267 QPainter painter(viewport());
269 // Calculate and update the widget and paint area sizes
270 QSize widgetSize = getFullSize();
271 setMinimumWidth(widgetSize.width());
272 setMaximumWidth(widgetSize.width());
273 QSize areaSize = viewport()->size() - QSize(0, charHeight_);
275 // Only show scrollbar if the content goes beyond the visible area
276 if (widgetSize.height() > areaSize.height()) {
277 verticalScrollBar()->setEnabled(true);
278 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
279 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
281 verticalScrollBar()->setEnabled(false);
283 // Fill widget background
284 painter.fillRect(event->rect(), palette().color(QPalette::Base));
286 if (!data_ || (data_size_ == 0)) {
287 painter.setPen(palette().color(QPalette::Text));
288 QString s = tr("No data available");
289 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
290 int y = areaSize.height() / 2;
291 painter.drawText(x, y, s);
295 // Determine first/last line indices
296 size_t firstLineIdx = verticalScrollBar()->value();
298 size_t lastLineIdx = firstLineIdx + (areaSize.height() / charHeight_);
299 if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
300 lastLineIdx = data_size_ / BYTES_PER_LINE;
301 if (data_size_ % BYTES_PER_LINE)
305 // Paint divider line between hex and ASCII areas
306 int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
307 painter.setPen(palette().color(QPalette::Midlight));
308 painter.drawLine(line_x, event->rect().top(), line_x, height());
310 // Fill address area background
311 painter.fillRect(QRect(posAddr_, event->rect().top(),
312 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
313 painter.fillRect(QRect(posAddr_, event->rect().top(),
314 posAscii_ - (GAP_HEX_ASCII / 2), charHeight_ + 2), palette().color(QPalette::Window));
316 // Paint address area
317 painter.setPen(palette().color(QPalette::ButtonText));
319 int yStart = 2 * charHeight_;
320 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
322 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
323 painter.drawText(posAddr_, y, address);
327 // Paint top row with hex offsets
328 painter.setPen(palette().color(QPalette::ButtonText));
329 for (int offset = 0; offset <= 0xF; offset++)
330 painter.drawText(posHex_ + (1 + offset * 3) * charWidth_,
331 charHeight_ - 3, QString::number(offset, 16).toUpper());
334 QBrush regular = palette().buttonText();
335 QBrush selected = palette().highlight();
337 bool multiple_chunks = (data_->chunks.size() > 1);
338 unsigned int chunk_color = 0;
340 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
341 yStart = 2 * charHeight_;
342 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
345 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
346 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
350 uint8_t byte_value = get_next_byte(&is_next_chunk);
354 if (chunk_color == chunk_colors_.size())
358 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
359 painter.setBackgroundMode(Qt::OpaqueMode);
360 painter.setBackground(selected);
361 painter.setPen(palette().color(QPalette::HighlightedText));
363 painter.setBackground(regular);
364 painter.setBackgroundMode(Qt::TransparentMode);
365 if (!multiple_chunks)
366 painter.setPen(palette().color(QPalette::Text));
368 painter.setPen(chunk_colors_[chunk_color]);
372 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
373 painter.drawText(x, y, val);
376 val = QString::number((byte_value & 0xF), 16).toUpper();
377 painter.drawText(x + charWidth_, y, val);
379 if ((pos >= selectBegin_) && (pos < selectEnd_ - 1) && (i < BYTES_PER_LINE - 1))
380 painter.drawText(x + 2 * charWidth_, y, QString(' '));
388 // Paint ASCII characters
389 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
390 yStart = 2 * charHeight_;
391 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
394 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
396 uint8_t ch = get_next_byte();
398 if ((ch < 0x20) || (ch > 0x7E))
401 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
402 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
403 painter.setBackgroundMode(Qt::OpaqueMode);
404 painter.setBackground(selected);
405 painter.setPen(palette().color(QPalette::HighlightedText));
407 painter.setBackgroundMode(Qt::TransparentMode);
408 painter.setBackground(regular);
409 painter.setPen(palette().color(QPalette::Text));
412 painter.drawText(x, y, QString(ch));
421 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
422 int y = cursorPos_ / (2 * BYTES_PER_LINE);
424 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
425 int cursorY = charHeight_ + y * charHeight_ + 4;
426 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
430 void QHexView::keyPressEvent(QKeyEvent *event)
432 bool setVisible = false;
435 if (event->matches(QKeySequence::MoveToNextChar)) {
436 setCursorPos(cursorPos_ + 1);
437 resetSelection(cursorPos_);
440 if (event->matches(QKeySequence::MoveToPreviousChar)) {
441 setCursorPos(cursorPos_ - 1);
442 resetSelection(cursorPos_);
446 if (event->matches(QKeySequence::MoveToEndOfLine)) {
447 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
448 resetSelection(cursorPos_);
451 if (event->matches(QKeySequence::MoveToStartOfLine)) {
452 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
453 resetSelection(cursorPos_);
456 if (event->matches(QKeySequence::MoveToPreviousLine)) {
457 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
458 resetSelection(cursorPos_);
461 if (event->matches(QKeySequence::MoveToNextLine)) {
462 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
463 resetSelection(cursorPos_);
467 if (event->matches(QKeySequence::MoveToNextPage)) {
468 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
469 resetSelection(cursorPos_);
472 if (event->matches(QKeySequence::MoveToPreviousPage)) {
473 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
474 resetSelection(cursorPos_);
477 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
478 setCursorPos(data_size_ * 2);
479 resetSelection(cursorPos_);
482 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
484 resetSelection(cursorPos_);
489 if (event->matches(QKeySequence::SelectAll)) {
491 setSelection(2 * data_size_);
494 if (event->matches(QKeySequence::SelectNextChar)) {
495 int pos = cursorPos_ + 1;
500 if (event->matches(QKeySequence::SelectPreviousChar)) {
501 int pos = cursorPos_ - 1;
506 if (event->matches(QKeySequence::SelectEndOfLine)) {
507 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
512 if (event->matches(QKeySequence::SelectStartOfLine)) {
513 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
518 if (event->matches(QKeySequence::SelectPreviousLine)) {
519 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
524 if (event->matches(QKeySequence::SelectNextLine)) {
525 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
531 if (event->matches(QKeySequence::SelectNextPage)) {
532 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
537 if (event->matches(QKeySequence::SelectPreviousPage)) {
538 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
543 if (event->matches(QKeySequence::SelectEndOfDocument)) {
544 int pos = data_size_ * 2;
549 if (event->matches(QKeySequence::SelectStartOfDocument)) {
555 if (event->matches(QKeySequence::Copy) && (data_)) {
558 initialize_byte_iterator(selectBegin_ / 2);
560 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
561 for (size_t i = 0; i < selectedSize; i++) {
562 uint8_t byte_value = get_next_byte();
564 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
565 QString::number((byte_value & 0xF), 16).toUpper() + " ";
568 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
572 QClipboard *clipboard = QApplication::clipboard();
573 clipboard->setText(text, QClipboard::Clipboard);
574 if (clipboard->supportsSelection())
575 clipboard->setText(text, QClipboard::Selection);
581 viewport()->update();
584 void QHexView::mouseMoveEvent(QMouseEvent *event)
586 int actPos = cursorPosFromMousePos(event->pos());
587 setCursorPos(actPos);
588 setSelection(actPos);
590 viewport()->update();
593 void QHexView::mousePressEvent(QMouseEvent *event)
595 int cPos = cursorPosFromMousePos(event->pos());
597 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
600 resetSelection(cPos);
604 viewport()->update();
607 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
611 if (((size_t)position.x() >= posHex_) &&
612 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
614 // Note: We add 1.5 character widths so that selection across
615 // byte gaps is smoother
616 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
618 // Note: We allow only full bytes to be selected, not nibbles,
619 // so we round to the nearest byte gap
622 size_t firstLineIdx = verticalScrollBar()->value();
623 size_t y = ((position.y() / charHeight_) - 1) * 2 * BYTES_PER_LINE;
624 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
627 size_t max_pos = data_size_ * 2;
629 return std::min(pos, max_pos);
632 void QHexView::resetSelection()
634 selectBegin_ = selectInit_;
635 selectEnd_ = selectInit_;
638 void QHexView::resetSelection(int pos)
648 void QHexView::setSelection(int pos)
653 if ((size_t)pos >= selectInit_) {
655 selectBegin_ = selectInit_;
658 selectEnd_ = selectInit_;
662 void QHexView::setCursorPos(int position)
667 int max_pos = data_size_ * 2;
669 if (position > max_pos)
672 cursorPos_ = position;
675 void QHexView::ensureVisible()
677 QSize areaSize = viewport()->size();
679 int firstLineIdx = verticalScrollBar()->value();
680 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
682 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
684 if (cursorY < firstLineIdx)
685 verticalScrollBar()->setValue(cursorY);
687 if(cursorY >= lastLineIdx)
688 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);