bineditor.cpp 42.7 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/QMenu>
44
#include <QtGui/QMessageBox>
con's avatar
con committed
45 46 47 48 49 50
#include <QtGui/QPainter>
#include <QtGui/QScrollBar>
#include <QtGui/QWheelEvent>

using namespace BINEditor;

51 52 53 54 55 56 57 58 59 60 61 62
// 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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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;
85
    m_inLazyMode = false;
ck's avatar
ck committed
86
    m_baseAddr = 0;
87
    m_blockSize = 4096;
con's avatar
con committed
88
    m_size = 0;
89
    m_addressBytes = 4;
con's avatar
con committed
90 91
    init();
    m_unmodifiedState = 0;
92
    m_readOnly = false;
con's avatar
con committed
93 94 95 96 97
    m_hexCursor = true;
    m_cursorPosition = 0;
    m_anchorPosition = 0;
    m_lowNibble = false;
    m_cursorVisible = false;
98
    m_caseSensitiveSearch = false;
99
    m_canRequestNewWindow = false;
con's avatar
con committed
100 101 102 103 104 105 106 107 108
    setFocusPolicy(Qt::WheelFocus);
}

BinEditor::~BinEditor()
{
}

void BinEditor::init()
{
109 110 111
    const int addressStringWidth =
        2*m_addressBytes + (m_addressBytes - 1) / 2;
    m_addressString = QString(addressStringWidth, QLatin1Char(':'));
con's avatar
con committed
112 113 114 115 116 117 118
    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(' ')));
119
    m_numLines = m_size / 16 + 1;
con's avatar
con committed
120 121 122
    m_numVisibleLines = viewport()->height() / m_lineHeight;
    m_textWidth = 16 * m_charWidth + m_charWidth;
    int m_numberWidth = fm.width(QChar(QLatin1Char('9')));
123 124
    m_labelWidth =
        2*m_addressBytes * m_numberWidth + (m_addressBytes - 1)/2 * m_charWidth;
con's avatar
con committed
125 126 127 128 129 130 131 132 133 134 135 136

    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;
    }

137 138 139 140 141 142
    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");
143 144 145
        m_labelWidth = m_addressBytes == 4
            ? fm.width("MMMM:MMMM")
            : fm.width("MMMM:MMMM:MMMM:MMMM");
146 147
    }

con's avatar
con committed
148 149 150 151 152
    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);
153
    ensureCursorVisible();
con's avatar
con committed
154 155 156
}


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

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

    int block = pos / m_blockSize;
ck's avatar
ck committed
178 179 180 181
    QMap<int, QByteArray>::const_iterator it = m_modifiedData.find(block);
    if (it != m_modifiedData.constEnd())
        return true;
    it = m_lazyData.find(block);
182 183 184
    if (it == m_lazyData.end()) {
        if (!m_lazyRequests.contains(block)) {
            m_lazyRequests.insert(block);
ck's avatar
ck committed
185
            emit const_cast<BinEditor*>(this)->
186 187
                lazyDataRequested(editorInterface(), m_baseAddr / m_blockSize + block,
                                  synchronous);
188 189 190 191 192 193 194 195 196 197 198 199 200 201
            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
202
    return blockData(block).at(pos - (block*m_blockSize));
203 204 205 206 207 208 209 210 211
}

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
212 213 214 215 216 217 218 219 220 221 222
    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);
        }
    }
223 224 225 226 227 228
}

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

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

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

    return data.mid(from - ((from / m_blockSize) * m_blockSize), length);
240 241
}

242 243 244 245 246 247 248 249
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
250 251 252
    QMap<int, QByteArray>::const_iterator it = m_modifiedData.find(block);
    return it != m_modifiedData.constEnd()
            ? it.value() : m_lazyData.value(block, m_emptyBlock);
253 254 255
}


con's avatar
con committed
256 257 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
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);
}

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

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

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

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

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

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

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

ck's avatar
ck committed
368
bool BinEditor::save(const QString &oldFileName, const QString &newFileName)
369
{
ck's avatar
ck committed
370 371 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
    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;
        }
397 398 399 400

        // 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
401 402 403 404 405 406 407
            return false;
    } else {
        QFile output(newFileName);
        if (!output.open(QIODevice::WriteOnly | QIODevice::Truncate))
            return false;
        if (output.write(m_data) < m_size)
            return false;
408
    }
ck's avatar
ck committed
409
    setModified(false);
410 411 412
    return true;
}

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

    // 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;
429 430 431
    const quint64 maxRange = Q_UINT64_C(0xffffffffffffffff) - m_baseAddr + 1;
    m_size = m_baseAddr != 0 && static_cast<quint64>(range) >= maxRange
             ? maxRange : range;
432 433
    m_addressBytes = (m_baseAddr + m_size < quint64(1) << 32
                      && m_baseAddr + m_size >= m_baseAddr) ? 4 : 8;
434 435 436 437 438 439 440

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

    init();

441
    setCursorPosition(startAddr - m_baseAddr);
442
    viewport()->update();
443 444
}

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

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

void BinEditor::changeEvent(QEvent *e)
{
    QAbstractScrollArea::changeEvent(e);
hjk's avatar
hjk committed
467
    if (e->type() == QEvent::ActivationChange) {
con's avatar
con committed
468 469 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
        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;
518
            if (pos < 0 || pos >= m_size)
con's avatar
con committed
519
                break;
520
            QChar qc(QLatin1Char(dataAt(pos)));
con's avatar
con committed
521 522 523 524 525 526 527 528
            if (!qc.isPrint())
                qc = 0xB7;
            x -= fontMetrics().width(qc);
            if (x <= 0)
                break;
        }
    }

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

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
539 540 541 542
void BinEditor::updateLines()
{
    updateLines(m_cursorPosition, m_cursorPosition);
}
con's avatar
con committed
543 544 545 546 547 548 549 550 551 552 553 554

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);
}

555
int BinEditor::dataIndexOf(const QByteArray &pattern, int from, bool caseSensitive) const
con's avatar
con committed
556
{
557 558 559 560 561 562 563 564
    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
565 566
    QByteArray buffer;
    buffer.resize(m_blockSize + trailing);
567 568 569 570
    char *b = buffer.data();
    QByteArrayMatcher matcher(pattern);

    int block = from / m_blockSize;
ck's avatar
ck committed
571 572 573
    const int end =
        qMin<qint64>(static_cast<qint64>(from) + SearchStride, m_size);
    while (from < end) {
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
        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
589
    return end == m_size ? -1 : -2;
590 591 592 593 594 595 596 597 598 599 600
}

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
601 602
    QByteArray buffer;
    buffer.resize(m_blockSize + trailing);
603 604 605
    char *b = buffer.data();

    int block = from / m_blockSize;
ck's avatar
ck committed
606 607
    const int lowerBound = qMax(0, from - SearchStride);
    while (from > lowerBound) {
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        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
623
    return lowerBound == 0 ? -1 : -2;
624 625 626
}


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

    QByteArray pattern = pattern_arg;

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

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

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

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

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

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

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

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

    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
696
QString BinEditor::addressString(quint64 address)
con's avatar
con committed
697 698 699
{
    QChar *addressStringData = m_addressString.data();
    const char *hex = "0123456789abcdef";
ck's avatar
ck committed
700 701 702 703 704 705

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

706 707 708 709 710
    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
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
    }
    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;

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

con's avatar
con committed
745

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

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

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

    painter.setPen(palette().text().color());
hjk's avatar
hjk committed
756
    const QFontMetrics &fm = painter.fontMetrics();
con's avatar
con committed
757 758 759 760 761 762 763 764 765 766 767 768
    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
769 770
        painter.drawText(-xoffset, i * m_lineHeight + m_ascent,
                         addressString(m_baseAddr + ((uint) line) * 16));
771

con's avatar
con committed
772
        int cursor = -1;
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
        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
792 793 794 795 796 797 798
        }

        QRect selectionRect;
        QRect printableSelectionRect;

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

799 800 801 802 803 804 805 806 807
        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
808 809
                }

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


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

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

820 821 822
                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
823
                                           + fm.width(printable.left(c));
824
                    painter.fillRect(printable_item_x, y-m_ascent,
hjk's avatar
hjk committed
825
                                     fm.width(printable.at(c)),
826 827
                                     m_lineHeight, QColor(0xffef0b));
                }
con's avatar
con committed
828

829 830 831
                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
832
                                           + fm.width(printable.left(c));
833
                    printableSelectionRect |= QRect(printable_item_x, y-m_ascent,
hjk's avatar
hjk committed
834
                                                    fm.width(printable.at(c)),
835 836
                                                    m_lineHeight);
                }
con's avatar
con committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
            }
        }

        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
862
            int w = fm.boundingRect(itemString.mid(cursor*3, 2)).width();
con's avatar
con committed
863 864 865 866 867 868 869
            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
870
                    cursorRect.adjust(fm.width(itemString.left(1)), 0, 0, 0);
con's avatar
con committed
871 872 873 874 875 876 877 878 879 880 881 882 883
                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
884
                painter.fillRect(text_x, y-m_ascent, fm.width(printable), m_lineHeight,
con's avatar
con committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
                                 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();
            }
        }

901
        if (cursor >= 0 && !printable.isEmpty()) {
hjk's avatar
hjk committed
902
            QRect cursorRect(text_x + fm.width(printable.left(cursor)),
con's avatar
con committed
903
                             y-m_ascent,
hjk's avatar
hjk committed
904
                             fm.width(printable.at(cursor)),
con's avatar
con committed
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
                             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)
{
929
    pos = qMin(m_size-1, qMax(0, pos));
con's avatar
con committed
930 931 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
    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);
1003
    setCursorPosition(m_size-1, KeepAnchor);
con's avatar
con committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
}

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;
1021 1022 1023 1024
        case Qt::Key_Down:
            if (m_inLazyMode) {
                const QScrollBar * const scrollBar = verticalScrollBar();
                if (scrollBar->value() >= scrollBar->maximum() - 1) {
ck's avatar
ck committed
1025 1026
                    emit newRangeRequested(editorInterface(),
                        baseAddress() + dataSize());
1027 1028 1029 1030
                    return true;
                }
            }
            break;
con's avatar
con committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 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
        default:;
        }
    }
    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:
        setCursorPosition((e->modifiers() & Qt::ControlModifier) ?
                          0 : (m_cursorPosition/16 * 16), moveMode);
        break;
    case Qt::Key_End:
        setCursorPosition((e->modifiers() & Qt::ControlModifier) ?
1087
                          (m_size-1) : (m_cursorPosition/16 * 16 + 15), moveMode);
con's avatar
con committed
1088 1089
        break;

1090 1091 1092 1093
    default:
        if (m_readOnly)
            break;
        {
con's avatar
con committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        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) {
1107
                    changeData(m_cursorPosition, nibble + (dataAt(m_cursorPosition) & 0xf0));
con's avatar
con committed
1108 1109 1110
                    m_lowNibble = false;
                    setCursorPosition(m_cursorPosition + 1);
                } else {
1111
                    changeData(m_cursorPosition, (nibble << 4) + (dataAt(m_cursorPosition) & 0x0f), true);
con's avatar
con committed
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 1141 1142 1143
                    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);
}

1144
void BinEditor::copy(bool raw)
con's avatar
con committed
1145
{
1146 1147 1148
    const int selStart = selectionStart();
    const int selEnd = selectionEnd();
    if (selStart < selEnd) {
1149 1150 1151 1152 1153 1154 1155
        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);
1156 1157 1158 1159
        if (raw) {
            QApplication::clipboard()->setText(data);
            return;
        }
1160 1161
        QString hexString;
        const char * const hex = "0123456789abcdef";
1162
        hexString.reserve(3 * data.size());
1163 1164 1165 1166 1167 1168 1169
        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
1170 1171
}

1172
void BinEditor::highlightSearchResults(const QByteArray &pattern, QTextDocument::FindFlags findFlags)
con's avatar
con committed
1173 1174 1175 1176
{
    if (m_searchPattern == pattern)
        return;
    m_searchPattern = pattern;
1177 1178 1179
    m_caseSensitiveSearch = (findFlags & QTextDocument::FindCaseSensitively);
    if (!m_caseSensitiveSearch)
        ::lower(m_searchPattern);
con's avatar
con committed
1180 1181 1182 1183 1184 1185 1186
    m_searchPatternHex = calculateHexPattern(pattern);
    viewport()->update();
}


void BinEditor::changeData(int position, uchar character, bool highNibble)
{
1187 1188
    if (!requestDataAt(position))
        return;
con's avatar
con committed
1189 1190 1191 1192 1193
    m_redoStack.clear();
    if (m_unmodifiedState > m_undoStack.size())
        m_unmodifiedState = -1;
    BinEditorEditCommand cmd;
    cmd.position = position;
1194
    cmd.character = (uchar) dataAt(position);
con's avatar
con committed
1195 1196 1197 1198 1199 1200 1201 1202
    cmd.highNibble = highNibble;

    if (!highNibble && !m_undoStack.isEmpty() && m_undoStack.top().position == position && m_undoStack.top().highNibble) {
        // compress
        cmd.character = m_undoStack.top().character;
        m_undoStack.pop();
    }

1203
    changeDataAt(position, (char) character);
con's avatar
con committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState);
    m_undoStack.push(cmd);
    if (emitModificationChanged) {
        emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
    }

    if (m_undoStack.size() == 1)
        emit undoAvailable(true);
}


void BinEditor::undo()
{
    if (m_undoStack.isEmpty())
        return;
    bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState);
    BinEditorEditCommand cmd = m_undoStack.pop();
    emitModificationChanged |= (m_undoStack.size() == m_unmodifiedState);
1222 1223
    uchar c = dataAt(cmd.position);
    changeDataAt(cmd.position, (char)cmd.character);
con's avatar
con committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    cmd.character = c;
    m_redoStack.push(cmd);
    setCursorPosition(cmd.position);
    if (emitModificationChanged)
        emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
    if (!m_undoStack.size())
        emit undoAvailable(false);
    if (m_redoStack.size() == 1)
        emit redoAvailable(true);
}

void BinEditor::redo()
{
    if (m_redoStack.isEmpty())
        return;
    BinEditorEditCommand cmd = m_redoStack.pop();
1240 1241
    uchar c = dataAt(cmd.position);
    changeDataAt(cmd.position, (char)cmd.character);
con's avatar
con committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    cmd.character = c;
    bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState);
    m_undoStack.push(cmd);
    setCursorPosition(cmd.position + 1);
    if (emitModificationChanged)
        emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
    if (m_undoStack.size() == 1)
        emit undoAvailable(true);
    if (!m_redoStack.size())
        emit redoAvailable(false);
}