debuggerengine.cpp 25.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** 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.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "debuggerengine.h"

#include "debuggeractions.h"
#include "debuggeragents.h"
#include "debuggerrunner.h"
#include "debuggeroutputwindow.h"
#include "debuggerplugin.h"
#include "debuggerstringutils.h"

#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "snapshothandler.h"
#include "sourcefileshandler.h"
#include "stackhandler.h"
#include "threadshandler.h"
#include "watchhandler.h"

hjk's avatar
hjk committed
48 49 50
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>

51 52 53 54 55 56 57 58 59 60
#include <projectexplorer/debugginghelper.h>
#include <projectexplorer/environment.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/applicationrunconfiguration.h> // For LocalApplication*

#include <qt4projectmanager/qt4projectmanagerconstants.h>

hjk's avatar
hjk committed
61 62
#include <texteditor/itexteditor.h>

63 64 65 66 67 68 69 70 71 72 73 74
#include <utils/savedaction.h>
#include <utils/qtcassert.h>

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTimer>

#include <QtGui/QAbstractItemView>
#include <QtGui/QStandardItemModel>
#include <QtGui/QAction>
#include <QtGui/QMessageBox>
hjk's avatar
hjk committed
75
#include <QtGui/QPlainTextEdit>
76
#include <QtGui/QPushButton>
hjk's avatar
hjk committed
77 78
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
79 80 81 82
#include <QtGui/QTextDocument>
#include <QtGui/QTreeWidget>


hjk's avatar
hjk committed
83
using namespace Core;
84 85
using namespace Debugger;
using namespace Debugger::Internal;
hjk's avatar
hjk committed
86 87
using namespace ProjectExplorer;
using namespace TextEditor;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166


///////////////////////////////////////////////////////////////////////
//
// DebuggerStartParameters
//
///////////////////////////////////////////////////////////////////////

DebuggerStartParameters::DebuggerStartParameters()
  : attachPID(-1),
    useTerminal(false),
    breakAtMain(false),
    toolChainType(ToolChain::UNKNOWN),
    startMode(NoStartMode)
{}

void DebuggerStartParameters::clear()
{
    *this = DebuggerStartParameters();
}


namespace Debugger {

QDebug operator<<(QDebug d, DebuggerState state)
{
    return d << DebuggerEngine::stateName(state) << '(' << int(state) << ')';
}

QDebug operator<<(QDebug str, const DebuggerStartParameters &sp)
{
    QDebug nospace = str.nospace();
    const QString sep = QString(QLatin1Char(','));
    nospace << "executable=" << sp.executable
            << " coreFile=" << sp.coreFile
            << " processArgs=" << sp.processArgs.join(sep)
            << " environment=<" << sp.environment.size() << " variables>"
            << " workingDir=" << sp.workingDirectory
            << " attachPID=" << sp.attachPID
            << " useTerminal=" << sp.useTerminal
            << " remoteChannel=" << sp.remoteChannel
            << " remoteArchitecture=" << sp.remoteArchitecture
            << " symbolFileName=" << sp.symbolFileName
            << " serverStartScript=" << sp.serverStartScript
            << " toolchain=" << sp.toolChainType << '\n';
    return str;
}


namespace Internal {

const char *DebuggerEngine::stateName(int s)
{
#    define SN(x) case x: return #x;
    switch (s) {
        SN(DebuggerNotReady)
        SN(EngineStarting)
        SN(AdapterStarting)
        SN(AdapterStarted)
        SN(AdapterStartFailed)
        SN(InferiorStarting)
        SN(InferiorStartFailed)
        SN(InferiorRunningRequested)
        SN(InferiorRunningRequested_Kill)
        SN(InferiorRunning)
        SN(InferiorUnrunnable)
        SN(InferiorStopping)
        SN(InferiorStopping_Kill)
        SN(InferiorStopped)
        SN(InferiorStopFailed)
        SN(InferiorShuttingDown)
        SN(InferiorShutDown)
        SN(InferiorShutdownFailed)
        SN(EngineShuttingDown)
    }
    return "<unknown>";
#    undef SN
}

167

168 169 170 171 172 173 174 175 176
//////////////////////////////////////////////////////////////////////
//
// CommandHandler
//
//////////////////////////////////////////////////////////////////////

class CommandHandler : public QStandardItemModel
{
public:
177
    explicit CommandHandler(DebuggerEngine *engine) : m_engine(engine) {}
178 179 180 181
    bool setData(const QModelIndex &index, const QVariant &value, int role);
    QAbstractItemModel *model() { return this; }

private:
182
    QPointer<DebuggerEngine> m_engine;
183 184
};

185
bool CommandHandler::setData(const QModelIndex &, const QVariant &value, int role)
186
{
187 188 189
    QTC_ASSERT(m_engine, return false);
    m_engine->handleCommand(role, value);
    return true;
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
}


//////////////////////////////////////////////////////////////////////
//
// DebuggerEnginePrivate
//
//////////////////////////////////////////////////////////////////////

class DebuggerEnginePrivate
{
public:
    DebuggerEnginePrivate(DebuggerEngine *engine, const DebuggerStartParameters &sp)
      : m_engine(engine),
        m_runControl(0),
        m_startParameters(sp),
        m_state(DebuggerNotReady),
        m_breakHandler(engine),
        m_commandHandler(engine),
        m_modulesHandler(engine),
        m_registerHandler(engine),
        m_snapshotHandler(engine),
        m_sourceFilesHandler(engine),
        m_stackHandler(engine),
        m_threadsHandler(engine),
        m_watchHandler(engine),
        m_disassemblerViewAgent(engine)
    {}

public:
    DebuggerEngine *m_engine; // Not owned.
    DebuggerRunControl *m_runControl;  // Not owned.

    DebuggerStartParameters m_startParameters;
    DebuggerState m_state;

    qint64 m_inferiorPid;

    BreakHandler m_breakHandler;
    CommandHandler m_commandHandler;
    ModulesHandler m_modulesHandler;
    RegisterHandler m_registerHandler;
    SnapshotHandler m_snapshotHandler;
    SourceFilesHandler m_sourceFilesHandler;
    StackHandler m_stackHandler;
    ThreadsHandler m_threadsHandler;
    WatchHandler m_watchHandler;
    DisassemblerViewAgent m_disassemblerViewAgent;
};


//////////////////////////////////////////////////////////////////////
//
// DebuggerEngine
//
//////////////////////////////////////////////////////////////////////

DebuggerEngine::DebuggerEngine(const DebuggerStartParameters &startParameters)
  : d(new DebuggerEnginePrivate(this, startParameters))
{
}

DebuggerEngine::~DebuggerEngine()
{
}

256
void DebuggerEngine::showStatusMessage(const QString &msg, int timeout) const
257
{
258
    showMessage(msg, StatusBar, timeout);
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

void DebuggerEngine::handleCommand(int role, const QVariant &value)
{
    //qDebug() << "COMMAND: " << role << value;

    switch (role) {
        case RequestLoadSessionDataRole:
            loadSessionData();
            break;

        case RequestSaveSessionDataRole:
            saveSessionData();
            break;

        case RequestReloadSourceFilesRole:
            reloadSourceFiles();
            break;

        case RequestReloadModulesRole:
            reloadModules();
            break;

        case RequestExecContinueRole:
            continueInferior();
            break;

        case RequestExecInterruptRole:
            interruptInferior();
            break;

        case RequestExecResetRole:
            //exec();
            break;

        case RequestExecStepRole:
            executeStepX();
            break;

        case RequestExecStepOutRole:
            executeStepOutX();
            break;

        case RequestExecNextRole:
            executeStepNextX();
            break;

        case RequestExecRunToLineRole:
hjk's avatar
hjk committed
307
            executeRunToLine();
308 309 310
            break;

        case RequestExecRunToFunctionRole:
hjk's avatar
hjk committed
311
            executeRunToFunction();
312 313 314 315 316 317 318
            break;

        case RequestExecReturnFromFunctionRole:
            executeReturnX();
            break;

        case RequestExecJumpToLineRole:
hjk's avatar
hjk committed
319
            executeJumpToLine();
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
            break;

        case RequestExecWatchRole:
            //exec();
            QTC_ASSERT(false, /* FIXME ABC */);
            break;

        case RequestExecExitRole:
            exitDebugger();
            break;

        case RequestExecSnapshotRole:
            makeSnapshot();
            break;

        case RequestExecFrameDownRole:
            frameDown();
            break;

        case RequestExecFrameUpRole:
            frameUp();
            break;

        case RequestOperatedByInstructionTriggeredRole:
            gotoLocation(stackHandler()->currentFrame(), true);
            break;

        case RequestExecuteCommandRole:
            executeDebuggerCommand(value.toString());
            break;
hjk's avatar
hjk committed
350 351 352 353 354 355

        case RequestWatchPointRole:
            //if (QAction *action = qobject_cast<QAction *>(sender()))
            //    watchPoint(action->data().toPoint());
            QTC_ASSERT(false, /* FIXME ABC */);
            break;
356 357 358
    }
}

359 360 361 362 363 364 365 366 367 368 369 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621

void DebuggerEngine::showModuleSymbols
    (const QString &moduleName, const Symbols &symbols)
{
    QTreeWidget *w = new QTreeWidget;
    w->setColumnCount(3);
    w->setRootIsDecorated(false);
    w->setAlternatingRowColors(true);
    w->setSortingEnabled(true);
    w->setHeaderLabels(QStringList() << tr("Symbol") << tr("Address") << tr("Code"));
    w->setWindowTitle(tr("Symbols in \"%1\"").arg(moduleName));
    foreach (const Symbol &s, symbols) {
        QTreeWidgetItem *it = new QTreeWidgetItem;
        it->setData(0, Qt::DisplayRole, s.name);
        it->setData(1, Qt::DisplayRole, s.address);
        it->setData(2, Qt::DisplayRole, s.state);
        w->addTopLevelItem(it);
    }
    plugin()->createNewDock(w);
}

void DebuggerEngine::frameUp()
{
    int currentIndex = stackHandler()->currentIndex();
    activateFrame(qMin(currentIndex + 1, stackHandler()->stackSize() - 1));
}

void DebuggerEngine::frameDown()
{
    int currentIndex = stackHandler()->currentIndex();
    activateFrame(qMax(currentIndex - 1, 0));
}

ModulesHandler *DebuggerEngine::modulesHandler() const
{
    return &d->m_modulesHandler;
}

BreakHandler *DebuggerEngine::breakHandler() const
{
    return &d->m_breakHandler;
}

RegisterHandler *DebuggerEngine::registerHandler() const
{
    return &d->m_registerHandler;
}

StackHandler *DebuggerEngine::stackHandler() const
{
    return &d->m_stackHandler;
}

ThreadsHandler *DebuggerEngine::threadsHandler() const
{
    return &d->m_threadsHandler;
}

WatchHandler *DebuggerEngine::watchHandler() const
{
    return &d->m_watchHandler;
}

SnapshotHandler *DebuggerEngine::snapshotHandler() const
{
    return &d->m_snapshotHandler;
}

SourceFilesHandler *DebuggerEngine::sourceFilesHandler() const
{
    return &d->m_sourceFilesHandler;
}

QAbstractItemModel *DebuggerEngine::modulesModel() const
{
    return d->m_modulesHandler.model();
}

QAbstractItemModel *DebuggerEngine::breakModel() const
{
    return d->m_breakHandler.model();
}

QAbstractItemModel *DebuggerEngine::registerModel() const
{
    return d->m_registerHandler.model();
}

QAbstractItemModel *DebuggerEngine::stackModel() const
{
    return d->m_stackHandler.model();
}

QAbstractItemModel *DebuggerEngine::threadsModel() const
{
    return d->m_threadsHandler.model();
}

QAbstractItemModel *DebuggerEngine::localsModel() const
{
    return d->m_watchHandler.model(LocalsWatch);
}

QAbstractItemModel *DebuggerEngine::watchersModel() const
{
    return d->m_watchHandler.model(WatchersWatch);
}

QAbstractItemModel *DebuggerEngine::returnModel() const
{
    return d->m_watchHandler.model(ReturnWatch);
}

QAbstractItemModel *DebuggerEngine::snapshotModel() const
{
    return d->m_snapshotHandler.model();
}

QAbstractItemModel *DebuggerEngine::sourceFilesModel() const
{
    return d->m_sourceFilesHandler.model();
}

QAbstractItemModel *DebuggerEngine::commandModel() const
{
    return d->m_commandHandler.model();
}

void DebuggerEngine::fetchMemory(MemoryViewAgent *, QObject *,
        quint64 addr, quint64 length)
{
    Q_UNUSED(addr);
    Q_UNUSED(length);
}

void DebuggerEngine::setRegisterValue(int regnr, const QString &value)
{
    Q_UNUSED(regnr);
    Q_UNUSED(value);
}

void DebuggerEngine::showMessage(const QString &msg, int channel, int timeout) const
{
    //qDebug() << channel << msg;
    d->m_runControl->showMessage(msg, channel);
    plugin()->showMessage(msg, channel, timeout);
}

void DebuggerEngine::startDebugger(DebuggerRunControl *runControl)
{
    QTC_ASSERT(runControl, startFailed(); return);
    QTC_ASSERT(!d->m_runControl, startFailed(); return);

    DebuggerEngine *sessionTemplate = plugin()->sessionTemplate();
    QTC_ASSERT(sessionTemplate, startFailed(); return);
    QTC_ASSERT(sessionTemplate != this, startFailed(); return);

    breakHandler()->initializeFromTemplate(sessionTemplate->breakHandler());

    d->m_runControl = runControl;

    QTC_ASSERT(state() == DebuggerNotReady, setState(DebuggerNotReady));

    d->m_inferiorPid = d->m_startParameters.attachPID > 0
        ? d->m_startParameters.attachPID : 0;

    if (d->m_startParameters.environment.empty())
        d->m_startParameters.environment = Environment().toStringList();

    if (d->m_startParameters.breakAtMain)
        breakByFunctionMain();

    const unsigned engineCapabilities = debuggerCapabilities();
    theDebuggerAction(OperateByInstruction)
        ->setEnabled(engineCapabilities & DisassemblerCapability);

    startDebugger();
}

void DebuggerEngine::breakByFunctionMain()
{
#ifdef Q_OS_WIN
    // FIXME: wrong on non-Qt based binaries
    emit breakByFunction("qMain");
#else
    emit breakByFunction("main");
#endif
}

void DebuggerEngine::breakByFunction(const QString &functionName)
{
    d->m_breakHandler.breakByFunction(functionName);
    attemptBreakpointSynchronization();
}

void DebuggerEngine::loadSessionData()
{
    d->m_breakHandler.loadSessionData();
    d->m_watchHandler.loadSessionData();
}

void DebuggerEngine::saveSessionData()
{
    d->m_breakHandler.saveSessionData();
    d->m_watchHandler.saveSessionData();
}

void DebuggerEngine::resetLocation()
{
    d->m_disassemblerViewAgent.resetLocation();
    d->m_stackHandler.setCurrentIndex(-1);
    plugin()->resetLocation();
}

void DebuggerEngine::gotoLocation(const QString &fileName, int lineNumber, bool setMarker)
{
    StackFrame frame;
    frame.file = fileName;
    frame.line = lineNumber;
    gotoLocation(frame, setMarker);
}

void DebuggerEngine::gotoLocation(const StackFrame &frame, bool setMarker)
{
    if (theDebuggerBoolSetting(OperateByInstruction) || !frame.isUsable()) {
        if (setMarker)
            plugin()->resetLocation();
        d->m_disassemblerViewAgent.setFrame(frame);
    } else {
        plugin()->gotoLocation(frame.file, frame.line, setMarker);
    }
}

void DebuggerEngine::executeStepX()
{
    resetLocation();
    if (theDebuggerBoolSetting(OperateByInstruction))
        executeStepI();
    else
        executeStep();
}

void DebuggerEngine::executeStepOutX()
{
    resetLocation();
    executeStepOut();
}

void DebuggerEngine::executeStepNextX()
{
    resetLocation();
    if (theDebuggerBoolSetting(OperateByInstruction))
        executeNextI();
    else
        executeNext();
}

void DebuggerEngine::executeReturnX()
{
    resetLocation();
    executeReturn();
}

hjk's avatar
hjk committed
622
static TextEditor::ITextEditor *currentTextEditor()
623
{
hjk's avatar
hjk committed
624 625 626 627 628
    EditorManager *editorManager = EditorManager::instance();
    if (!editorManager)
        return 0;
    Core::IEditor *editor = editorManager->currentEditor();
    return qobject_cast<ITextEditor*>(editor);
629 630
}

hjk's avatar
hjk committed
631
void DebuggerEngine::executeRunToLine()
632
{
hjk's avatar
hjk committed
633
    ITextEditor *textEditor = currentTextEditor();
634 635
    QTC_ASSERT(textEditor, return);
    QString fileName = textEditor->file()->fileName();
hjk's avatar
hjk committed
636 637
    if (fileName.isEmpty())
        return;
638
    int lineNumber = textEditor->currentLine();
hjk's avatar
hjk committed
639 640
    resetLocation();
    executeRunToLine(fileName, lineNumber);
641 642
}

hjk's avatar
hjk committed
643
void DebuggerEngine::executeRunToFunction()
644
{
hjk's avatar
hjk committed
645
    ITextEditor *textEditor = currentTextEditor();
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    QTC_ASSERT(textEditor, return);
    QString fileName = textEditor->file()->fileName();
    QPlainTextEdit *ed = qobject_cast<QPlainTextEdit*>(textEditor->widget());
    if (!ed)
        return;
    QTextCursor cursor = ed->textCursor();
    QString functionName = cursor.selectedText();
    if (functionName.isEmpty()) {
        const QTextBlock block = cursor.block();
        const QString line = block.text();
        foreach (const QString &str, line.trimmed().split('(')) {
            QString a;
            for (int i = str.size(); --i >= 0; ) {
                if (!str.at(i).isLetterOrNumber())
                    break;
                a = str.at(i) + a;
            }
            if (!a.isEmpty()) {
                functionName = a;
                break;
            }
        }
    }

hjk's avatar
hjk committed
670 671 672 673
    if (functionName.isEmpty())
        return;
    resetLocation();
    executeRunToFunction(functionName);
674 675
}

hjk's avatar
hjk committed
676
void DebuggerEngine::executeJumpToLine()
677
{
hjk's avatar
hjk committed
678
    ITextEditor *textEditor = currentTextEditor();
679 680 681
    QTC_ASSERT(textEditor, return);
    QString fileName = textEditor->file()->fileName();
    int lineNumber = textEditor->currentLine();
hjk's avatar
hjk committed
682 683 684
    if (fileName.isEmpty())
        return;
    executeJumpToLine(fileName, lineNumber);
685 686
}

687 688
// Called from RunControl.
void DebuggerEngine::handleFinished()
689 690 691 692 693
{
    modulesHandler()->removeAll();
    stackHandler()->removeAll();
    threadsHandler()->removeAll();
    watchHandler()->cleanup();
694 695

    DebuggerEngine *sessionTemplate = plugin()->sessionTemplate();
696 697
    QTC_ASSERT(sessionTemplate != this, /**/);
    breakHandler()->storeToTemplate(sessionTemplate->breakHandler());
698 699 700 701 702 703 704 705 706 707 708 709 710 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 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 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 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
}

const DebuggerStartParameters &DebuggerEngine::startParameters() const
{
    return d->m_startParameters;
}

DebuggerStartParameters &DebuggerEngine::startParameters()
{
    return d->m_startParameters;
}


//////////////////////////////////////////////////////////////////////
//
// Dumpers. "Custom dumpers" are a library compiled against the current
// Qt containing functions to evaluate values of Qt classes
// (such as QString, taking pointers to their addresses).
// The library must be loaded into the debuggee.
//
//////////////////////////////////////////////////////////////////////

bool DebuggerEngine::qtDumperLibraryEnabled() const
{
    return theDebuggerBoolSetting(UseDebuggingHelpers);
}

QStringList DebuggerEngine::qtDumperLibraryLocations() const
{
    if (theDebuggerAction(UseCustomDebuggingHelperLocation)->value().toBool()) {
        const QString customLocation =
            theDebuggerAction(CustomDebuggingHelperLocation)->value().toString();
        const QString location =
            tr("%1 (explicitly set in the Debugger Options)").arg(customLocation);
        return QStringList(location);
    }
    return d->m_startParameters.dumperLibraryLocations;
}

void DebuggerEngine::showQtDumperLibraryWarning(const QString &details)
{
    //QMessageBox dialog(d->m_mainWindow); // FIXME
    QMessageBox dialog;
    QPushButton *qtPref = dialog.addButton(tr("Open Qt preferences"),
        QMessageBox::ActionRole);
    QPushButton *helperOff = dialog.addButton(tr("Turn off helper usage"),
        QMessageBox::ActionRole);
    QPushButton *justContinue = dialog.addButton(tr("Continue anyway"),
        QMessageBox::AcceptRole);
    dialog.setDefaultButton(justContinue);
    dialog.setWindowTitle(tr("Debugging helper missing"));
    dialog.setText(tr("The debugger could not load the debugging helper library."));
    dialog.setInformativeText(tr(
        "The debugging helper is used to nicely format the values of some Qt "
        "and Standard Library data types. "
        "It must be compiled for each used Qt version separately. "
        "This can be done in the Qt preferences page by selecting a Qt installation "
        "and clicking on 'Rebuild' in the 'Debugging Helper' row."));
    if (!details.isEmpty())
        dialog.setDetailedText(details);
    dialog.exec();
    if (dialog.clickedButton() == qtPref) {
        Core::ICore::instance()->showOptionsDialog(
            _(Qt4ProjectManager::Constants::QT_SETTINGS_CATEGORY),
            _(Qt4ProjectManager::Constants::QTVERSION_SETTINGS_PAGE_ID));
    } else if (dialog.clickedButton() == helperOff) {
        theDebuggerAction(UseDebuggingHelpers)
            ->setValue(qVariantFromValue(false), false);
    }
}

QString DebuggerEngine::qtDumperLibraryName() const
{
    if (theDebuggerAction(UseCustomDebuggingHelperLocation)->value().toBool())
        return theDebuggerAction(CustomDebuggingHelperLocation)->value().toString();
    return startParameters().dumperLibrary;
}

DebuggerState DebuggerEngine::state() const
{
    return d->m_state;
}

static bool isAllowedTransition(int from, int to)
{
    switch (from) {
    case -1:
        return to == DebuggerNotReady;

    case DebuggerNotReady:
        return to == EngineStarting || to == DebuggerNotReady;

    case EngineStarting:
        return to == AdapterStarting || to == DebuggerNotReady;

    case AdapterStarting:
        return to == AdapterStarted || to == AdapterStartFailed;
    case AdapterStarted:
        return to == InferiorStarting || to == EngineShuttingDown;
    case AdapterStartFailed:
        return to == DebuggerNotReady;

    case InferiorStarting:
        return to == InferiorRunningRequested || to == InferiorStopped
            || to == InferiorStartFailed || to == InferiorUnrunnable;
    case InferiorStartFailed:
        return to == EngineShuttingDown;

    case InferiorRunningRequested:
        return to == InferiorRunning || to == InferiorStopped
            || to == InferiorRunningRequested_Kill;
    case InferiorRunningRequested_Kill:
        return to == InferiorRunning || to == InferiorStopped;
    case InferiorRunning:
        return to == InferiorStopping;

    case InferiorStopping:
        return to == InferiorStopped || to == InferiorStopFailed
            || to == InferiorStopping_Kill;
    case InferiorStopping_Kill:
        return to == InferiorStopped || to == InferiorStopFailed;
    case InferiorStopped:
        return to == InferiorRunningRequested || to == InferiorShuttingDown;
    case InferiorStopFailed:
        return to == EngineShuttingDown;

    case InferiorUnrunnable:
        return to == EngineShuttingDown;
    case InferiorShuttingDown:
        return to == InferiorShutDown || to == InferiorShutdownFailed;
    case InferiorShutDown:
        return to == EngineShuttingDown;
    case InferiorShutdownFailed:
        return to == EngineShuttingDown;

    case EngineShuttingDown:
        return to == DebuggerNotReady;
    }

    qDebug() << "UNKNOWN STATE:" << from;
    return false;
}

void DebuggerEngine::setState(DebuggerState state, bool forced)
{
    //qDebug() << "STATUS CHANGE: FROM " << stateName(d->m_state)
    //        << " TO " << stateName(state);

    QString msg = _("State changed from %1(%2) to %3(%4).")
     .arg(stateName(d->m_state)).arg(d->m_state).arg(stateName(state)).arg(state);
    //if (!((d->m_state == -1 && state == 0) || (d->m_state == 0 && state == 0)))
    //    qDebug() << msg;
    if (!forced && !isAllowedTransition(d->m_state, state))
        qDebug() << "UNEXPECTED STATE TRANSITION: " << msg;

    showMessage(msg, LogDebug);

    //resetLocation();
    if (state == d->m_state)
        return;

    d->m_state = state;

    plugin()->updateState(this);

    if (d->m_state == DebuggerNotReady) {
        saveSessionData();
        d->m_runControl->debuggingFinished();
    }
}

bool DebuggerEngine::debuggerActionsEnabled() const
{
    return debuggerActionsEnabled(d->m_state);
}

bool DebuggerEngine::debuggerActionsEnabled(DebuggerState state)
{
    switch (state) {
    case InferiorStarting:
    case InferiorRunningRequested:
    case InferiorRunning:
    case InferiorUnrunnable:
    case InferiorStopping:
    case InferiorStopped:
        return true;
    case DebuggerNotReady:
    case EngineStarting:
    case AdapterStarting:
    case AdapterStarted:
    case AdapterStartFailed:
    case InferiorStartFailed:
    case InferiorRunningRequested_Kill:
    case InferiorStopping_Kill:
    case InferiorStopFailed:
    case InferiorShuttingDown:
    case InferiorShutDown:
    case InferiorShutdownFailed:
    case EngineShuttingDown:
        break;
    }
    return false;
}

void DebuggerEngine::startFailed()
{
    // The concrete engines themselves are responsible for changing state.
    QTC_ASSERT(state() == DebuggerNotReady, setState(DebuggerNotReady));
    d->m_runControl->startFailed();
}

void DebuggerEngine::startSuccessful()
{
    d->m_runControl->startSuccessful();
}

void DebuggerEngine::notifyInferiorPid(qint64 pid)
{
    if (d->m_inferiorPid == pid)
        return;
    d->m_inferiorPid = pid;
    QTimer::singleShot(0, this, SLOT(raiseApplication()));
}

qint64 DebuggerEngine::inferiorPid() const
{
    return d->m_inferiorPid;
}

DebuggerPlugin *DebuggerEngine::plugin() const
{
    return DebuggerPlugin::instance();
}

void DebuggerEngine::raiseApplication()
{
    d->m_runControl->bringApplicationToForeground(d->m_inferiorPid);
}

void DebuggerEngine::openFile(const QString &fileName, int lineNumber)
{
    plugin()->gotoLocation(fileName, lineNumber, false);
}

bool DebuggerEngine::isReverseDebugging() const
{
    return plugin()->isReverseDebugging();
}

} // namespace Internal
} // namespace Debugger