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(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();
183 dest->append((char)value);
190 void QHexView::initialize_byte_iterator(size_t offset)
192 current_chunk_id_ = 0;
193 current_chunk_offset_ = 0;
194 current_offset_ = offset;
196 size_t chunks = data_->chunks.size();
197 for (size_t i = 0; i < chunks; i++) {
198 size_t size = data_->chunks[i].data.size();
200 if (offset >= size) {
204 current_chunk_offset_ = offset;
209 if (current_chunk_id_ < data_->chunks.size())
210 current_chunk_ = data_->chunks[current_chunk_id_];
213 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
215 if (is_next_chunk != nullptr)
216 *is_next_chunk = (current_chunk_offset_ == 0);
219 if (current_chunk_offset_ < current_chunk_.data.size())
220 v = current_chunk_.data[current_chunk_offset_];
223 current_chunk_offset_++;
225 if (current_offset_ > data_size_) {
226 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
227 current_offset_ << "of" << data_size_ << "bytes";
231 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
233 current_chunk_offset_ = 0;
234 current_chunk_ = data_->chunks[current_chunk_id_];
240 QSize QHexView::getFullSize() const
242 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
244 if (verticalScrollBar()->isEnabled())
245 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
247 if (!data_ || (data_size_ == 0))
248 return QSize(width, 0);
250 size_t height = data_size_ / BYTES_PER_LINE;
252 if (data_size_ % BYTES_PER_LINE)
255 height *= charHeight_;
257 return QSize(width, height);
260 void QHexView::paintEvent(QPaintEvent *event)
262 QPainter painter(viewport());
264 // Calculate and update the widget and paint area sizes
265 QSize widgetSize = getFullSize();
266 setMinimumWidth(widgetSize.width());
267 setMaximumWidth(widgetSize.width());
268 QSize areaSize = viewport()->size();
270 // Only show scrollbar if the content goes beyond the visible area
271 if (widgetSize.height() > areaSize.height()) {
272 verticalScrollBar()->setEnabled(true);
273 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
274 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
276 verticalScrollBar()->setEnabled(false);
278 // Fill widget background
279 painter.fillRect(event->rect(), palette().color(QPalette::Base));
281 if (!data_ || (data_size_ == 0)) {
282 painter.setPen(palette().color(QPalette::Text));
283 QString s = tr("No data available");
284 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
285 int y = areaSize.height() / 2;
286 painter.drawText(x, y, s);
290 // Determine first/last line indices
291 size_t firstLineIdx = verticalScrollBar()->value();
293 size_t lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
294 if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
295 lastLineIdx = data_size_ / BYTES_PER_LINE;
296 if (data_size_ % BYTES_PER_LINE)
300 // Fill address area background
301 painter.fillRect(QRect(posAddr_, event->rect().top(),
302 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
304 // Paint divider line between hex and ASCII areas
305 int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
306 painter.setPen(palette().color(QPalette::Midlight));
307 painter.drawLine(line_x, event->rect().top(), line_x, height());
309 // Paint address area
310 painter.setPen(palette().color(QPalette::ButtonText));
312 int yStart = charHeight_;
313 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
315 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
316 painter.drawText(posAddr_, y, address);
321 QBrush regular = palette().buttonText();
322 QBrush selected = palette().highlight();
324 bool multiple_chunks = (data_->chunks.size() > 1);
325 unsigned int chunk_color = 0;
327 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
328 yStart = charHeight_;
329 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
332 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
333 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
337 uint8_t byte_value = get_next_byte(&is_next_chunk);
341 if (chunk_color == chunk_colors_.size())
345 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
346 painter.setBackgroundMode(Qt::OpaqueMode);
347 painter.setBackground(selected);
348 painter.setPen(palette().color(QPalette::HighlightedText));
350 painter.setBackground(regular);
351 painter.setBackgroundMode(Qt::TransparentMode);
352 if (!multiple_chunks)
353 painter.setPen(palette().color(QPalette::Text));
355 painter.setPen(chunk_colors_[chunk_color]);
359 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
360 painter.drawText(x, y, val);
363 val = QString::number((byte_value & 0xF), 16).toUpper();
364 painter.drawText(x + charWidth_, y, val);
366 if ((pos >= selectBegin_) && (pos < selectEnd_ - 1) && (i < BYTES_PER_LINE - 1))
367 painter.drawText(x + 2 * charWidth_, y, QString(' '));
375 // Paint ASCII characters
376 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
377 yStart = charHeight_;
378 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
381 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
383 uint8_t ch = get_next_byte();
385 if ((ch < 0x20) || (ch > 0x7E))
388 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
389 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
390 painter.setBackgroundMode(Qt::OpaqueMode);
391 painter.setBackground(selected);
392 painter.setPen(palette().color(QPalette::HighlightedText));
394 painter.setBackgroundMode(Qt::TransparentMode);
395 painter.setBackground(regular);
396 painter.setPen(palette().color(QPalette::Text));
399 painter.drawText(x, y, QString(ch));
408 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
409 int y = cursorPos_ / (2 * BYTES_PER_LINE);
411 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
412 int cursorY = y * charHeight_ + 4;
413 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
417 void QHexView::keyPressEvent(QKeyEvent *event)
419 bool setVisible = false;
422 if (event->matches(QKeySequence::MoveToNextChar)) {
423 setCursorPos(cursorPos_ + 1);
424 resetSelection(cursorPos_);
427 if (event->matches(QKeySequence::MoveToPreviousChar)) {
428 setCursorPos(cursorPos_ - 1);
429 resetSelection(cursorPos_);
433 if (event->matches(QKeySequence::MoveToEndOfLine)) {
434 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
435 resetSelection(cursorPos_);
438 if (event->matches(QKeySequence::MoveToStartOfLine)) {
439 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
440 resetSelection(cursorPos_);
443 if (event->matches(QKeySequence::MoveToPreviousLine)) {
444 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
445 resetSelection(cursorPos_);
448 if (event->matches(QKeySequence::MoveToNextLine)) {
449 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
450 resetSelection(cursorPos_);
454 if (event->matches(QKeySequence::MoveToNextPage)) {
455 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
456 resetSelection(cursorPos_);
459 if (event->matches(QKeySequence::MoveToPreviousPage)) {
460 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
461 resetSelection(cursorPos_);
464 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
465 setCursorPos(data_size_ * 2);
466 resetSelection(cursorPos_);
469 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
471 resetSelection(cursorPos_);
476 if (event->matches(QKeySequence::SelectAll)) {
478 setSelection(2 * data_size_);
481 if (event->matches(QKeySequence::SelectNextChar)) {
482 int pos = cursorPos_ + 1;
487 if (event->matches(QKeySequence::SelectPreviousChar)) {
488 int pos = cursorPos_ - 1;
493 if (event->matches(QKeySequence::SelectEndOfLine)) {
494 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
499 if (event->matches(QKeySequence::SelectStartOfLine)) {
500 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
505 if (event->matches(QKeySequence::SelectPreviousLine)) {
506 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
511 if (event->matches(QKeySequence::SelectNextLine)) {
512 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
518 if (event->matches(QKeySequence::SelectNextPage)) {
519 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
524 if (event->matches(QKeySequence::SelectPreviousPage)) {
525 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
530 if (event->matches(QKeySequence::SelectEndOfDocument)) {
531 int pos = data_size_ * 2;
536 if (event->matches(QKeySequence::SelectStartOfDocument)) {
542 if (event->matches(QKeySequence::Copy) && (data_)) {
545 initialize_byte_iterator(selectBegin_ / 2);
547 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
548 for (size_t i = 0; i < selectedSize; i++) {
549 uint8_t byte_value = get_next_byte();
551 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
552 QString::number((byte_value & 0xF), 16).toUpper() + " ";
555 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
559 QClipboard *clipboard = QApplication::clipboard();
560 clipboard->setText(text, QClipboard::Clipboard);
561 if (clipboard->supportsSelection())
562 clipboard->setText(text, QClipboard::Selection);
568 viewport()->update();
571 void QHexView::mouseMoveEvent(QMouseEvent *event)
573 int actPos = cursorPosFromMousePos(event->pos());
574 setCursorPos(actPos);
575 setSelection(actPos);
577 viewport()->update();
580 void QHexView::mousePressEvent(QMouseEvent *event)
582 int cPos = cursorPosFromMousePos(event->pos());
584 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
587 resetSelection(cPos);
591 viewport()->update();
594 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
598 if (((size_t)position.x() >= posHex_) &&
599 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
601 // Note: We add 1.5 character widths so that selection across
602 // byte gaps is smoother
603 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
605 // Note: We allow only full bytes to be selected, not nibbles,
606 // so we round to the nearest byte gap
609 size_t firstLineIdx = verticalScrollBar()->value();
610 size_t y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
611 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
614 size_t max_pos = data_size_ * 2;
616 return std::min(pos, max_pos);
619 void QHexView::resetSelection()
621 selectBegin_ = selectInit_;
622 selectEnd_ = selectInit_;
625 void QHexView::resetSelection(int pos)
635 void QHexView::setSelection(int pos)
640 if ((size_t)pos >= selectInit_) {
642 selectBegin_ = selectInit_;
645 selectEnd_ = selectInit_;
649 void QHexView::setCursorPos(int position)
654 int max_pos = data_size_ * 2;
656 if (position > max_pos)
659 cursorPos_ = position;
662 void QHexView::ensureVisible()
664 QSize areaSize = viewport()->size();
666 int firstLineIdx = verticalScrollBar()->value();
667 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
669 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
671 if (cursorY < firstLineIdx)
672 verticalScrollBar()->setValue(cursorY);
674 if(cursorY >= lastLineIdx)
675 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);