]> sigrok.org Git - pulseview.git/blame_incremental - pv/views/decoder_output/QHexView.cpp
DecoderOutputView: Implement saving
[pulseview.git] / pv / views / decoder_output / QHexView.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2015 Victor Anjin <virinext@gmail.com>
5 * Copyright (C) 2019 Soeren Apel <soeren@apelpie.net>
6 *
7 * The MIT License (MIT)
8 *
9 * Copyright (c) 2015
10 *
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:
17 *
18 * The above copyright notice and this permission notice shall be included in all
19 * copies or substantial portions of the Software.
20 *
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
27 * SOFTWARE.
28 */
29
30#include <QApplication>
31#include <QClipboard>
32#include <QDebug>
33#include <QFont>
34#include <QKeyEvent>
35#include <QScrollBar>
36#include <QSize>
37#include <QPainter>
38#include <QPaintEvent>
39
40#include "QHexView.hpp"
41
42const unsigned int BYTES_PER_LINE = 16;
43const unsigned int HEXCHARS_IN_LINE = BYTES_PER_LINE * 3 - 1;
44const unsigned int GAP_ADR_HEX = 10;
45const unsigned int GAP_HEX_ASCII = 10;
46const unsigned int GAP_ASCII_SLIDER = 5;
47
48
49QHexView::QHexView(QWidget *parent):
50 QAbstractScrollArea(parent),
51 mode_(ChunkedDataMode),
52 data_(nullptr),
53 selectBegin_(0),
54 selectEnd_(0),
55 cursorPos_(0)
56{
57 setFont(QFont("Courier", 10));
58
59 charWidth_ = fontMetrics().boundingRect('X').width();
60 charHeight_ = fontMetrics().height();
61
62 // Determine X coordinates of the three sub-areas
63 posAddr_ = 0;
64 posHex_ = 10 * charWidth_ + GAP_ADR_HEX;
65 posAscii_ = posHex_ + HEXCHARS_IN_LINE * charWidth_ + GAP_HEX_ASCII;
66
67 setFocusPolicy(Qt::StrongFocus);
68
69 if (palette().color(QPalette::ButtonText).toHsv().value() > 127) {
70 // Color is bright
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
74 } else {
75 // Color is dark
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
79 }
80}
81
82void QHexView::set_mode(Mode m)
83{
84 mode_ = m;
85
86 // This is not expected to be set when data is showing,
87 // so we don't update the viewport here
88}
89
90void QHexView::set_data(const DecodeBinaryClass* data)
91{
92 data_ = data;
93
94 size_t size = 0;
95 size_t chunks = data_->chunks.size();
96 for (size_t i = 0; i < chunks; i++)
97 size += data_->chunks[i].data.size();
98 data_size_ = size;
99
100 viewport()->update();
101}
102
103unsigned int QHexView::get_bytes_per_line() const
104{
105 return BYTES_PER_LINE;
106}
107
108void QHexView::clear()
109{
110 verticalScrollBar()->setValue(0);
111 data_ = nullptr;
112 data_size_ = 0;
113
114 viewport()->update();
115}
116
117void QHexView::showFromOffset(size_t offset)
118{
119 if (data_ && (offset < data_size_)) {
120 setCursorPos(offset * 2);
121
122 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
123 verticalScrollBar() -> setValue(cursorY);
124 }
125
126 viewport()->update();
127}
128
129QSizePolicy QHexView::sizePolicy() const
130{
131 return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
132}
133
134pair<size_t, size_t> QHexView::get_selection() const
135{
136 size_t start = selectBegin_ / 2;
137 size_t end = selectEnd_ / 2;
138
139 if (start == end) {
140 // Nothing is currently selected
141 start = 0;
142 end = data_size_;
143 } else
144 end++;
145
146 return std::make_pair(start, end);
147}
148
149size_t QHexView::create_hex_line(size_t start, size_t end, QString* dest,
150 bool with_offset, bool with_ascii)
151{
152 dest->clear();
153
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);
158
159 if (with_offset)
160 dest->append(QString("%1 ").arg(row * BYTES_PER_LINE, 10, 16, QChar('0')).toUpper());
161
162 initialize_byte_iterator(offset);
163 for (size_t i = offset; i < offset + BYTES_PER_LINE; i++) {
164 uint8_t value = 0;
165
166 if (i < end)
167 value = get_next_byte();
168
169 if ((i < start) || (i >= end))
170 dest->append(" ");
171 else
172 dest->append(QString("%1 ").arg(value, 2, 16, QChar('0')).toUpper());
173 }
174
175 if (with_ascii) {
176 initialize_byte_iterator(offset);
177 for (size_t i = offset; i < end; i++) {
178 uint8_t value = get_next_byte();
179
180 if (i < start)
181 dest->append(' ');
182 else
183 dest->append((char)value);
184 }
185 }
186
187 return end;
188}
189
190void QHexView::initialize_byte_iterator(size_t offset)
191{
192 current_chunk_id_ = 0;
193 current_chunk_offset_ = 0;
194 current_offset_ = offset;
195
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();
199
200 if (offset >= size) {
201 current_chunk_id_++;
202 offset -= size;
203 } else {
204 current_chunk_offset_ = offset;
205 break;
206 }
207 }
208
209 if (current_chunk_id_ < data_->chunks.size())
210 current_chunk_ = data_->chunks[current_chunk_id_];
211}
212
213uint8_t QHexView::get_next_byte(bool* is_next_chunk)
214{
215 if (is_next_chunk != nullptr)
216 *is_next_chunk = (current_chunk_offset_ == 0);
217
218 uint8_t v = 0;
219 if (current_chunk_offset_ < current_chunk_.data.size())
220 v = current_chunk_.data[current_chunk_offset_];
221
222 current_offset_++;
223 current_chunk_offset_++;
224
225 if (current_offset_ > data_size_) {
226 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
227 current_offset_ << "of" << data_size_ << "bytes";
228 return 0xEE;
229 }
230
231 if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
232 current_chunk_id_++;
233 current_chunk_offset_ = 0;
234 current_chunk_ = data_->chunks[current_chunk_id_];
235 }
236
237 return v;
238}
239
240QSize QHexView::getFullSize() const
241{
242 size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
243
244 if (verticalScrollBar()->isEnabled())
245 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
246
247 if (!data_ || (data_size_ == 0))
248 return QSize(width, 0);
249
250 size_t height = data_size_ / BYTES_PER_LINE;
251
252 if (data_size_ % BYTES_PER_LINE)
253 height++;
254
255 height *= charHeight_;
256
257 return QSize(width, height);
258}
259
260void QHexView::paintEvent(QPaintEvent *event)
261{
262 QPainter painter(viewport());
263
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();
269
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);
275 } else
276 verticalScrollBar()->setEnabled(false);
277
278 // Fill widget background
279 painter.fillRect(event->rect(), palette().color(QPalette::Base));
280
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);
287 return;
288 }
289
290 // Determine first/last line indices
291 size_t firstLineIdx = verticalScrollBar()->value();
292
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)
297 lastLineIdx++;
298 }
299
300 // Fill address area background
301 painter.fillRect(QRect(posAddr_, event->rect().top(),
302 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
303
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());
308
309 // Paint address area
310 painter.setPen(palette().color(QPalette::ButtonText));
311
312 int yStart = charHeight_;
313 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
314
315 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
316 painter.drawText(posAddr_, y, address);
317 y += charHeight_;
318 }
319
320 // Paint hex values
321 QBrush regular = palette().buttonText();
322 QBrush selected = palette().highlight();
323
324 bool multiple_chunks = (data_->chunks.size() > 1);
325 unsigned int chunk_color = 0;
326
327 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
328 yStart = charHeight_;
329 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
330
331 int x = posHex_;
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;
334
335 // Fetch byte
336 bool is_next_chunk;
337 uint8_t byte_value = get_next_byte(&is_next_chunk);
338
339 if (is_next_chunk) {
340 chunk_color++;
341 if (chunk_color == chunk_colors_.size())
342 chunk_color = 0;
343 }
344
345 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
346 painter.setBackgroundMode(Qt::OpaqueMode);
347 painter.setBackground(selected);
348 painter.setPen(palette().color(QPalette::HighlightedText));
349 } else {
350 painter.setBackground(regular);
351 painter.setBackgroundMode(Qt::TransparentMode);
352 if (!multiple_chunks)
353 painter.setPen(palette().color(QPalette::Text));
354 else
355 painter.setPen(chunk_colors_[chunk_color]);
356 }
357
358 // First nibble
359 QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
360 painter.drawText(x, y, val);
361
362 // Second nibble
363 val = QString::number((byte_value & 0xF), 16).toUpper();
364 painter.drawText(x + charWidth_, y, val);
365
366 x += 3 * charWidth_;
367 }
368
369 y += charHeight_;
370 }
371
372 // Paint ASCII characters
373 initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
374 yStart = charHeight_;
375 for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
376
377 int x = posAscii_;
378 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
379 // Fetch byte
380 uint8_t ch = get_next_byte();
381
382 if ((ch < 0x20) || (ch > 0x7E))
383 ch = '.';
384
385 size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
386 if ((pos >= selectBegin_) && (pos < selectEnd_)) {
387 painter.setBackgroundMode(Qt::OpaqueMode);
388 painter.setBackground(selected);
389 painter.setPen(palette().color(QPalette::HighlightedText));
390 } else {
391 painter.setBackgroundMode(Qt::TransparentMode);
392 painter.setBackground(regular);
393 painter.setPen(palette().color(QPalette::Text));
394 }
395
396 painter.drawText(x, y, QString(ch));
397 x += charWidth_;
398 }
399
400 y += charHeight_;
401 }
402
403 // Paint cursor
404 if (hasFocus()) {
405 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
406 int y = cursorPos_ / (2 * BYTES_PER_LINE);
407 y -= firstLineIdx;
408 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
409 int cursorY = y * charHeight_ + 4;
410 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
411 }
412}
413
414void QHexView::keyPressEvent(QKeyEvent *event)
415{
416 bool setVisible = false;
417
418 // Cursor movements
419 if (event->matches(QKeySequence::MoveToNextChar)) {
420 setCursorPos(cursorPos_ + 1);
421 resetSelection(cursorPos_);
422 setVisible = true;
423 }
424 if (event->matches(QKeySequence::MoveToPreviousChar)) {
425 setCursorPos(cursorPos_ - 1);
426 resetSelection(cursorPos_);
427 setVisible = true;
428 }
429
430 if (event->matches(QKeySequence::MoveToEndOfLine)) {
431 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
432 resetSelection(cursorPos_);
433 setVisible = true;
434 }
435 if (event->matches(QKeySequence::MoveToStartOfLine)) {
436 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
437 resetSelection(cursorPos_);
438 setVisible = true;
439 }
440 if (event->matches(QKeySequence::MoveToPreviousLine)) {
441 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
442 resetSelection(cursorPos_);
443 setVisible = true;
444 }
445 if (event->matches(QKeySequence::MoveToNextLine)) {
446 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
447 resetSelection(cursorPos_);
448 setVisible = true;
449 }
450
451 if (event->matches(QKeySequence::MoveToNextPage)) {
452 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
453 resetSelection(cursorPos_);
454 setVisible = true;
455 }
456 if (event->matches(QKeySequence::MoveToPreviousPage)) {
457 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
458 resetSelection(cursorPos_);
459 setVisible = true;
460 }
461 if (event->matches(QKeySequence::MoveToEndOfDocument)) {
462 setCursorPos(data_size_ * 2);
463 resetSelection(cursorPos_);
464 setVisible = true;
465 }
466 if (event->matches(QKeySequence::MoveToStartOfDocument)) {
467 setCursorPos(0);
468 resetSelection(cursorPos_);
469 setVisible = true;
470 }
471
472 // Select commands
473 if (event->matches(QKeySequence::SelectAll)) {
474 resetSelection(0);
475 setSelection(2 * data_size_);
476 setVisible = true;
477 }
478 if (event->matches(QKeySequence::SelectNextChar)) {
479 int pos = cursorPos_ + 1;
480 setCursorPos(pos);
481 setSelection(pos);
482 setVisible = true;
483 }
484 if (event->matches(QKeySequence::SelectPreviousChar)) {
485 int pos = cursorPos_ - 1;
486 setSelection(pos);
487 setCursorPos(pos);
488 setVisible = true;
489 }
490 if (event->matches(QKeySequence::SelectEndOfLine)) {
491 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
492 setCursorPos(pos);
493 setSelection(pos);
494 setVisible = true;
495 }
496 if (event->matches(QKeySequence::SelectStartOfLine)) {
497 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
498 setCursorPos(pos);
499 setSelection(pos);
500 setVisible = true;
501 }
502 if (event->matches(QKeySequence::SelectPreviousLine)) {
503 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
504 setCursorPos(pos);
505 setSelection(pos);
506 setVisible = true;
507 }
508 if (event->matches(QKeySequence::SelectNextLine)) {
509 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
510 setCursorPos(pos);
511 setSelection(pos);
512 setVisible = true;
513 }
514
515 if (event->matches(QKeySequence::SelectNextPage)) {
516 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
517 setCursorPos(pos);
518 setSelection(pos);
519 setVisible = true;
520 }
521 if (event->matches(QKeySequence::SelectPreviousPage)) {
522 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
523 setCursorPos(pos);
524 setSelection(pos);
525 setVisible = true;
526 }
527 if (event->matches(QKeySequence::SelectEndOfDocument)) {
528 int pos = data_size_ * 2;
529 setCursorPos(pos);
530 setSelection(pos);
531 setVisible = true;
532 }
533 if (event->matches(QKeySequence::SelectStartOfDocument)) {
534 setCursorPos(0);
535 setSelection(0);
536 setVisible = true;
537 }
538
539 if (event->matches(QKeySequence::Copy) && (data_)) {
540 QString text;
541
542 initialize_byte_iterator(selectBegin_ / 2);
543
544 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
545 for (size_t i = 0; i < selectedSize; i++) {
546 uint8_t byte_value = get_next_byte();
547
548 QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
549 QString::number((byte_value & 0xF), 16).toUpper() + " ";
550 text += s;
551
552 if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
553 text += "\n";
554 }
555
556 QClipboard *clipboard = QApplication::clipboard();
557 clipboard->setText(text, QClipboard::Clipboard);
558 if (clipboard->supportsSelection())
559 clipboard->setText(text, QClipboard::Selection);
560 }
561
562 if (setVisible)
563 ensureVisible();
564
565 viewport()->update();
566}
567
568void QHexView::mouseMoveEvent(QMouseEvent *event)
569{
570 int actPos = cursorPosFromMousePos(event->pos());
571 setCursorPos(actPos);
572 setSelection(actPos);
573
574 viewport()->update();
575}
576
577void QHexView::mousePressEvent(QMouseEvent *event)
578{
579 int cPos = cursorPosFromMousePos(event->pos());
580
581 if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
582 setSelection(cPos);
583 else
584 resetSelection(cPos);
585
586 setCursorPos(cPos);
587
588 viewport()->update();
589}
590
591size_t QHexView::cursorPosFromMousePos(const QPoint &position)
592{
593 size_t pos = -1;
594
595 if (((size_t)position.x() >= posHex_) &&
596 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
597
598 // Note: We add 1.5 character widths so that selection across
599 // byte gaps is smoother
600 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
601
602 // Note: We allow only full bytes to be selected, not nibbles,
603 // so we round to the nearest byte gap
604 x = (2 * x + 1) / 3;
605
606 size_t firstLineIdx = verticalScrollBar()->value();
607 size_t y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
608 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
609 }
610
611 size_t max_pos = data_size_ * 2;
612
613 return std::min(pos, max_pos);
614}
615
616void QHexView::resetSelection()
617{
618 selectBegin_ = selectInit_;
619 selectEnd_ = selectInit_;
620}
621
622void QHexView::resetSelection(int pos)
623{
624 if (pos < 0)
625 pos = 0;
626
627 selectInit_ = pos;
628 selectBegin_ = pos;
629 selectEnd_ = pos;
630}
631
632void QHexView::setSelection(int pos)
633{
634 if (pos < 0)
635 pos = 0;
636
637 if ((size_t)pos >= selectInit_) {
638 selectEnd_ = pos;
639 selectBegin_ = selectInit_;
640 } else {
641 selectBegin_ = pos;
642 selectEnd_ = selectInit_;
643 }
644}
645
646void QHexView::setCursorPos(int position)
647{
648 if (position < 0)
649 position = 0;
650
651 int max_pos = data_size_ * 2;
652
653 if (position > max_pos)
654 position = max_pos;
655
656 cursorPos_ = position;
657}
658
659void QHexView::ensureVisible()
660{
661 QSize areaSize = viewport()->size();
662
663 int firstLineIdx = verticalScrollBar()->value();
664 int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
665
666 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
667
668 if (cursorY < firstLineIdx)
669 verticalScrollBar()->setValue(cursorY);
670 else
671 if(cursorY >= lastLineIdx)
672 verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);
673}