bineditor.cpp 45.9 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31 32 33 34
#include "bineditor.h"

#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>

35
#include <QtCore/QByteArrayMatcher>
ck's avatar
ck committed
36 37 38
#include <QtCore/QFile>
#include <QtCore/QTemporaryFile>

39
#include <QtGui/QApplication>
40
#include <QtGui/QAction>
41
#include <QtGui/QClipboard>
con's avatar
con committed
42
#include <QtGui/QFontMetrics>
43
#include <QtGui/QHelpEvent>
44
#include <QtGui/QMenu>
45
#include <QtGui/QMessageBox>
con's avatar
con committed
46 47
#include <QtGui/QPainter>
#include <QtGui/QScrollBar>
48
#include <QtGui/QToolTip>
con's avatar
con committed
49 50 51 52
#include <QtGui/QWheelEvent>

using namespace BINEditor;

53 54 55 56 57 58 59 60 61 62 63 64
// QByteArray::toLower() is broken, it stops at the first \0
static void lower(QByteArray &ba)
{
    char *data = ba.data();
    char *end = data + ba.size();
    while (data != end) {
        if (*data >= 0x41 && *data <= 0x5A)
            *data += 0x20;
        ++data;
    }
}

con's avatar
con committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
static QByteArray calculateHexPattern(const QByteArray &pattern)
{
    QByteArray result;
    if (pattern.size() % 2 == 0) {
        bool ok = true;
        int i = 0;
        while (i < pattern.size()) {
            ushort s = pattern.mid(i, 2).toUShort(&ok, 16);
            if (!ok) {
                return QByteArray();
            }
            result.append(s);
            i += 2;
        }
    }
    return result;
}

BinEditor::BinEditor(QWidget *parent)
    : QAbstractScrollArea(parent)
{
    m_ieditor = 0;
87
    m_inLazyMode = false;
ck's avatar
ck committed
88
    m_baseAddr = 0;
89
    m_blockSize = 4096;
con's avatar
con committed
90
    m_size = 0;
91
    m_addressBytes = 4;
con's avatar
con committed
92 93
    init();
    m_unmodifiedState = 0;
94
    m_readOnly = false;
con's avatar
con committed
95 96 97 98 99
    m_hexCursor = true;
    m_cursorPosition = 0;
    m_anchorPosition = 0;
    m_lowNibble = false;
    m_cursorVisible = false;
100
    m_caseSensitiveSearch = false;
101
    m_canRequestNewWindow = false;
con's avatar
con committed
102 103 104 105 106 107 108 109 110
    setFocusPolicy(Qt::WheelFocus);
}

BinEditor::~BinEditor()
{
}

void BinEditor::init()
{
111 112 113
    const int addressStringWidth =
        2*m_addressBytes + (m_addressBytes - 1) / 2;
    m_addressString = QString(addressStringWidth, QLatin1Char(':'));
con's avatar
con committed
114 115 116 117 118 119 120
    QFontMetrics fm(fontMetrics());
    m_margin = 4;
    m_descent = fm.descent();
    m_ascent = fm.ascent();
    m_lineHeight = fm.lineSpacing();
    m_charWidth = fm.width(QChar(QLatin1Char('M')));
    m_columnWidth = 2 * m_charWidth + fm.width(QChar(QLatin1Char(' ')));
121
    m_numLines = m_size / 16 + 1;
con's avatar
con committed
122 123 124
    m_numVisibleLines = viewport()->height() / m_lineHeight;
    m_textWidth = 16 * m_charWidth + m_charWidth;
    int m_numberWidth = fm.width(QChar(QLatin1Char('9')));
125 126
    m_labelWidth =
        2*m_addressBytes * m_numberWidth + (m_addressBytes - 1)/2 * m_charWidth;
con's avatar
con committed
127 128 129 130 131 132 133 134 135 136 137 138

    int expectedCharWidth = m_columnWidth / 3;
    const char *hex = "0123456789abcdef";
    m_isMonospacedFont = true;
    while (*hex) {
        if (fm.width(QLatin1Char(*hex)) != expectedCharWidth) {
            m_isMonospacedFont = false;
            break;
        }
        ++hex;
    }

139 140 141 142 143 144
    if (m_isMonospacedFont && fm.width("M M ") != m_charWidth * 4) {
        // On Qt/Mac, monospace font widths may have a fractional component
        // This breaks the assumption that width("MMM") == width('M') * 3

        m_isMonospacedFont = false;
        m_columnWidth = fm.width("MMM");
145 146 147
        m_labelWidth = m_addressBytes == 4
            ? fm.width("MMMM:MMMM")
            : fm.width("MMMM:MMMM:MMMM:MMMM");
148 149
    }

con's avatar
con committed
150 151 152 153 154
    horizontalScrollBar()->setRange(0, 2 * m_margin + 16 * m_columnWidth
                                    + m_labelWidth + m_textWidth - viewport()->width());
    horizontalScrollBar()->setPageStep(viewport()->width());
    verticalScrollBar()->setRange(0, m_numLines - m_numVisibleLines);
    verticalScrollBar()->setPageStep(m_numVisibleLines);
155
    ensureCursorVisible();
con's avatar
con committed
156 157 158
}


ck's avatar
ck committed
159
void BinEditor::addLazyData(quint64 block, const QByteArray &data)
160 161 162
{
    Q_ASSERT(m_inLazyMode);
    Q_ASSERT(data.size() == m_blockSize);
ck's avatar
ck committed
163 164
    const quint64 addr = block * m_blockSize;
    if (addr >= m_baseAddr && addr <= m_baseAddr + m_size - 1) {
ck's avatar
ck committed
165 166
        if (m_lazyData.size() * m_blockSize >= 64 * 1024 * 1024)
            m_lazyData.clear();
ck's avatar
ck committed
167 168 169 170 171
        const int translatedBlock = (addr - m_baseAddr) / m_blockSize;
        m_lazyData.insert(translatedBlock, data);
        m_lazyRequests.remove(translatedBlock);
        viewport()->update();
    }
172 173
}

174
bool BinEditor::requestDataAt(int pos, bool synchronous) const
175 176 177 178 179
{
    if (!m_inLazyMode)
        return true;

    int block = pos / m_blockSize;
ck's avatar
ck committed
180 181 182 183
    QMap<int, QByteArray>::const_iterator it = m_modifiedData.find(block);
    if (it != m_modifiedData.constEnd())
        return true;
    it = m_lazyData.find(block);
184 185 186
    if (it == m_lazyData.end()) {
        if (!m_lazyRequests.contains(block)) {
            m_lazyRequests.insert(block);
ck's avatar
ck committed
187
            emit const_cast<BinEditor*>(this)->
188 189
                lazyDataRequested(editorInterface(), m_baseAddr / m_blockSize + block,
                                  synchronous);
190 191 192 193 194 195 196 197 198 199 200 201 202 203
            if (!m_lazyRequests.contains(block))
                return true; // synchronous data source
        }
        return false;
    }

    return true;
}

char BinEditor::dataAt(int pos) const
{
    if (!m_inLazyMode)
        return m_data.at(pos);
    int block = pos / m_blockSize;
ck's avatar
ck committed
204
    return blockData(block).at(pos - (block*m_blockSize));
205 206 207 208 209 210 211 212 213
}

void BinEditor::changeDataAt(int pos, char c)
{
    if (!m_inLazyMode) {
        m_data[pos] = c;
        return;
    }
    int block = pos / m_blockSize;
ck's avatar
ck committed
214 215 216 217 218 219 220 221 222 223 224
    QMap<int, QByteArray>::iterator it = m_modifiedData.find(block);
    if (it != m_modifiedData.end()) {
        it.value()[pos - (block*m_blockSize)] = c;
    } else {
        it = m_lazyData.find(block);
        if (it != m_lazyData.end()) {
            QByteArray data = it.value();
            data[pos - (block*m_blockSize)] = c;
            m_modifiedData.insert(block, data);
        }
    }
225 226 227 228 229 230
}

QByteArray BinEditor::dataMid(int from, int length) const
{
    if (!m_inLazyMode)
        return m_data.mid(from, length);
231 232 233 234 235

    int end = from + length;
    int block = from / m_blockSize;

    QByteArray data;
236
    data.reserve(length);
237
    do {
ck's avatar
ck committed
238
        data += blockData(block++);
239 240 241
    } while (block * m_blockSize < end);

    return data.mid(from - ((from / m_blockSize) * m_blockSize), length);
242 243
}

244 245 246 247 248 249 250 251
QByteArray BinEditor::blockData(int block) const
{
    if (!m_inLazyMode) {
        QByteArray data = m_data.mid(block * m_blockSize, m_blockSize);
        if (data.size() < m_blockSize)
            data.resize(m_blockSize);
        return data;
    }
ck's avatar
ck committed
252 253 254
    QMap<int, QByteArray>::const_iterator it = m_modifiedData.find(block);
    return it != m_modifiedData.constEnd()
            ? it.value() : m_lazyData.value(block, m_emptyBlock);
255 256 257
}


con's avatar
con committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
void BinEditor::setFontSettings(const TextEditor::FontSettings &fs)
{
    setFont(fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_TEXT)).font());
}

void BinEditor::setBlinkingCursorEnabled(bool enable)
{
    if (enable && QApplication::cursorFlashTime() > 0)
        m_cursorBlinkTimer.start(QApplication::cursorFlashTime() / 2, this);
    else
        m_cursorBlinkTimer.stop();
    m_cursorVisible = enable;
    updateLines();
}

void BinEditor::focusInEvent(QFocusEvent *)
{
    setBlinkingCursorEnabled(true);
}

void BinEditor::focusOutEvent(QFocusEvent *)
{
    setBlinkingCursorEnabled(false);
}

void BinEditor::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == m_autoScrollTimer.timerId()) {
        QRect visible = viewport()->rect();
        QPoint pos;
        const QPoint globalPos = QCursor::pos();
        pos = viewport()->mapFromGlobal(globalPos);
        QMouseEvent ev(QEvent::MouseMove, pos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
        mouseMoveEvent(&ev);
        int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
        int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
        int delta = qMax(deltaX, deltaY);
        if (delta >= 0) {
            if (delta < 7)
                delta = 7;
            int timeout = 4900 / (delta * delta);
            m_autoScrollTimer.start(timeout, this);

            if (deltaY > 0)
                verticalScrollBar()->triggerAction(pos.y() < visible.center().y() ?
                                       QAbstractSlider::SliderSingleStepSub
                                       : QAbstractSlider::SliderSingleStepAdd);
            if (deltaX > 0)
                horizontalScrollBar()->triggerAction(pos.x() < visible.center().x() ?
                                       QAbstractSlider::SliderSingleStepSub
                                       : QAbstractSlider::SliderSingleStepAdd);
        }
    } else if (e->timerId() == m_cursorBlinkTimer.timerId()) {
        m_cursorVisible = !m_cursorVisible;
        updateLines();
    }
    QAbstractScrollArea::timerEvent(e);
}


void BinEditor::setModified(bool modified)
{
    int unmodifiedState = modified ? -1 : m_undoStack.size();
    if (unmodifiedState == m_unmodifiedState)
        return;
    m_unmodifiedState = unmodifiedState;
    emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
}

bool BinEditor::isModified() const
{
    return (m_undoStack.size() != m_unmodifiedState);
}

332 333 334 335 336 337 338 339 340 341
void BinEditor::setReadOnly(bool readOnly)
{
    m_readOnly = readOnly;
}

bool BinEditor::isReadOnly() const
{
    return m_readOnly;
}

con's avatar
con committed
342 343
void BinEditor::setData(const QByteArray &data)
{
344
    m_inLazyMode = false;
ck's avatar
ck committed
345
    m_baseAddr = 0;
346
    m_lazyData.clear();
ck's avatar
ck committed
347
    m_modifiedData.clear();
348
    m_lazyRequests.clear();
con's avatar
con committed
349
    m_data = data;
350
    m_size = data.size();
351
    m_addressBytes = 4;
352

con's avatar
con committed
353 354 355
    m_unmodifiedState = 0;
    m_undoStack.clear();
    m_redoStack.clear();
356

con's avatar
con committed
357
    init();
358 359
    m_cursorPosition = 0;
    verticalScrollBar()->setValue(0);
con's avatar
con committed
360

361
    emit cursorPositionChanged(m_cursorPosition);
con's avatar
con committed
362 363 364 365 366 367 368 369
    viewport()->update();
}

QByteArray BinEditor::data() const
{
    return m_data;
}

ck's avatar
ck committed
370
bool BinEditor::save(const QString &oldFileName, const QString &newFileName)
371
{
ck's avatar
ck committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    if (m_inLazyMode) {
        if (oldFileName != newFileName) {
            QString tmpName;
            {
                QTemporaryFile tmp;
                if (!tmp.open())
                    return false;
                tmpName = tmp.fileName();
            }
            if (!QFile::copy(oldFileName, tmpName))
                return false;
            if (QFile::exists(newFileName) && !QFile::remove(newFileName))
                return false;
            if (!QFile::rename(tmpName, newFileName))
                return false;
        }
        QFile output(newFileName);
        if (!output.open(QIODevice::ReadWrite)) // QtBug: WriteOnly truncates.
            return false;
        const qint64 size = output.size();
        for (QMap<int, QByteArray>::const_iterator it = m_modifiedData.constBegin();
            it != m_modifiedData.constEnd(); ++it) {
            if (!output.seek(it.key() * m_blockSize))
                return false;
            if (output.write(it.value()) < m_blockSize)
                return false;
        }
399 400 401 402

        // We may have padded the displayed data, so we have to make sure
        // changes to that area are not actually written back to disk.
        if (!output.resize(size))
ck's avatar
ck committed
403 404 405 406 407 408 409
            return false;
    } else {
        QFile output(newFileName);
        if (!output.open(QIODevice::WriteOnly | QIODevice::Truncate))
            return false;
        if (output.write(m_data) < m_size)
            return false;
410
    }
ck's avatar
ck committed
411
    setModified(false);
412 413 414
    return true;
}

ck's avatar
ck committed
415
void BinEditor::setLazyData(quint64 startAddr, int range, int blockSize)
416 417 418
{
    m_inLazyMode = true;
    m_blockSize = blockSize;
419
    Q_ASSERT((blockSize/16) * 16 == blockSize);
420 421 422
    m_emptyBlock = QByteArray(blockSize, '\0');
    m_data.clear();
    m_lazyData.clear();
ck's avatar
ck committed
423
    m_modifiedData.clear();
424
    m_lazyRequests.clear();
ck's avatar
ck committed
425 426 427 428 429 430

    // In lazy mode, users can edit data in the range
    // [startAddr - range/2, startAddr + range/2].
    m_baseAddr = static_cast<quint64>(range/2) > startAddr
                ? 0 : startAddr - range/2;
    m_baseAddr = (m_baseAddr / blockSize) * blockSize;
431 432 433
    const quint64 maxRange = Q_UINT64_C(0xffffffffffffffff) - m_baseAddr + 1;
    m_size = m_baseAddr != 0 && static_cast<quint64>(range) >= maxRange
             ? maxRange : range;
434 435
    m_addressBytes = (m_baseAddr + m_size < quint64(1) << 32
                      && m_baseAddr + m_size >= m_baseAddr) ? 4 : 8;
436 437 438 439 440 441 442

    m_unmodifiedState = 0;
    m_undoStack.clear();
    m_redoStack.clear();

    init();

443
    setCursorPosition(startAddr - m_baseAddr);
444
    viewport()->update();
445 446
}

con's avatar
con committed
447 448 449 450 451 452 453 454
void BinEditor::resizeEvent(QResizeEvent *)
{
    init();
}

void BinEditor::scrollContentsBy(int dx, int dy)
{
    viewport()->scroll(isRightToLeft() ? -dx : dx, dy * m_lineHeight);
455 456 457 458
    if (m_inLazyMode) {
        const QScrollBar * const scrollBar = verticalScrollBar();
        const int scrollPos = scrollBar->value();
        if (dy <= 0 && scrollPos == scrollBar->maximum())
ck's avatar
ck committed
459 460
            emit newRangeRequested(editorInterface(),
                baseAddress() + dataSize());
461
        else if (dy >= 0 && scrollPos == scrollBar->minimum())
ck's avatar
ck committed
462
            emit newRangeRequested(editorInterface(), baseAddress());
463
    }
con's avatar
con committed
464 465 466 467 468
}

void BinEditor::changeEvent(QEvent *e)
{
    QAbstractScrollArea::changeEvent(e);
hjk's avatar
hjk committed
469
    if (e->type() == QEvent::ActivationChange) {
con's avatar
con committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
        if (!isActiveWindow())
            m_autoScrollTimer.stop();
    }
    init();
    viewport()->update();
}


void BinEditor::wheelEvent(QWheelEvent *e)
{
    if (e->modifiers() & Qt::ControlModifier) {
        const int delta = e->delta();
        if (delta < 0)
            zoomOut();
        else if (delta > 0)
            zoomIn();
        return;
    }
    QAbstractScrollArea::wheelEvent(e);
}



QRect BinEditor::cursorRect() const
{
    int topLine = verticalScrollBar()->value();
    int line = m_cursorPosition / 16;
    int y = (line - topLine) * m_lineHeight;
    int xoffset = horizontalScrollBar()->value();
    int column = m_cursorPosition % 16;
    int x = m_hexCursor ?
            (-xoffset + m_margin + m_labelWidth + column * m_columnWidth)
            : (-xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth + column * m_charWidth);
    int w = m_hexCursor ? m_columnWidth : m_charWidth;
    return QRect(x, y, w, m_lineHeight);
}

int BinEditor::posAt(const QPoint &pos) const
{
    int xoffset = horizontalScrollBar()->value();
    int x = xoffset + pos.x() - m_margin - m_labelWidth;
    int column = qMin(15, qMax(0,x) / m_columnWidth);
    int topLine = verticalScrollBar()->value();
    int line = pos.y() / m_lineHeight;


    if (x > 16 * m_columnWidth + m_charWidth/2) {
        x -= 16 * m_columnWidth + m_charWidth;
        for (column = 0; column < 15; ++column) {
            int pos = (topLine + line) * 16 + column;
520
            if (pos < 0 || pos >= m_size)
con's avatar
con committed
521
                break;
522
            QChar qc(QLatin1Char(dataAt(pos)));
con's avatar
con committed
523 524 525 526 527 528 529 530
            if (!qc.isPrint())
                qc = 0xB7;
            x -= fontMetrics().width(qc);
            if (x <= 0)
                break;
        }
    }

531
    return (qMin(m_size, qMin(m_numLines, topLine + line) * 16) + column);
con's avatar
con committed
532 533 534 535 536 537 538 539 540
}

bool BinEditor::inTextArea(const QPoint &pos) const
{
    int xoffset = horizontalScrollBar()->value();
    int x = xoffset + pos.x() - m_margin - m_labelWidth;
    return (x > 16 * m_columnWidth + m_charWidth/2);
}

hjk's avatar
hjk committed
541 542 543 544
void BinEditor::updateLines()
{
    updateLines(m_cursorPosition, m_cursorPosition);
}
con's avatar
con committed
545 546 547 548 549 550 551 552 553 554 555 556

void BinEditor::updateLines(int fromPosition, int toPosition)
{
    int topLine = verticalScrollBar()->value();
    int firstLine = qMin(fromPosition, toPosition) / 16;
    int lastLine = qMax(fromPosition, toPosition) / 16;
    int y = (firstLine - topLine) * m_lineHeight;
    int h = (lastLine - firstLine + 1 ) * m_lineHeight;

    viewport()->update(0, y, viewport()->width(), h);
}

557
int BinEditor::dataIndexOf(const QByteArray &pattern, int from, bool caseSensitive) const
con's avatar
con committed
558
{
559 560 561 562 563 564 565 566
    if (!m_inLazyMode && caseSensitive) {
        return m_data.indexOf(pattern, from);
    }

    int trailing = pattern.size();
    if (trailing > m_blockSize)
        return -1;

con's avatar
con committed
567 568
    QByteArray buffer;
    buffer.resize(m_blockSize + trailing);
569 570 571 572
    char *b = buffer.data();
    QByteArrayMatcher matcher(pattern);

    int block = from / m_blockSize;
ck's avatar
ck committed
573 574 575
    const int end =
        qMin<qint64>(static_cast<qint64>(from) + SearchStride, m_size);
    while (from < end) {
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        if (!requestDataAt(block * m_blockSize, true))
            return -1;
        QByteArray data = blockData(block);
        ::memcpy(b, b + m_blockSize, trailing);
        ::memcpy(b + trailing, data.constData(), m_blockSize);

        if (!caseSensitive)
            ::lower(buffer);

        int pos = matcher.indexIn(buffer, from - (block * m_blockSize) + trailing);
        if (pos >= 0)
            return pos + block * m_blockSize - trailing;
        ++block;
        from = block * m_blockSize - trailing;
    }
ck's avatar
ck committed
591
    return end == m_size ? -1 : -2;
592 593 594 595 596 597 598 599 600 601 602
}

int BinEditor::dataLastIndexOf(const QByteArray &pattern, int from, bool caseSensitive) const
{
    if (!m_inLazyMode && caseSensitive)
        return m_data.lastIndexOf(pattern, from);

    int trailing = pattern.size();
    if (trailing > m_blockSize)
        return -1;

mae's avatar
mae committed
603 604
    QByteArray buffer;
    buffer.resize(m_blockSize + trailing);
605 606 607
    char *b = buffer.data();

    int block = from / m_blockSize;
ck's avatar
ck committed
608 609
    const int lowerBound = qMax(0, from - SearchStride);
    while (from > lowerBound) {
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        if (!requestDataAt(block * m_blockSize, true))
            return -1;
        QByteArray data = blockData(block);
        ::memcpy(b + m_blockSize, b, trailing);
        ::memcpy(b, data.constData(), m_blockSize);

        if (!caseSensitive)
            ::lower(buffer);

        int pos = buffer.lastIndexOf(pattern, from - (block * m_blockSize));
        if (pos >= 0)
            return pos + block * m_blockSize;
        --block;
        from = block * m_blockSize + (m_blockSize-1) + trailing;
    }
ck's avatar
ck committed
625
    return lowerBound == 0 ? -1 : -2;
626 627 628
}


ck's avatar
ck committed
629 630
int BinEditor::find(const QByteArray &pattern_arg, int from,
                    QTextDocument::FindFlags findFlags)
631 632 633 634 635 636 637 638 639 640 641
{
    if (pattern_arg.isEmpty())
        return 0;

    QByteArray pattern = pattern_arg;

    bool caseSensitiveSearch = (findFlags & QTextDocument::FindCaseSensitively);

    if (!caseSensitiveSearch)
        ::lower(pattern);

con's avatar
con committed
642
    bool backwards = (findFlags & QTextDocument::FindBackward);
643 644
    int found = backwards ? dataLastIndexOf(pattern, from, caseSensitiveSearch)
                : dataIndexOf(pattern, from, caseSensitiveSearch);
ck's avatar
ck committed
645

con's avatar
con committed
646
    int foundHex = -1;
647
    QByteArray hexPattern = calculateHexPattern(pattern_arg);
con's avatar
con committed
648
    if (!hexPattern.isEmpty()) {
649 650
        foundHex = backwards ? dataLastIndexOf(hexPattern, from)
                   : dataIndexOf(hexPattern, from);
con's avatar
con committed
651 652
    }

ck's avatar
ck committed
653 654
    int pos = foundHex == -1 || (found >= 0 && (foundHex == -2 || found < foundHex))
              ? found : foundHex;
655 656 657 658

    if (pos >= m_size)
        pos = -1;

con's avatar
con committed
659 660 661 662 663 664 665
    if (pos >= 0) {
        setCursorPosition(pos);
        setCursorPosition(pos + (found == pos ? pattern.size() : hexPattern.size()), KeepAnchor);
    }
    return pos;
}

666
int BinEditor::findPattern(const QByteArray &data, const QByteArray &dataHex, int from, int offset, int *match)
con's avatar
con committed
667 668 669 670
{
    if (m_searchPattern.isEmpty())
        return -1;
    int normal = m_searchPattern.isEmpty()? -1 : data.indexOf(m_searchPattern, from - offset);
671
    int hex = m_searchPatternHex.isEmpty()? -1 : dataHex.indexOf(m_searchPatternHex, from - offset);
con's avatar
con committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

    if (normal >= 0 && (hex < 0 || normal < hex)) {
        if (match)
            *match = m_searchPattern.length();
        return normal + offset;
    }
    if (hex >= 0) {
        if (match)
            *match = m_searchPatternHex.length();
        return hex + offset;
    }

    return -1;
}


void BinEditor::drawItems(QPainter *painter, int x, int y, const QString &itemString)
{
    if (m_isMonospacedFont) {
        painter->drawText(x, y, itemString);
    } else {
        for (int i = 0; i < 16; ++i)
            painter->drawText(x + i*m_columnWidth, y, itemString.mid(i*3, 2));
    }
}

ck's avatar
ck committed
698
QString BinEditor::addressString(quint64 address)
con's avatar
con committed
699 700 701
{
    QChar *addressStringData = m_addressString.data();
    const char *hex = "0123456789abcdef";
ck's avatar
ck committed
702 703 704 705 706 707

    // Take colons into account.
    const int indices[16] = {
        0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18
    };

708 709 710 711 712
    for (int b = 0; b < m_addressBytes; ++b) {
        addressStringData[indices[2*m_addressBytes - 1 - b*2]] =
            hex[(address >> (8*b)) & 0xf];
        addressStringData[indices[2*m_addressBytes - 2 - b*2]] =
            hex[(address >> (8*b + 4)) & 0xf];
con's avatar
con committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    }
    return m_addressString;
}

void BinEditor::paintEvent(QPaintEvent *e)
{
    QPainter painter(viewport());
    int topLine = verticalScrollBar()->value();
    int xoffset = horizontalScrollBar()->value();
    painter.drawLine(-xoffset + m_margin + m_labelWidth - m_charWidth/2, 0,
                     -xoffset + m_margin + m_labelWidth - m_charWidth/2, viewport()->height());
    painter.drawLine(-xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth/2, 0,
                     -xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth/2, viewport()->height());


    int viewport_height = viewport()->height();
    QBrush alternate_base = palette().alternateBase();
    for (int i = 0; i < 8; ++i) {
        int bg_x = -xoffset +  m_margin + (2 * i + 1) * m_columnWidth + m_labelWidth;
        QRect r(bg_x - m_charWidth/2, 0, m_columnWidth, viewport_height);
        painter.fillRect(e->rect() & r, palette().alternateBase());
    }

    int matchLength = 0;

738
    QByteArray patternData, patternDataHex;
con's avatar
con committed
739
    int patternOffset = qMax(0, topLine*16 - m_searchPattern.size());
740
    if (!m_searchPattern.isEmpty()) {
741
        patternData = dataMid(patternOffset, m_numVisibleLines * 16 + (topLine*16 - patternOffset));
742 743 744 745 746
        patternDataHex = patternData;
        if (!m_caseSensitiveSearch)
            ::lower(patternData);
    }

con's avatar
con committed
747

748
    int foundPatternAt = findPattern(patternData, patternDataHex, patternOffset, patternOffset, &matchLength);
con's avatar
con committed
749 750 751 752

    int selStart = qMin(m_cursorPosition, m_anchorPosition);
    int selEnd = qMax(m_cursorPosition, m_anchorPosition);

753
    QString itemString(16*3, QLatin1Char(' '));
con's avatar
con committed
754 755 756 757
    QChar *itemStringData = itemString.data();
    const char *hex = "0123456789abcdef";

    painter.setPen(palette().text().color());
hjk's avatar
hjk committed
758
    const QFontMetrics &fm = painter.fontMetrics();
con's avatar
con committed
759 760 761 762 763 764 765 766 767 768 769 770
    for (int i = 0; i <= m_numVisibleLines; ++i) {
        int line = topLine + i;
        if (line >= m_numLines)
            break;

        int y = i * m_lineHeight + m_ascent;
        if (y - m_ascent > e->rect().bottom())
            break;
        if (y + m_descent < e->rect().top())
            continue;


ck's avatar
ck committed
771 772
        painter.drawText(-xoffset, i * m_lineHeight + m_ascent,
                         addressString(m_baseAddr + ((uint) line) * 16));
773

con's avatar
con committed
774
        int cursor = -1;
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
        if (line * 16 <= m_cursorPosition && m_cursorPosition < line * 16 + 16)
            cursor = m_cursorPosition - line * 16;

        bool hasData = requestDataAt(line * 16);

        QString printable;

        if (hasData) {
            for (int c = 0; c < 16; ++c) {
                int pos = line * 16 + c;
                if (pos >= m_size)
                    break;
                QChar qc(QLatin1Char(dataAt(pos)));
                if (qc.unicode() >= 127 || !qc.isPrint())
                    qc = 0xB7;
                printable += qc;
            }
        } else {
            printable = QString(16, QLatin1Char(' '));
con's avatar
con committed
794 795 796 797 798 799 800
        }

        QRect selectionRect;
        QRect printableSelectionRect;

        bool isFullySelected = (selStart < selEnd && selStart <= line*16 && (line+1)*16 <= selEnd);

801 802 803 804 805 806 807 808 809
        if (hasData) {
            for (int c = 0; c < 16; ++c) {
                int pos = line * 16 + c;
                if (pos >= m_size) {
                    while (c < 16) {
                        itemStringData[c*3] = itemStringData[c*3+1] = ' ';
                        ++c;
                    }
                    break;
con's avatar
con committed
810 811
                }

812
                if (foundPatternAt >= 0 && pos >= foundPatternAt + matchLength)
813
                    foundPatternAt = findPattern(patternData, patternDataHex, foundPatternAt + matchLength, patternOffset, &matchLength);
con's avatar
con committed
814 815


816 817 818
                uchar value = (uchar)dataAt(pos);
                itemStringData[c*3] = hex[value >> 4];
                itemStringData[c*3+1] = hex[value & 0xf];
con's avatar
con committed
819

820
                int item_x = -xoffset +  m_margin + c * m_columnWidth + m_labelWidth;
con's avatar
con committed
821

822 823 824
                if (foundPatternAt >= 0 && pos >= foundPatternAt && pos < foundPatternAt + matchLength) {
                    painter.fillRect(item_x, y-m_ascent, m_columnWidth, m_lineHeight, QColor(0xffef0b));
                    int printable_item_x = -xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth
hjk's avatar
hjk committed
825
                                           + fm.width(printable.left(c));
826
                    painter.fillRect(printable_item_x, y-m_ascent,
hjk's avatar
hjk committed
827
                                     fm.width(printable.at(c)),
828 829
                                     m_lineHeight, QColor(0xffef0b));
                }
con's avatar
con committed
830

831 832 833
                if (selStart < selEnd && !isFullySelected && pos >= selStart && pos < selEnd) {
                    selectionRect |= QRect(item_x, y-m_ascent, m_columnWidth, m_lineHeight);
                    int printable_item_x = -xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth
hjk's avatar
hjk committed
834
                                           + fm.width(printable.left(c));
835
                    printableSelectionRect |= QRect(printable_item_x, y-m_ascent,
hjk's avatar
hjk committed
836
                                                    fm.width(printable.at(c)),
837 838
                                                    m_lineHeight);
                }
con's avatar
con committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
            }
        }

        int x = -xoffset +  m_margin + m_labelWidth;

        if (isFullySelected) {
            painter.save();
            painter.fillRect(x, y-m_ascent, 16*m_columnWidth, m_lineHeight, palette().highlight());
            painter.setPen(palette().highlightedText().color());
            drawItems(&painter, x, y, itemString);
            painter.restore();
        } else {
            drawItems(&painter, x, y, itemString);
            if (!selectionRect.isEmpty()) {
                painter.save();
                painter.fillRect(selectionRect, palette().highlight());
                painter.setPen(palette().highlightedText().color());
                painter.setClipRect(selectionRect);
                drawItems(&painter, x, y, itemString);
                painter.restore();
            }
        }


        if (cursor >= 0) {
hjk's avatar
hjk committed
864
            int w = fm.boundingRect(itemString.mid(cursor*3, 2)).width();
con's avatar
con committed
865 866 867 868 869 870 871
            QRect cursorRect(x + cursor * m_columnWidth, y - m_ascent, w + 1, m_lineHeight);
            painter.save();
            painter.setPen(Qt::red);
            painter.drawRect(cursorRect.adjusted(0, 0, 0, -1));
            painter.restore();
            if (m_hexCursor && m_cursorVisible) {
                if (m_lowNibble)
hjk's avatar
hjk committed
872
                    cursorRect.adjust(fm.width(itemString.left(1)), 0, 0, 0);
con's avatar
con committed
873 874 875 876 877 878 879 880 881 882 883 884 885
                painter.fillRect(cursorRect, Qt::red);
                painter.save();
                painter.setClipRect(cursorRect);
                painter.setPen(Qt::white);
                drawItems(&painter, x, y, itemString);
                painter.restore();
            }
        }

        int text_x = -xoffset + m_margin + m_labelWidth + 16 * m_columnWidth + m_charWidth;

        if (isFullySelected) {
                painter.save();
hjk's avatar
hjk committed
886
                painter.fillRect(text_x, y-m_ascent, fm.width(printable), m_lineHeight,
con's avatar
con committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
                                 palette().highlight());
                painter.setPen(palette().highlightedText().color());
                painter.drawText(text_x, y, printable);
                painter.restore();
        }else {
            painter.drawText(text_x, y, printable);
            if (!printableSelectionRect.isEmpty()) {
                painter.save();
                painter.fillRect(printableSelectionRect, palette().highlight());
                painter.setPen(palette().highlightedText().color());
                painter.setClipRect(printableSelectionRect);
                painter.drawText(text_x, y, printable);
                painter.restore();
            }
        }

903
        if (cursor >= 0 && !printable.isEmpty()) {
hjk's avatar
hjk committed
904
            QRect cursorRect(text_x + fm.width(printable.left(cursor)),
con's avatar
con committed
905
                             y-m_ascent,
hjk's avatar
hjk committed
906
                             fm.width(printable.at(cursor)),
con's avatar
con committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
                             m_lineHeight);
            painter.save();
            if (m_hexCursor || !m_cursorVisible) {
                painter.setPen(Qt::red);
                painter.drawRect(cursorRect.adjusted(0, 0, 0, -1));
            } else {
                painter.setClipRect(cursorRect);
                painter.fillRect(cursorRect, Qt::red);
                painter.setPen(Qt::white);
                painter.drawText(text_x, y, printable);
            }
            painter.restore();
        }
    }
}


int BinEditor::cursorPosition() const
{
    return m_cursorPosition;
}

void BinEditor::setCursorPosition(int pos, MoveMode moveMode)
{
931
    pos = qMin(m_size-1, qMax(0, pos));
con's avatar
con committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    int oldCursorPosition = m_cursorPosition;

    bool hasSelection = m_anchorPosition != m_cursorPosition;
    m_lowNibble = false;
    if (!hasSelection)
        updateLines();
    m_cursorPosition = pos;
    if (moveMode == MoveAnchor) {
        if (hasSelection)
            updateLines(m_anchorPosition, oldCursorPosition);
        m_anchorPosition = m_cursorPosition;
    }

    hasSelection = m_anchorPosition != m_cursorPosition;
    updateLines(hasSelection ? oldCursorPosition : m_cursorPosition, m_cursorPosition);
    ensureCursorVisible();
    if (hasSelection != (m_anchorPosition != m_anchorPosition))
        emit copyAvailable(m_anchorPosition != m_cursorPosition);
    emit cursorPositionChanged(m_cursorPosition);
}


void BinEditor::ensureCursorVisible()
{
    QRect cr = cursorRect();
    QRect vr = viewport()->rect();
    if (!vr.contains(cr)) {
        if (cr.top() < vr.top())
            verticalScrollBar()->setValue(m_cursorPosition / 16);
        else if (cr.bottom() > vr.bottom())
            verticalScrollBar()->setValue(m_cursorPosition / 16 - m_numVisibleLines + 1);
    }
}

void BinEditor::mousePressEvent(QMouseEvent *e)
{
    if (e->button() != Qt::LeftButton)
        return;
    setCursorPosition(posAt(e->pos()));
    setBlinkingCursorEnabled(true);
    if (m_hexCursor == inTextArea(e->pos())) {
        m_hexCursor = !m_hexCursor;
        updateLines();
    }
}

void BinEditor::mouseMoveEvent(QMouseEvent *e)
{
    if (!(e->buttons() & Qt::LeftButton))
        return;
    setCursorPosition(posAt(e->pos()), KeepAnchor);
    if (m_hexCursor == inTextArea(e->pos())) {
        m_hexCursor = !m_hexCursor;
        updateLines();
    }
    QRect visible = viewport()->rect();
    if (visible.contains(e->pos()))
        m_autoScrollTimer.stop();
    else if (!m_autoScrollTimer.isActive())
        m_autoScrollTimer.start(100, this);
}

void BinEditor::mouseReleaseEvent(QMouseEvent *)
{
    if (m_autoScrollTimer.isActive()) {
        m_autoScrollTimer.stop();
        ensureCursorVisible();
    }
}

void BinEditor::selectAll()
{
    setCursorPosition(0);
1005
    setCursorPosition(m_size-1, KeepAnchor);
con's avatar
con committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
}

void BinEditor::clear()
{
    setData(QByteArray());
}

bool BinEditor::event(QEvent *e) {
    if (e->type() == QEvent::KeyPress) {
        switch (static_cast<QKeyEvent*>(e)->key()) {
        case Qt::Key_Tab:
        case Qt::Key_Backtab:
            m_hexCursor = !m_hexCursor;
            setBlinkingCursorEnabled(true);
            ensureCursorVisible();
            e->accept();
            return true;
1023 1024 1025 1026
        case Qt::Key_Down:
            if (m_inLazyMode) {
                const QScrollBar * const scrollBar = verticalScrollBar();
                if (scrollBar->value() >= scrollBar->maximum() - 1) {
ck's avatar
ck committed
1027 1028
                    emit newRangeRequested(editorInterface(),
                        baseAddress() + dataSize());
1029 1030 1031 1032
                    return true;
                }
            }
            break;
con's avatar
con committed
1033 1034
        default:;
        }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    } else if (e->type() == QEvent::ToolTip) {
        bool hide = true;
        int selStart = selectionStart();
        int selEnd = selectionEnd();
        int byteCount = selEnd - selStart;
        if (byteCount <= 0) {
            selStart = m_cursorPosition;
            selEnd = selStart + 1;
            byteCount = 1;
        }
1045
        if (m_hexCursor && byteCount <= 8) {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            const QPoint &startPoint = offsetToPos(selStart);
            const QPoint &endPoint = offsetToPos(selEnd);
            const QPoint expandedEndPoint
                = QPoint(endPoint.x(), endPoint.y() + m_lineHeight);
            const QRect selRect(startPoint, expandedEndPoint);
            const QHelpEvent * const helpEvent = static_cast<QHelpEvent *>(e);
            const QPoint &mousePos = helpEvent->pos();
            if (selRect.contains(mousePos)) {
                quint64 beValue, leValue;
                asIntegers(selStart, byteCount, beValue, leValue);
                QString leSigned;
                QString beSigned;
                switch (byteCount) {
                case 8: case 7: case 6: case 5:
                    leSigned = QString::number(static_cast<qint64>(leValue));
                    beSigned = QString::number(static_cast<qint64>(beValue));
                    break;
                case 4: case 3:
                    leSigned = QString::number(static_cast<qint32>(leValue));
                    beSigned = QString::number(static_cast<qint32>(beValue));
                    break;
                case 2:
                    leSigned = QString::number(static_cast<qint16>(leValue));
                    beSigned = QString::number(static_cast<qint16>(beValue));
                    break;
                case 1:
                    leSigned = QString::number(static_cast<qint8>(leValue));
                    beSigned = QString::number(static_cast<qint8>(beValue));
                    break;
                }
                hide = false;
                QToolTip::showText(helpEvent->globalPos(),
                    tr("Decimal unsigned value (little endian): %1\n"
                       "Decimal unsigned value (big endian): %2\n"
                       "Decimal signed value (little endian): %3\n"
                       "Decimal signed value (big endian): %4")
                       .arg(QString::number(leValue))
                       .arg(QString::number(beValue))
                       .arg(leSigned).arg(beSigned));
            }
        }
        if (hide)
            QToolTip::hideText();
        e->accept();
        return true;
con's avatar
con committed
1091
    }
1092

con's avatar
con committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    return QAbstractScrollArea::event(e);
}

void BinEditor::keyPressEvent(QKeyEvent *e)
{

    if (e == QKeySequence::SelectAll) {
            e->accept();
            selectAll();
            return;
    } else if (e == QKeySequence::Copy) {
        e->accept();
        copy();
        return;
    } else if (e == QKeySequence::Undo) {
        e->accept();
        undo();
        return;
    } else if (e == QKeySequence::Redo) {
        e->accept();
        redo();
        return;
    }


    MoveMode moveMode = e->modifiers() & Qt::ShiftModifier ? KeepAnchor : MoveAnchor;
    switch (e->key()) {
    case Qt::Key_Up:
        setCursorPosition(m_cursorPosition - 16, moveMode);
        break;
    case Qt::Key_Down:
        setCursorPosition(m_cursorPosition + 16, moveMode);
        break;
    case Qt::Key_Right:
        setCursorPosition(m_cursorPosition + 1, moveMode);
        break;
    case Qt::Key_Left:
        setCursorPosition(m_cursorPosition - 1, moveMode);
        break;
    case Qt::Key_PageUp:
    case Qt::Key_PageDown: {
        int line = qMax(0, m_cursorPosition / 16 - verticalScrollBar()->value());
        verticalScrollBar()->triggerAction(e->key() == Qt::Key_PageUp ?
                                           QScrollBar::SliderPageStepSub : QScrollBar::SliderPageStepAdd);
        setCursorPosition((verticalScrollBar()->value() + line) * 16 + m_cursorPosition % 16, moveMode);
    } break;

    case Qt::Key_Home:
1141 1142 1143 1144 1145 1146 1147 1148
        if (e->modifiers() & Qt::ControlModifier) {
            if (m_inLazyMode)
                emit startOfFileRequested(editorInterface());
            else
                setCursorPosition(0);
        } else {
            setCursorPosition(m_cursorPosition/16 * 16, moveMode);
        }
con's avatar
con committed
1149 1150
        break;
    case Qt::Key_End:
1151 1152 1153 1154 1155 1156 1157 1158
        if (e->modifiers() & Qt::ControlModifier) {
            if (m_inLazyMode)
                emit endOfFileRequested(editorInterface());
            else
                setCursorPosition(m_size - 1);
        } else {
            setCursorPosition(m_cursorPosition/16 * 16 + 15, moveMode);
        }
con's avatar
con committed
1159
        break;
1160 1161 1162 1163
    default:
        if (m_readOnly)
            break;
        {
con's avatar
con committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
        QString text = e->text();
        for (int i = 0; i < text.length(); ++i) {
            QChar c = text.at(i);
            if (m_hexCursor) {
                c = c.toLower();
                int nibble = -1;
                if (c.unicode() >= 'a' && c.unicode() <= 'f')
                    nibble = c.unicode() - 'a' + 10;
                else if (c.unicode() >= '0' && c.unicode() <= '9')
                    nibble = c.unicode() - '0';
                if (nibble < 0)
                    continue;
                if (m_lowNibble) {
1177
                    changeData(m_cursorPosition, nibble + (dataAt(m_cursorPosition) & 0xf0));
con's avatar
con committed
1178 1179 1180
                    m_lowNibble = false;
                    setCursorPosition(m_cursorPosition + 1);
                } else {
1181
                    changeData(m_cursorPosition, (nibble << 4) + (dataAt(m_cursorPosition) & 0x0f), true);
con's avatar
con committed
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
                    m_lowNibble = true;
                    updateLines();
                }
            } else {
                if (c.unicode() >= 128 || !c.isPrint())
                    continue;
                changeData(m_cursorPosition, c.unicode(), m_cursorPosition + 1);
                setCursorPosition(m_cursorPosition + 1);
            }
            setBlinkingCursorEnabled(true);
        }
    }
    }

    e->accept();
}

void BinEditor::zoomIn(int range)
{
    QFont f = font();
    const int newSize = f.pointSize() + range;
    if (newSize <= 0)
        return;
    f.setPointSize(newSize);
    setFont(f);
}

void BinEditor::zoomOut(int range)
{
    zoomIn(-range);
}

1214
void BinEditor::copy(bool raw)
con's avatar
con committed
1215
{
1216 1217 1218
    const int selStart = selectionStart();
    const int selEnd = selectionEnd();
    if (selStart < selEnd) {
1219 1220 1221 1222 1223 1224 1225
        const int selectionLength = selEnd - selStart;
        if (selectionLength >> 22) {
            QMessageBox::warning(this, tr("Copying Failed"),
                                 tr("You cannot copy more than 4 MB of binary data."));
            return;
        }
        const QByteArray &data = dataMid(selStart, selectionLength);
1226 1227 1228 1229
        if (raw) {
            QApplication::clipboard()->setText(data);
            return;
        }
1230 1231
        QString hexString;
        const char * const hex = "0123456789abcdef";
1232
        hexString.reserve(3 * data.size());
1233 1234 1235 1236 1237 1238 1239
        for (int i = 0; i < data.size(); ++i) {
            const uchar val = static_cast<uchar>(data[i]);
            hexString.append(hex[val >> 4]).append(hex[val & 0xf]).append(' ');
        }
        hexString.chop(1);
        QApplication::clipboard()->setText(hexString);
    }
con's avatar
con committed
1240 1241
}

1242
void BinEditor::highlightSearchResults(const QByteArray &pattern, QTextDocument::FindFlags findFlags)
con's avatar
con committed
1243 1244 1245 1246
{
    if (m_searchPattern == pattern)
        return;
    m_searchPattern = pattern;
1247 1248 1249
    m_caseSensitiveSearch = (findFlags & QTextDocument::FindCaseSensitively);
    if (!m_caseSensitiveSearch)
        ::lower(m_searchPattern);
con's avatar
con committed
1250