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)
95 size_t chunks = data_->chunks.size();
96 for (size_t i = 0; i < chunks; i++)
97 size += data_->chunks[i].data.size();
100 viewport()->update();
103 unsigned int QHexView::get_bytes_per_line() const
105 return BYTES_PER_LINE;
108 void QHexView::clear()
110 verticalScrollBar()->setValue(0);
114 viewport()->update();
117 void QHexView::showFromOffset(size_t offset)
119 if (data_ && (offset < data_size_)) {
120 setCursorPos(offset * 2);
122 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
123 verticalScrollBar() -> setValue(cursorY);
126 viewport()->update();
129 QSizePolicy QHexView::sizePolicy() const
131 return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
134 pair<size_t, size_t> QHexView::get_selection() const
136 size_t start = selectBegin_ / 2;
137 size_t end = selectEnd_ / 2;
140 // Nothing is currently selected
146 return std::make_pair(start, end);
149 size_t QHexView::create_hex_line(size_t start, size_t end, QString* dest,
150 bool with_offset, bool with_ascii)
154 // Determine start address for the row
155 uint64_t row = start / BYTES_PER_LINE;
156 uint64_t offset = row * BYTES_PER_LINE;
157 end = std::min((uint64_t)end, offset + BYTES_PER_LINE);
160 dest->append(QString("%1 ").arg(row * BYTES_PER_LINE, 10, 16, QChar('0')).toUpper());
162 initialize_byte_iterator(offset);
163 for (size_t i = offset; i < offset + BYTES_PER_LINE; i++) {
167 value = get_next_byte();
169 if ((i < start) || (i >= end))
172 dest->append(QString("%1 ").arg(value, 2, 16, QChar('0')).toUpper());
176 initialize_byte_iterator(offset);
177 for (size_t i = offset; i < end; i++) {
178 uint8_t value = get_next_byte();
180 if ((value < 0x20) || (value > 0x7E))
186 dest->append((char)value);
193 void QHexView::initialize_byte_iterator(size_t offset)
195 current_chunk_id_ = 0;
196 current_chunk_offset_ = 0;
197 current_offset_ = offset;
199 size_t chunks = data_->chunks.size();
200 for (size_t i = 0; i < chunks; i++) {
201 size_t size = data_->chunks[i].data.size();
203 if (offset >= size) {
207 current_chunk_offset_ = offset;
212 if (current_chunk_id_ < data_->chunks.size())
213 current_chunk_ = data_->chunks[current_chunk_id_];
216 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
218 if (is_next_chunk != nullptr)
219 *is_next_chunk = (current_chunk_offset_ == 0);
222 if (current_chunk_offset_ < current_chunk_.data.size())
223 v = current_chunk_.data[current_chunk_offset_];
226 current_chunk_offset_++;
228 if (current_offset_ > data_size_) {
229 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
230 current_offset_ << "of" << data_size_ << "bytes";
234 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
236 current_chunk_offset_ = 0;
237 current_chunk_ = data_->chunks[current_chunk_id_];
243 QSize QHexView::getFullSize() const
245 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
247 if (verticalScrollBar()->isEnabled())
248 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
250 if (!data_ || (data_size_ == 0))
251 return QSize(width, 0);
253 size_t height = data_size_ / BYTES_PER_LINE;
255 if (data_size_ % BYTES_PER_LINE)
258 height *= charHeight_;
260 return QSize(width, height);
263 void QHexView::paintEvent(QPaintEvent *event)
265 QPainter painter(viewport());
267 // Calculate and update the widget and paint area sizes
268 QSize widgetSize = getFullSize();
269 setMinimumWidth(widgetSize.width());
270 setMaximumWidth(widgetSize.width());
271 QSize areaSize = viewport()->size();
273 // Only show scrollbar if the content goes beyond the visible area
274 if (widgetSize.height() > areaSize.height()) {
275 verticalScrollBar()->setEnabled(true);
276 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
277 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
279 verticalScrollBar()->setEnabled(false);
281 // Fill widget background
282 painter.fillRect(event->rect(), palette().color(QPalette::Base));
284 if (!data_ || (data_size_ == 0)) {
285 painter.setPen(palette().color(QPalette::Text));
286 QString s = tr("No data available");
287 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
288 int y = areaSize.height() / 2;
289 painter.drawText(x, y, s);
293 // Determine first/last line indices
294 size_t firstLineIdx = verticalScrollBar()->value();
296 size_t lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
297 if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
298 lastLineIdx = data_size_ / BYTES_PER_LINE;
299 if (data_size_ % BYTES_PER_LINE)
303 // Fill address area background
304 painter.fillRect(QRect(posAddr_, event->rect().top(),
305 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
307 // Paint divider line between hex and ASCII areas
308 int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
309 painter.setPen(palette().color(QPalette::Midlight));
310 painter.drawLine(line_x, event->rect().top(), line_x, height());
312 // Paint address area
313 painter.setPen(palette().color(QPalette::ButtonText));
315 int yStart = charHeight_;
316 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
318 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
319 painter.drawText(posAddr_, y, address);
324 QBrush regular = palette().buttonText();
325 QBrush selected = palette().highlight();
327 bool multiple_chunks = (data_->chunks.size() > 1);
328 unsigned int chunk_color = 0;
330 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
331 yStart = charHeight_;
332 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
335 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
336 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
340 uint8_t byte_value = get_next_byte(&is_next_chunk);
344 if (chunk_color == chunk_colors_.size())
348 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
349 painter.setBackgroundMode(Qt::OpaqueMode);
350 painter.setBackground(selected);
351 painter.setPen(palette().color(QPalette::HighlightedText));
353 painter.setBackground(regular);
354 painter.setBackgroundMode(Qt::TransparentMode);
355 if (!multiple_chunks)
356 painter.setPen(palette().color(QPalette::Text));
358 painter.setPen(chunk_colors_[chunk_color]);
362 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
363 painter.drawText(x, y, val);
366 val = QString::number((byte_value & 0xF), 16).toUpper();
367 painter.drawText(x + charWidth_, y, val);
369 if ((pos >= selectBegin_) && (pos < selectEnd_ - 1) && (i < BYTES_PER_LINE - 1))
370 painter.drawText(x + 2 * charWidth_, y, QString(' '));
378 // Paint ASCII characters
379 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
380 yStart = charHeight_;
381 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
384 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
386 uint8_t ch = get_next_byte();
388 if ((ch < 0x20) || (ch > 0x7E))
391 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
392 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
393 painter.setBackgroundMode(Qt::OpaqueMode);
394 painter.setBackground(selected);
395 painter.setPen(palette().color(QPalette::HighlightedText));
397 painter.setBackgroundMode(Qt::TransparentMode);
398 painter.setBackground(regular);
399 painter.setPen(palette().color(QPalette::Text));
402 painter.drawText(x, y, QString(ch));
411 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
412 int y = cursorPos_ / (2 * BYTES_PER_LINE);
414 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
415 int cursorY = y * charHeight_ + 4;
416 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
420 void QHexView::keyPressEvent(QKeyEvent *event)
422 bool setVisible = false;
425 if (event->matches(QKeySequence::MoveToNextChar)) {
426 setCursorPos(cursorPos_ + 1);
427 resetSelection(cursorPos_);
430 if (event->matches(QKeySequence::MoveToPreviousChar)) {
431 setCursorPos(cursorPos_ - 1);
432 resetSelection(cursorPos_);
436 if (event->matches(QKeySequence::MoveToEndOfLine)) {
437 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
438 resetSelection(cursorPos_);
441 if (event->matches(QKeySequence::MoveToStartOfLine)) {
442 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
443 resetSelection(cursorPos_);
446 if (event->matches(QKeySequence::MoveToPreviousLine)) {
447 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
448 resetSelection(cursorPos_);
451 if (event->matches(QKeySequence::MoveToNextLine)) {
452 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
453 resetSelection(cursorPos_);
457 if (event->matches(QKeySequence::MoveToNextPage)) {
458 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
459 resetSelection(cursorPos_);
462 if (event->matches(QKeySequence::MoveToPreviousPage)) {
463 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
464 resetSelection(cursorPos_);
467 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
468 setCursorPos(data_size_ * 2);
469 resetSelection(cursorPos_);
472 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
474 resetSelection(cursorPos_);
479 if (event->matches(QKeySequence::SelectAll)) {
481 setSelection(2 * data_size_);
484 if (event->matches(QKeySequence::SelectNextChar)) {
485 int pos = cursorPos_ + 1;
490 if (event->matches(QKeySequence::SelectPreviousChar)) {
491 int pos = cursorPos_ - 1;
496 if (event->matches(QKeySequence::SelectEndOfLine)) {
497 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
502 if (event->matches(QKeySequence::SelectStartOfLine)) {
503 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
508 if (event->matches(QKeySequence::SelectPreviousLine)) {
509 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
514 if (event->matches(QKeySequence::SelectNextLine)) {
515 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
521 if (event->matches(QKeySequence::SelectNextPage)) {
522 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
527 if (event->matches(QKeySequence::SelectPreviousPage)) {
528 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
533 if (event->matches(QKeySequence::SelectEndOfDocument)) {
534 int pos = data_size_ * 2;
539 if (event->matches(QKeySequence::SelectStartOfDocument)) {
545 if (event->matches(QKeySequence::Copy) && (data_)) {
548 initialize_byte_iterator(selectBegin_ / 2);
550 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
551 for (size_t i = 0; i < selectedSize; i++) {
552 uint8_t byte_value = get_next_byte();
554 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
555 QString::number((byte_value & 0xF), 16).toUpper() + " ";
558 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
562 QClipboard *clipboard = QApplication::clipboard();
563 clipboard->setText(text, QClipboard::Clipboard);
564 if (clipboard->supportsSelection())
565 clipboard->setText(text, QClipboard::Selection);
571 viewport()->update();
574 void QHexView::mouseMoveEvent(QMouseEvent *event)
576 int actPos = cursorPosFromMousePos(event->pos());
577 setCursorPos(actPos);
578 setSelection(actPos);
580 viewport()->update();
583 void QHexView::mousePressEvent(QMouseEvent *event)
585 int cPos = cursorPosFromMousePos(event->pos());
587 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
590 resetSelection(cPos);
594 viewport()->update();
597 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
601 if (((size_t)position.x() >= posHex_) &&
602 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
604 // Note: We add 1.5 character widths so that selection across
605 // byte gaps is smoother
606 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
608 // Note: We allow only full bytes to be selected, not nibbles,
609 // so we round to the nearest byte gap
612 size_t firstLineIdx = verticalScrollBar()->value();
613 size_t y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
614 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
617 size_t max_pos = data_size_ * 2;
619 return std::min(pos, max_pos);
622 void QHexView::resetSelection()
624 selectBegin_ = selectInit_;
625 selectEnd_ = selectInit_;
628 void QHexView::resetSelection(int pos)
638 void QHexView::setSelection(int pos)
643 if ((size_t)pos >= selectInit_) {
645 selectBegin_ = selectInit_;
648 selectEnd_ = selectInit_;
652 void QHexView::setCursorPos(int position)
657 int max_pos = data_size_ * 2;
659 if (position > max_pos)
662 cursorPos_ = position;
665 void QHexView::ensureVisible()
667 QSize areaSize = viewport()->size();
669 int firstLineIdx = verticalScrollBar()->value();
670 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
672 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
674 if (cursorY < firstLineIdx)
675 verticalScrollBar()->setValue(cursorY);
677 if(cursorY >= lastLineIdx)
678 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);