]> sigrok.org Git - pulseview.git/blob - pv/views/decoder_output/QHexView.cpp
53120ce07b75a6cdc296cd6a88e9e87510bdd8fd
[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 <QFont>
33 #include <QKeyEvent>
34 #include <QScrollBar>
35 #include <QSize>
36 #include <QPainter>
37 #include <QPaintEvent>
38
39 #include "QHexView.hpp"
40
41 const unsigned int BYTES_PER_LINE   = 16;
42 const unsigned int HEXCHARS_IN_LINE = BYTES_PER_LINE * 3 - 1;
43 const unsigned int GAP_ADR_HEX      = 10;
44 const unsigned int GAP_HEX_ASCII    = 10;
45 const unsigned int GAP_ASCII_SLIDER = 5;
46
47
48 QHexView::QHexView(QWidget *parent):
49         QAbstractScrollArea(parent),
50         data_(nullptr)
51 {
52         setFont(QFont("Courier", 10));
53
54         charWidth_ = fontMetrics().boundingRect('X').width();
55         charHeight_ = fontMetrics().height();
56
57         // Determine X coordinates of the three sub-areas
58         posAddr_  = 0;
59         posHex_   = 10 * charWidth_ + GAP_ADR_HEX;
60         posAscii_ = posHex_ + HEXCHARS_IN_LINE * charWidth_ + GAP_HEX_ASCII;
61
62         setFocusPolicy(Qt::StrongFocus);
63 }
64
65 void QHexView::setData(QByteArray *data)
66 {
67         verticalScrollBar()->setValue(0);
68
69         data_ = data;
70         cursorPos_ = 0;
71         resetSelection(0);
72 }
73
74 void QHexView::showFromOffset(size_t offset)
75 {
76         if (data_ && (offset < (size_t)data_->count())) {
77                 setCursorPos(offset * 2);
78
79                 int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
80                 verticalScrollBar() -> setValue(cursorY);
81         }
82
83         viewport()->update();
84 }
85
86 void QHexView::clear()
87 {
88         verticalScrollBar()->setValue(0);
89         data_ = nullptr;
90
91         viewport()->update();
92 }
93
94 QSize QHexView::getFullSize() const
95 {
96         size_t width = posAscii_ + (BYTES_PER_LINE * charWidth_) +
97                 GAP_ASCII_SLIDER + verticalScrollBar()->width();
98
99         if (!data_)
100                 return QSize(width, 0);
101
102         size_t height = data_->count() / BYTES_PER_LINE;
103
104         if (data_->count() % BYTES_PER_LINE)
105                 height++;
106
107         height *= charHeight_;
108
109         return QSize(width, height);
110 }
111
112 void QHexView::paintEvent(QPaintEvent *event)
113 {
114         QPainter painter(viewport());
115
116         // Calculate and update the widget and paint area sizes
117         QSize widgetSize = getFullSize();
118         setMinimumWidth(widgetSize.width());
119         setMaximumWidth(widgetSize.width());
120         QSize areaSize = viewport()->size();
121
122         verticalScrollBar()->setPageStep(areaSize.height() / charHeight_);
123         verticalScrollBar()->setRange(0, (widgetSize.height() - areaSize.height()) / charHeight_ + 1);
124
125         // Fill widget background
126         painter.fillRect(event->rect(), palette().color(QPalette::Base));
127
128         if (!data_ || (data_->size() == 0)) {
129                 painter.setPen(palette().color(QPalette::Text));
130                 QString s = tr("No data available");
131                 int x = (areaSize.width() - fontMetrics().boundingRect(s).width()) / 2;
132                 int y = areaSize.height() / 2;
133                 painter.drawText(x, y, s);
134                 return;
135         }
136
137         // Determine first/last line indices
138         size_t firstLineIdx = verticalScrollBar()->value();
139
140         size_t lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
141         if (lastLineIdx > (data_->count() / BYTES_PER_LINE)) {
142                 lastLineIdx = data_->count() / BYTES_PER_LINE;
143                 if (data_->count() % BYTES_PER_LINE)
144                         lastLineIdx++;
145         }
146
147         // Fill address area background
148         painter.fillRect(QRect(posAddr_, event->rect().top(),
149                 posHex_ - (GAP_ADR_HEX / 2), height()), palette().color(QPalette::Window));
150
151         // Paint divider line between hex and ASCII areas
152         int line_x = posAscii_ - (GAP_HEX_ASCII / 2);
153         painter.setPen(palette().color(QPalette::Midlight));
154         painter.drawLine(line_x, event->rect().top(), line_x, height());
155
156         // Paint address area
157         painter.setPen(palette().color(QPalette::ButtonText));
158
159         int yStart = charHeight_;
160         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
161
162                 QString address = QString("%1").arg(lineIdx * 16, 10, 16, QChar('0')).toUpper();
163                 painter.drawText(posAddr_, y, address);
164                 y += charHeight_;
165         }
166
167         // Paint hex values
168         QBrush regular = painter.brush();
169         QBrush selected = QBrush(palette().color(QPalette::Highlight));
170         QByteArray data = data_->mid(firstLineIdx * BYTES_PER_LINE,
171                 (lastLineIdx - firstLineIdx) * BYTES_PER_LINE);
172
173         yStart = charHeight_;
174         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
175
176                 painter.setBackgroundMode(Qt::OpaqueMode);
177
178                 int x = posHex_;
179                 for (size_t i = 0; i < BYTES_PER_LINE && ((lineIdx - firstLineIdx) * BYTES_PER_LINE + i) < (size_t)data.size(); i++) {
180                         size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
181
182                         if ((pos >= selectBegin_) && (pos < selectEnd_)) {
183                                 painter.setBackground(selected);
184                                 painter.setPen(palette().color(QPalette::HighlightedText));
185                         } else {
186                                 painter.setBackground(regular);
187                                 painter.setPen(palette().color(QPalette::Text));
188                         }
189
190                         // First nibble
191                         QString val = QString::number((data.at((lineIdx - firstLineIdx) * BYTES_PER_LINE + i) & 0xF0) >> 4, 16).toUpper();
192                         painter.drawText(x, y, val);
193
194                         // Second nibble
195                         val = QString::number((data.at((lineIdx - firstLineIdx) * BYTES_PER_LINE + i) & 0xF), 16).toUpper();
196                         painter.drawText(x + charWidth_, y, val);
197
198                         x += 3 * charWidth_;
199                 }
200
201                 y += charHeight_;
202         }
203
204         // Paint ASCII characters
205         yStart = charHeight_;
206         for (size_t lineIdx = firstLineIdx, y = yStart; lineIdx < lastLineIdx; lineIdx++) {
207
208                 int x = posAscii_;
209                 for (size_t i = 0; ((lineIdx - firstLineIdx) * BYTES_PER_LINE + i) < (size_t)data.size() && (i < BYTES_PER_LINE); i++) {
210                         char ch = data[(unsigned int)((lineIdx - firstLineIdx) * BYTES_PER_LINE + i)];
211
212                         if ((ch < 0x20) || (ch > 0x7E))
213                                 ch = '.';
214
215                         size_t pos = (lineIdx * BYTES_PER_LINE + i) * 2;
216                         if ((pos >= selectBegin_) && (pos < selectEnd_)) {
217                                 painter.setBackground(selected);
218                                 painter.setPen(palette().color(QPalette::HighlightedText));
219                         } else {
220                                 painter.setBackground(regular);
221                                 painter.setPen(palette().color(QPalette::Text));
222                         }
223
224                         painter.drawText(x, y, QString(ch));
225                         x += charWidth_;
226                 }
227
228                 y += charHeight_;
229         }
230
231         // Paint cursor
232         if (hasFocus()) {
233                 int x = (cursorPos_ % (2 * BYTES_PER_LINE));
234                 int y = cursorPos_ / (2 * BYTES_PER_LINE);
235                 y -= firstLineIdx;
236                 int cursorX = (((x / 2) * 3) + (x % 2)) * charWidth_ + posHex_;
237                 int cursorY = y * charHeight_ + 4;
238                 painter.fillRect(cursorX, cursorY, 2, charHeight_, palette().color(QPalette::WindowText));
239         }
240 }
241
242 void QHexView::keyPressEvent(QKeyEvent *event)
243 {
244         bool setVisible = false;
245
246         // Cursor movements
247         if (event->matches(QKeySequence::MoveToNextChar)) {
248                 setCursorPos(cursorPos_ + 1);
249                 resetSelection(cursorPos_);
250                 setVisible = true;
251         }
252         if (event->matches(QKeySequence::MoveToPreviousChar)) {
253                 setCursorPos(cursorPos_ - 1);
254                 resetSelection(cursorPos_);
255                 setVisible = true;
256         }
257
258         if (event->matches(QKeySequence::MoveToEndOfLine)) {
259                 setCursorPos(cursorPos_ | ((BYTES_PER_LINE * 2) - 1));
260                 resetSelection(cursorPos_);
261                 setVisible = true;
262         }
263         if (event->matches(QKeySequence::MoveToStartOfLine)) {
264                 setCursorPos(cursorPos_ | (cursorPos_ % (BYTES_PER_LINE * 2)));
265                 resetSelection(cursorPos_);
266                 setVisible = true;
267         }
268         if (event->matches(QKeySequence::MoveToPreviousLine)) {
269                 setCursorPos(cursorPos_ - BYTES_PER_LINE * 2);
270                 resetSelection(cursorPos_);
271                 setVisible = true;
272         }
273         if (event->matches(QKeySequence::MoveToNextLine)) {
274                 setCursorPos(cursorPos_ + BYTES_PER_LINE * 2);
275                 resetSelection(cursorPos_);
276                 setVisible = true;
277         }
278
279         if (event->matches(QKeySequence::MoveToNextPage)) {
280                 setCursorPos(cursorPos_ + (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
281                 resetSelection(cursorPos_);
282                 setVisible = true;
283         }
284         if (event->matches(QKeySequence::MoveToPreviousPage)) {
285                 setCursorPos(cursorPos_ - (viewport()->height() / charHeight_ - 1) * 2 * BYTES_PER_LINE);
286                 resetSelection(cursorPos_);
287                 setVisible = true;
288         }
289         if (event->matches(QKeySequence::MoveToEndOfDocument)) {
290                 if (data_)
291                         setCursorPos(data_->count() * 2);
292                 resetSelection(cursorPos_);
293                 setVisible = true;
294         }
295         if (event->matches(QKeySequence::MoveToStartOfDocument)) {
296                 setCursorPos(0);
297                 resetSelection(cursorPos_);
298                 setVisible = true;
299         }
300
301         // Select commands
302         if (event->matches(QKeySequence::SelectAll)) {
303                 resetSelection(0);
304                 if (data_)
305                         setSelection(2 * data_->count() + 1);
306                 setVisible = true;
307         }
308         if (event->matches(QKeySequence::SelectNextChar)) {
309                 int pos = cursorPos_ + 1;
310                 setCursorPos(pos);
311                 setSelection(pos);
312                 setVisible = true;
313         }
314         if (event->matches(QKeySequence::SelectPreviousChar)) {
315                 int pos = cursorPos_ - 1;
316                 setSelection(pos);
317                 setCursorPos(pos);
318                 setVisible = true;
319         }
320         if (event->matches(QKeySequence::SelectEndOfLine)) {
321                 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
322                 setCursorPos(pos);
323                 setSelection(pos);
324                 setVisible = true;
325         }
326         if (event->matches(QKeySequence::SelectStartOfLine)) {
327                 int pos = cursorPos_ - (cursorPos_ % (2 * BYTES_PER_LINE));
328                 setCursorPos(pos);
329                 setSelection(pos);
330                 setVisible = true;
331         }
332         if (event->matches(QKeySequence::SelectPreviousLine)) {
333                 int pos = cursorPos_ - (2 * BYTES_PER_LINE);
334                 setCursorPos(pos);
335                 setSelection(pos);
336                 setVisible = true;
337         }
338         if (event->matches(QKeySequence::SelectNextLine)) {
339                 int pos = cursorPos_ + (2 * BYTES_PER_LINE);
340                 setCursorPos(pos);
341                 setSelection(pos);
342                 setVisible = true;
343         }
344
345         if (event->matches(QKeySequence::SelectNextPage)) {
346                 int pos = cursorPos_ + (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
347                 setCursorPos(pos);
348                 setSelection(pos);
349                 setVisible = true;
350         }
351         if (event->matches(QKeySequence::SelectPreviousPage)) {
352                 int pos = cursorPos_ - (((viewport()->height() / charHeight_) - 1) * 2 * BYTES_PER_LINE);
353                 setCursorPos(pos);
354                 setSelection(pos);
355                 setVisible = true;
356         }
357         if (event->matches(QKeySequence::SelectEndOfDocument)) {
358                 int pos = 0;
359                 if (data_)
360                         pos = data_->count() * 2;
361                 setCursorPos(pos);
362                 setSelection(pos);
363                 setVisible = true;
364         }
365         if (event->matches(QKeySequence::SelectStartOfDocument)) {
366                 int pos = 0;
367                 setCursorPos(pos);
368                 setSelection(pos);
369                 setVisible = true;
370         }
371
372         if (event->matches(QKeySequence::Copy) && (data_)) {
373                 QString text;
374                 int idx = 0;
375                 int copyOffset = 0;
376
377                 QByteArray data = data_->mid(selectBegin_ / 2, (selectEnd_ - selectBegin_) / 2 + 1);
378                 if (selectBegin_ % 2) {
379                         text += QString::number((data.at((idx+1) / 2) & 0xF), 16);
380                         text += " ";
381                         idx++;
382                         copyOffset = 1;
383                 }
384
385                 int selectedSize = selectEnd_ - selectBegin_;
386                 while (idx < selectedSize) {
387                         QString val = QString::number((data.at((copyOffset + idx) / 2) & 0xF0) >> 4, 16);
388                         if ((idx + 1) < selectedSize) {
389                                 val += QString::number((data.at((copyOffset + idx) / 2) & 0xF), 16);
390                                 val += " ";
391                         }
392                         text += val;
393
394                         if ((idx/2) % BYTES_PER_LINE == (BYTES_PER_LINE - 1))
395                                 text += "\n";
396
397                         idx += 2;
398                 }
399
400                 QClipboard *clipboard = QApplication::clipboard();
401                 clipboard->setText(text);
402                 if (clipboard->supportsSelection())
403                         clipboard->setText(text);
404         }
405
406         if (setVisible)
407                 ensureVisible();
408
409         viewport()->update();
410 }
411
412 void QHexView::mouseMoveEvent(QMouseEvent *event)
413 {
414         int actPos = cursorPosFromMousePos(event->pos());
415         setCursorPos(actPos);
416         setSelection(actPos);
417
418         viewport()->update();
419 }
420
421 void QHexView::mousePressEvent(QMouseEvent *event)
422 {
423         int cPos = cursorPosFromMousePos(event->pos());
424
425         if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) && (event->button() == Qt::LeftButton))
426                 setSelection(cPos);
427         else
428                 resetSelection(cPos);
429
430         setCursorPos(cPos);
431
432         viewport()->update();
433 }
434
435 size_t QHexView::cursorPosFromMousePos(const QPoint &position)
436 {
437         int pos = -1;
438
439         if (((size_t)position.x() >= posHex_) &&
440                 ((size_t)position.x() < (posHex_ + HEXCHARS_IN_LINE * charWidth_))) {
441
442                 // Note: We add 1.5 character widths so that selection across
443                 // byte gaps is smoother
444                 int x = (position.x() + (1.5 * charWidth_ / 2) - posHex_) / charWidth_;
445
446                 // Note: We allow only full bytes to be selected, not nibbles,
447                 // so we round to the nearest byte gap
448                 x = (2 * x + 1) / 3;
449
450                 int firstLineIdx = verticalScrollBar()->value();
451                 int y = (position.y() / charHeight_) * 2 * BYTES_PER_LINE;
452                 pos = x + y + firstLineIdx * BYTES_PER_LINE * 2;
453         }
454
455         return pos;
456 }
457
458 void QHexView::resetSelection()
459 {
460         selectBegin_ = selectInit_;
461         selectEnd_ = selectInit_;
462 }
463
464 void QHexView::resetSelection(int pos)
465 {
466         if (pos < 0)
467                 pos = 0;
468
469         selectInit_ = pos;
470         selectBegin_ = pos;
471         selectEnd_ = pos;
472 }
473
474 void QHexView::setSelection(int pos)
475 {
476         if (pos < 0)
477                 pos = 0;
478
479         if ((size_t)pos >= selectInit_) {
480                 selectEnd_ = pos;
481                 selectBegin_ = selectInit_;
482         } else {
483                 selectBegin_ = pos;
484                 selectEnd_ = selectInit_;
485         }
486 }
487
488 void QHexView::setCursorPos(int position)
489 {
490         if (position < 0)
491                 position = 0;
492
493         int maxPos = 0;
494         if (data_) {
495                 maxPos = data_->count() * 2;
496                 if (data_->count() % BYTES_PER_LINE)
497                         maxPos++;
498         }
499
500         if (position > maxPos)
501                 position = maxPos;
502
503         cursorPos_ = position;
504 }
505
506 void QHexView::ensureVisible()
507 {
508         QSize areaSize = viewport()->size();
509
510         int firstLineIdx = verticalScrollBar() -> value();
511         int lastLineIdx = firstLineIdx + areaSize.height() / charHeight_;
512
513         int cursorY = cursorPos_ / (2 * BYTES_PER_LINE);
514
515         if (cursorY < firstLineIdx)
516                 verticalScrollBar() -> setValue(cursorY);
517         else if(cursorY >= lastLineIdx)
518                 verticalScrollBar() -> setValue(cursorY - areaSize.height() / charHeight_ + 1);
519 }