]> sigrok.org Git - pulseview.git/blob - pv/views/decoder_output/QHexView.cpp
QHexView: Improve vertical slider handling
[pulseview.git] / pv / views / decoder_output / QHexView.cpp
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
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;
47
48
49 QHexView::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
82 void QHexView::setMode(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
90 void QHexView::setData(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
103 void QHexView::clear()
104 {
105         verticalScrollBar()->setValue(0);
106         data_ = nullptr;
107         data_size_ = 0;
108
109         viewport()->update();
110 }
111
112 void QHexView::showFromOffset(size_t offset)
113 {
114         if (data_ && (offset < data_size_)) {
115                 setCursorPos(offset * 2);
116
117                 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
118                 verticalScrollBar() -> setValue(cursorY);
119         }
120
121         viewport()->update();
122 }
123
124 void QHexView::initialize_byte_iterator(size_t offset)
125 {
126         current_chunk_id_ = 0;
127         current_chunk_offset_ = 0;
128         current_offset_ = offset;
129
130         size_t chunks = data_->chunks.size();
131         for (size_t i = 0; i < chunks; i++) {
132                 size_t size = data_->chunks[i].data.size();
133
134                 if (offset >= size) {
135                         current_chunk_id_++;
136                         offset -= size;
137                 } else {
138                         current_chunk_offset_ = offset;
139                         break;
140                 }
141         }
142
143         if (current_chunk_id_ < data_->chunks.size())
144                 current_chunk_ = data_->chunks[current_chunk_id_];
145 }
146
147 uint8_t QHexView::get_next_byte(bool* is_next_chunk)
148 {
149         if (is_next_chunk != nullptr)
150                 *is_next_chunk = (current_chunk_offset_ == 0);
151
152         uint8_t v = 0;
153         if (current_chunk_offset_ < current_chunk_.data.size())
154                 v = current_chunk_.data[current_chunk_offset_];
155
156         current_offset_++;
157         current_chunk_offset_++;
158
159         if (current_offset_ > data_size_) {
160                 qWarning() << "QHexView::get_next_byte() overran binary data boundary:" <<
161                         current_offset_ << "of" << data_size_ << "bytes";
162                 return 0xEE;
163         }
164
165         if ((current_chunk_offset_ == current_chunk_.data.size()) && (current_offset_ < data_size_)) {
166                 current_chunk_id_++;
167                 current_chunk_offset_ = 0;
168                 current_chunk_ = data_->chunks[current_chunk_id_];
169         }
170
171         return v;
172 }
173
174 QSize QHexView::getFullSize() const
175 {
176         size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_);
177
178         if (verticalScrollBar()->isEnabled())
179                 width += GAP_ASCII_SLIDER + verticalScrollBar()->width();
180
181         if (!data_ || (data_size_ == 0))
182                 return QSize(width, 0);
183
184         size_t height = data_size_ / BYTES_PER_LINE;
185
186         if (data_size_ % BYTES_PER_LINE)
187                 height++;
188
189         height *= charHeight_;
190
191         return QSize(width, height);
192 }
193
194 void QHexView::paintEvent(QPaintEvent *event)
195 {
196         QPainter painter(viewport());
197
198         // Calculate and update the widget and paint area sizes
199         QSize widgetSize = getFullSize();
200         setMinimumWidth(widgetSize.width());
201         setMaximumWidth(widgetSize.width());
202         QSize areaSize = viewport()->size();
203
204         // Only show scrollbar if the content goes beyond the visible area
205         if (widgetSize.height() > areaSize.height()) {
206                 verticalScrollBar()->setEnabled(true);
207                 verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
208                 verticalScrollBar()->setRange(0, ((widgetSize.height() - areaSize.height())) / charHeight_ + 1);
209         } else
210                 verticalScrollBar()->setEnabled(false);
211
212         // Fill widget background
213         painter.fillRect(event->rect(), palette().color(QPalette::Base));
214
215         if (!data_ || (data_size_ == 0)) {
216                 painter.setPen(palette().color(QPalette::Text));
217                 QString s = tr("No data available");
218                 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
219                 int y = areaSize.height() / 2;
220                 painter.drawText(x, y, s);
221                 return;
222         }
223
224         // Determine first/last line indices
225         size_t firstLineIdx = verticalScrollBar()->value();
226
227         size_t lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
228         if (lastLineIdx > (data_size_ / BYTES_PER_LINE)) {
229                 lastLineIdx = data_size_ / BYTES_PER_LINE;
230                 if (data_size_ % BYTES_PER_LINE)
231                         lastLineIdx++;
232         }
233
234         // Fill address area background
235         painter.fillRect(QRect(posAddr_, event->rect().top(),
236                 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
237
238         // Paint divider line between hex and ASCII areas
239         int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
240         painter.setPen(palette().color(QPalette::Midlight));
241         painter.drawLine(line_x, event->rect().top(), line_x, height());
242
243         // Paint address area
244         painter.setPen(palette().color(QPalette::ButtonText));
245
246         int yStart = charHeight_;
247         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
248
249                 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
250                 painter.drawText(posAddr_, y, address);
251                 y += charHeight_;
252         }
253
254         // Paint hex values
255         QBrush regular = palette().buttonText();
256         QBrush selected = palette().highlight();
257
258         bool multiple_chunks = (data_->chunks.size() > 1);
259         unsigned int chunk_color = 0;
260
261         initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
262         yStart = charHeight_;
263         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
264
265                 int x = posHex_;
266                 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
267                         size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
268
269                         // Fetch byte
270                         bool is_next_chunk;
271                         uint8_t byte_value = get_next_byte(&is_next_chunk);
272
273                         if (is_next_chunk) {
274                                 chunk_color++;
275                                 if (chunk_color == chunk_colors_.size())
276                                         chunk_color = 0;
277                         }
278
279                         if ((pos >= selectBegin_) && (pos < selectEnd_)) {
280                                 painter.setBackgroundMode(Qt::OpaqueMode);
281                                 painter.setBackground(selected);
282                                 painter.setPen(palette().color(QPalette::HighlightedText));
283                         } else {
284                                 painter.setBackground(regular);
285                                 painter.setBackgroundMode(Qt::TransparentMode);
286                                 if (!multiple_chunks)
287                                         painter.setPen(palette().color(QPalette::Text));
288                                 else
289                                         painter.setPen(chunk_colors_[chunk_color]);
290                         }
291
292                         // First nibble
293                         QString val = QString::number((byte_value & 0xF0) >> 4, 16).toUpper();
294                         painter.drawText(x, y, val);
295
296                         // Second nibble
297                         val = QString::number((byte_value & 0xF), 16).toUpper();
298                         painter.drawText(x + charWidth_, y, val);
299
300                         x += 3 * charWidth_;
301                 }
302
303                 y += charHeight_;
304         }
305
306         // Paint ASCII characters
307         initialize_byte_iterator(firstLineIdx * BYTES_PER_LINE);
308         yStart = charHeight_;
309         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
310
311                 int x = posAscii_;
312                 for (size_t i = 0; (i < BYTES_PER_LINE) && (current_offset_ < data_size_); i++) {
313                         // Fetch byte
314                         uint8_t ch = get_next_byte();
315
316                         if ((ch < 0x20) || (ch > 0x7E))
317                                 ch = '.';
318
319                         size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
320                         if ((pos >= selectBegin_) && (pos < selectEnd_)) {
321                                 painter.setBackgroundMode(Qt::OpaqueMode);
322                                 painter.setBackground(selected);
323                                 painter.setPen(palette().color(QPalette::HighlightedText));
324                         } else {
325                                 painter.setBackgroundMode(Qt::TransparentMode);
326                                 painter.setBackground(regular);
327                                 painter.setPen(palette().color(QPalette::Text));
328                         }
329
330                         painter.drawText(x, y, QString(ch));
331                         x += charWidth_;
332                 }
333
334                 y += charHeight_;
335         }
336
337         // Paint cursor
338         if (hasFocus()) {
339                 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
340                 int y = cursorPos_ / (2 * BYTES_PER_LINE);
341                 y -= firstLineIdx;
342                 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
343                 int cursorY = y * charHeight_ + 4;
344                 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
345         }
346 }
347
348 void QHexView::keyPressEvent(QKeyEvent *event)
349 {
350         bool setVisible = false;
351
352         // Cursor movements
353         if (event->matches(QKeySequence::MoveToNextChar)) {
354                 setCursorPos(cursorPos_ + 1);
355                 resetSelection(cursorPos_);
356                 setVisible = true;
357         }
358         if (event->matches(QKeySequence::MoveToPreviousChar)) {
359                 setCursorPos(cursorPos_ - 1);
360                 resetSelection(cursorPos_);
361                 setVisible = true;
362         }
363
364         if (event->matches(QKeySequence::MoveToEndOfLine)) {
365                 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
366                 resetSelection(cursorPos_);
367                 setVisible = true;
368         }
369         if (event->matches(QKeySequence::MoveToStartOfLine)) {
370                 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
371                 resetSelection(cursorPos_);
372                 setVisible = true;
373         }
374         if (event->matches(QKeySequence::MoveToPreviousLine)) {
375                 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
376                 resetSelection(cursorPos_);
377                 setVisible = true;
378         }
379         if (event->matches(QKeySequence::MoveToNextLine)) {
380                 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
381                 resetSelection(cursorPos_);
382                 setVisible = true;
383         }
384
385         if (event->matches(QKeySequence::MoveToNextPage)) {
386                 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
387                 resetSelection(cursorPos_);
388                 setVisible = true;
389         }
390         if (event->matches(QKeySequence::MoveToPreviousPage)) {
391                 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
392                 resetSelection(cursorPos_);
393                 setVisible = true;
394         }
395         if (event->matches(QKeySequence::MoveToEndOfDocument)) {
396                 setCursorPos(data_size_ * 2);
397                 resetSelection(cursorPos_);
398                 setVisible = true;
399         }
400         if (event->matches(QKeySequence::MoveToStartOfDocument)) {
401                 setCursorPos(0);
402                 resetSelection(cursorPos_);
403                 setVisible = true;
404         }
405
406         // Select commands
407         if (event->matches(QKeySequence::SelectAll)) {
408                 resetSelection(0);
409                 setSelection(2 * data_size_);
410                 setVisible = true;
411         }
412         if (event->matches(QKeySequence::SelectNextChar)) {
413                 int pos = cursorPos_ + 1;
414                 setCursorPos(pos);
415                 setSelection(pos);
416                 setVisible = true;
417         }
418         if (event->matches(QKeySequence::SelectPreviousChar)) {
419                 int pos = cursorPos_ - 1;
420                 setSelection(pos);
421                 setCursorPos(pos);
422                 setVisible = true;
423         }
424         if (event->matches(QKeySequence::SelectEndOfLine)) {
425                 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
426                 setCursorPos(pos);
427                 setSelection(pos);
428                 setVisible = true;
429         }
430         if (event->matches(QKeySequence::SelectStartOfLine)) {
431                 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
432                 setCursorPos(pos);
433                 setSelection(pos);
434                 setVisible = true;
435         }
436         if (event->matches(QKeySequence::SelectPreviousLine)) {
437                 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
438                 setCursorPos(pos);
439                 setSelection(pos);
440                 setVisible = true;
441         }
442         if (event->matches(QKeySequence::SelectNextLine)) {
443                 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
444                 setCursorPos(pos);
445                 setSelection(pos);
446                 setVisible = true;
447         }
448
449         if (event->matches(QKeySequence::SelectNextPage)) {
450                 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
451                 setCursorPos(pos);
452                 setSelection(pos);
453                 setVisible = true;
454         }
455         if (event->matches(QKeySequence::SelectPreviousPage)) {
456                 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
457                 setCursorPos(pos);
458                 setSelection(pos);
459                 setVisible = true;
460         }
461         if (event->matches(QKeySequence::SelectEndOfDocument)) {
462                 int pos = data_size_ * 2;
463                 setCursorPos(pos);
464                 setSelection(pos);
465                 setVisible = true;
466         }
467         if (event->matches(QKeySequence::SelectStartOfDocument)) {
468                 setCursorPos(0);
469                 setSelection(0);
470                 setVisible = true;
471         }
472
473         if (event->matches(QKeySequence::Copy) && (data_)) {
474                 QString text;
475
476                 initialize_byte_iterator(selectBegin_ / 2);
477
478                 size_t selectedSize = (selectEnd_ - selectBegin_ + 1) / 2;
479                 for (size_t i = 0; i < selectedSize; i++) {
480                         uint8_t byte_value = get_next_byte();
481
482                         QString s = QString::number((byte_value & 0xF0) >> 4, 16).toUpper() +
483                                 QString::number((byte_value & 0xF), 16).toUpper() + " ";
484                         text += s;
485
486                         if (i % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
487                                 text += "\n";
488                 }
489
490                 QClipboard *clipboard = QApplication::clipboard();
491                 clipboard->setText(text, QClipboard::Clipboard);
492                 if (clipboard->supportsSelection())
493                         clipboard->setText(text, QClipboard::Selection);
494         }
495
496         if (setVisible)
497                 ensureVisible();
498
499         viewport()->update();
500 }
501
502 void QHexView::mouseMoveEvent(QMouseEvent *event)
503 {
504         int actPos = cursorPosFromMousePos(event->pos());
505         setCursorPos(actPos);
506         setSelection(actPos);
507
508         viewport()->update();
509 }
510
511 void QHexView::mousePressEvent(QMouseEvent *event)
512 {
513         int cPos = cursorPosFromMousePos(event->pos());
514
515         if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
516                 setSelection(cPos);
517         else
518                 resetSelection(cPos);
519
520         setCursorPos(cPos);
521
522         viewport()->update();
523 }
524
525 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
526 {
527         size_t pos = -1;
528
529         if (((size_t)position.x() >= posHex_) &&
530                 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
531
532                 // Note: We add 1.5 character widths so that selection across
533                 // byte gaps is smoother
534                 size_t x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
535
536                 // Note: We allow only full bytes to be selected, not nibbles,
537                 // so we round to the nearest byte gap
538                 x = (2 * x + 1) / 3;
539
540                 size_t firstLineIdx = verticalScrollBar()->value();
541                 size_t y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
542                 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
543         }
544
545         size_t max_pos = data_size_ * 2;
546
547         return std::min(pos, max_pos);
548 }
549
550 void QHexView::resetSelection()
551 {
552         selectBegin_ = selectInit_;
553         selectEnd_ = selectInit_;
554 }
555
556 void QHexView::resetSelection(int pos)
557 {
558         if (pos < 0)
559                 pos = 0;
560
561         selectInit_ = pos;
562         selectBegin_ = pos;
563         selectEnd_ = pos;
564 }
565
566 void QHexView::setSelection(int pos)
567 {
568         if (pos < 0)
569                 pos = 0;
570
571         if ((size_t)pos >= selectInit_) {
572                 selectEnd_ = pos;
573                 selectBegin_ = selectInit_;
574         } else {
575                 selectBegin_ = pos;
576                 selectEnd_ = selectInit_;
577         }
578 }
579
580 void QHexView::setCursorPos(int position)
581 {
582         if (position < 0)
583                 position = 0;
584
585         int max_pos = data_size_ * 2;
586
587         if (position > max_pos)
588                 position = max_pos;
589
590         cursorPos_ = position;
591 }
592
593 void QHexView::ensureVisible()
594 {
595         QSize areaSize = viewport()->size();
596
597         int firstLineIdx = verticalScrollBar()->value();
598         int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
599
600         int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
601
602         if (cursorY < firstLineIdx)
603                 verticalScrollBar()->setValue(cursorY);
604         else
605                 if(cursorY >= lastLineIdx)
606                         verticalScrollBar()->setValue(cursorY - areaSize.height() / charHeight_ + 1);
607 }