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::setMode(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::setData(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 void QHexView::clear()
105 verticalScrollBar()->setValue(0);
109 viewport()->update();
112 void QHexView::showFromOffset(size_t offset)
114 if (data_ && (offset < data_size_)) {
115 setCursorPos(offset * 2);
117 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
118 verticalScrollBar() -> setValue(cursorY);
121 viewport()->update();
124 QSizePolicy QHexView::sizePolicy() const
126 return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
129 pair<size_t, size_t> QHexView::get_selection() const
131 size_t start = selectBegin_ / 2;
132 size_t end = selectEnd_ / 2;
135 // Nothing is currently selected
141 return std::make_pair(start, end);
144 void QHexView::initialize_byte_iterator(size_t offset)
146 current_chunk_id_ = 0;
147 current_chunk_offset_ = 0;
148 current_offset_ = offset;
150 size_t chunks = data_->chunks.size();
151 for (size_t i = 0; i < chunks; i++) {
152 size_t size = data_->chunks[i].data.size();
154 if (offset >= size) {
158 current_chunk_offset_ = offset;
163 if (current_chunk_id_ < data_->chunks.size())
164 current_chunk_ = data_->chunks[current_chunk_id_];
167 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
169 if (is_next_chunk != nullptr)
170 *is_next_chunk = (current_chunk_offset_ == 0);
173 if (current_chunk_offset_ < current_chunk_.data.size())
174 v = current_chunk_.data[current_chunk_offset_];
177 current_chunk_offset_++;
179 if (current_offset_ > data_size_) {
180 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
181 current_offset_ << "of" << data_size_ << "bytes";
185 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
187 current_chunk_offset_ = 0;
188 current_chunk_ = data_->chunks[current_chunk_id_];
194 QSize QHexView::getFullSize() const
196 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
198 if (verticalScrollBar()->isEnabled())
199 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
201 if (!data_ || (data_size_ == 0))
202 return QSize(width, 0);
204 size_t height = data_size_ / BYTES_PER_LINE;
206 if (data_size_ % BYTES_PER_LINE)
209 height *= charHeight_;
211 return QSize(width, height);
214 void QHexView::paintEvent(QPaintEvent *event)
216 QPainter painter(viewport());
218 // Calculate and update the widget and paint area sizes
219 QSize widgetSize = getFullSize();
220 setMinimumWidth(widgetSize.width());
221 setMaximumWidth(widgetSize.width());
222 QSize areaSize = viewport()->size();
224 // Only show scrollbar if the content goes beyond the visible area
225 if (widgetSize.height() > areaSize.height()) {
226 verticalScrollBar()->setEnabled(true);
227 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
228 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
230 verticalScrollBar()->setEnabled(false);
232 // Fill widget background
233 painter.fillRect(event->rect(), palette().color(QPalette::Base));
235 if (!data_ || (data_size_ == 0)) {
236 painter.setPen(palette().color(QPalette::Text));
237 QString s = tr("No data available");
238 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
239 int y = areaSize.height() / 2;
240 painter.drawText(x, y, s);
244 // Determine first/last line indices
245 size_t firstLineIdx = verticalScrollBar()->value();
247 size_t lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
248 if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
249 lastLineIdx = data_size_ / BYTES_PER_LINE;
250 if (data_size_ % BYTES_PER_LINE)
254 // Fill address area background
255 painter.fillRect(QRect(posAddr_, event->rect().top(),
256 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
258 // Paint divider line between hex and ASCII areas
259 int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
260 painter.setPen(palette().color(QPalette::Midlight));
261 painter.drawLine(line_x, event->rect().top(), line_x, height());
263 // Paint address area
264 painter.setPen(palette().color(QPalette::ButtonText));
266 int yStart = charHeight_;
267 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
269 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
270 painter.drawText(posAddr_, y, address);
275 QBrush regular = palette().buttonText();
276 QBrush selected = palette().highlight();
278 bool multiple_chunks = (data_->chunks.size() > 1);
279 unsigned int chunk_color = 0;
281 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
282 yStart = charHeight_;
283 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
286 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
287 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
291 uint8_t byte_value = get_next_byte(&is_next_chunk);
295 if (chunk_color == chunk_colors_.size())
299 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
300 painter.setBackgroundMode(Qt::OpaqueMode);
301 painter.setBackground(selected);
302 painter.setPen(palette().color(QPalette::HighlightedText));
304 painter.setBackground(regular);
305 painter.setBackgroundMode(Qt::TransparentMode);
306 if (!multiple_chunks)
307 painter.setPen(palette().color(QPalette::Text));
309 painter.setPen(chunk_colors_[chunk_color]);
313 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
314 painter.drawText(x, y, val);
317 val = QString::number((byte_value & 0xF), 16).toUpper();
318 painter.drawText(x + charWidth_, y, val);
326 // Paint ASCII characters
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++) {
334 uint8_t ch = get_next_byte();
336 if ((ch < 0x20) || (ch > 0x7E))
339 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
340 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
341 painter.setBackgroundMode(Qt::OpaqueMode);
342 painter.setBackground(selected);
343 painter.setPen(palette().color(QPalette::HighlightedText));
345 painter.setBackgroundMode(Qt::TransparentMode);
346 painter.setBackground(regular);
347 painter.setPen(palette().color(QPalette::Text));
350 painter.drawText(x, y, QString(ch));
359 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
360 int y = cursorPos_ / (2 * BYTES_PER_LINE);
362 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
363 int cursorY = y * charHeight_ + 4;
364 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
368 void QHexView::keyPressEvent(QKeyEvent *event)
370 bool setVisible = false;
373 if (event->matches(QKeySequence::MoveToNextChar)) {
374 setCursorPos(cursorPos_ + 1);
375 resetSelection(cursorPos_);
378 if (event->matches(QKeySequence::MoveToPreviousChar)) {
379 setCursorPos(cursorPos_ - 1);
380 resetSelection(cursorPos_);
384 if (event->matches(QKeySequence::MoveToEndOfLine)) {
385 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
386 resetSelection(cursorPos_);
389 if (event->matches(QKeySequence::MoveToStartOfLine)) {
390 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
391 resetSelection(cursorPos_);
394 if (event->matches(QKeySequence::MoveToPreviousLine)) {
395 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
396 resetSelection(cursorPos_);
399 if (event->matches(QKeySequence::MoveToNextLine)) {
400 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
401 resetSelection(cursorPos_);
405 if (event->matches(QKeySequence::MoveToNextPage)) {
406 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
407 resetSelection(cursorPos_);
410 if (event->matches(QKeySequence::MoveToPreviousPage)) {
411 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
412 resetSelection(cursorPos_);
415 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
416 setCursorPos(data_size_ * 2);
417 resetSelection(cursorPos_);
420 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
422 resetSelection(cursorPos_);
427 if (event->matches(QKeySequence::SelectAll)) {
429 setSelection(2 * data_size_);
432 if (event->matches(QKeySequence::SelectNextChar)) {
433 int pos = cursorPos_ + 1;
438 if (event->matches(QKeySequence::SelectPreviousChar)) {
439 int pos = cursorPos_ - 1;
444 if (event->matches(QKeySequence::SelectEndOfLine)) {
445 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
450 if (event->matches(QKeySequence::SelectStartOfLine)) {
451 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
456 if (event->matches(QKeySequence::SelectPreviousLine)) {
457 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
462 if (event->matches(QKeySequence::SelectNextLine)) {
463 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
469 if (event->matches(QKeySequence::SelectNextPage)) {
470 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
475 if (event->matches(QKeySequence::SelectPreviousPage)) {
476 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
481 if (event->matches(QKeySequence::SelectEndOfDocument)) {
482 int pos = data_size_ * 2;
487 if (event->matches(QKeySequence::SelectStartOfDocument)) {
493 if (event->matches(QKeySequence::Copy) && (data_)) {
496 initialize_byte_iterator(selectBegin_ / 2);
498 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
499 for (size_t i = 0; i < selectedSize; i++) {
500 uint8_t byte_value = get_next_byte();
502 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
503 QString::number((byte_value & 0xF), 16).toUpper() + " ";
506 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
510 QClipboard *clipboard = QApplication::clipboard();
511 clipboard->setText(text, QClipboard::Clipboard);
512 if (clipboard->supportsSelection())
513 clipboard->setText(text, QClipboard::Selection);
519 viewport()->update();
522 void QHexView::mouseMoveEvent(QMouseEvent *event)
524 int actPos = cursorPosFromMousePos(event->pos());
525 setCursorPos(actPos);
526 setSelection(actPos);
528 viewport()->update();
531 void QHexView::mousePressEvent(QMouseEvent *event)
533 int cPos = cursorPosFromMousePos(event->pos());
535 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
538 resetSelection(cPos);
542 viewport()->update();
545 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
549 if (((size_t)position.x() >= posHex_) &&
550 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
552 // Note: We add 1.5 character widths so that selection across
553 // byte gaps is smoother
554 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
556 // Note: We allow only full bytes to be selected, not nibbles,
557 // so we round to the nearest byte gap
560 size_t firstLineIdx = verticalScrollBar()->value();
561 size_t y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
562 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
565 size_t max_pos = data_size_ * 2;
567 return std::min(pos, max_pos);
570 void QHexView::resetSelection()
572 selectBegin_ = selectInit_;
573 selectEnd_ = selectInit_;
576 void QHexView::resetSelection(int pos)
586 void QHexView::setSelection(int pos)
591 if ((size_t)pos >= selectInit_) {
593 selectBegin_ = selectInit_;
596 selectEnd_ = selectInit_;
600 void QHexView::setCursorPos(int position)
605 int max_pos = data_size_ * 2;
607 if (position > max_pos)
610 cursorPos_ = position;
613 void QHexView::ensureVisible()
615 QSize areaSize = viewport()->size();
617 int firstLineIdx = verticalScrollBar()->value();
618 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
620 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
622 if (cursorY < firstLineIdx)
623 verticalScrollBar()->setValue(cursorY);
625 if(cursorY >= lastLineIdx)
626 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);